Compare commits

16 Commits
Author SHA1 Message Date
pilnas 46f3b21a0b Merge remote-tracking branch 'origin/main' into mobile-app 2026-11-26 11:43:39 +01:00
GonnaHetzMe b402d9f92c backend: from to 2026-11-22 04:34:07 +01:00
GonnaHetzMe bbbbca95fa backend: versioned API 2026-11-22 04:09:46 +01:00
pilnas c4fe447d9d Přizpůsobení mobilního klienta změnám backendu 2026-11-19 16:03:00 +01:00
pilnas a1bf12ba72 Merge main into mobile-app 2026-11-19 15:48:34 +01:00
GonnaHetzMe 599237dd2c Add queued email and Firebase push delivery 2026-11-19 14:02:02 +01:00
GonnaHetzMe c96eb155ae Add SMTP email delivery and deployment config 2026-11-19 13:41:42 +01:00
GonnaHetzMe 28fc49ea39 Add category catalog management 2026-11-19 13:07:48 +01:00
GonnaHetzMe b1e0638979 backend: Add management statistics endpoints 2026-11-19 12:58:03 +01:00
pilnas 79772e10ce Napojení mobilního klienta na aktuální backend API 2026-11-19 12:34:20 +01:00
pilnas a65516b810 Merge remote-tracking branch 'origin/main' into mobile-app 2026-11-19 12:01:23 +01:00
GonnaHetzMe 1ff4a0a814 Add proposal workflow and voting API 2026-11-18 21:58:33 +01:00
GonnaHetzMe 9ca23a2c15 Add notification inbox and restrict email logging 2026-11-18 18:40:53 +01:00
GonnaHetzMe 33b6864d3b Merge pull request 'Implement issue reporting and workflows' (#28) from feature/backend-issue-reporting into main
Reviewed-on: #28
2026-11-18 18:33:46 +01:00
GonnaHetzMe b80ec57589 Implement issue reporting and workflows 2026-11-18 18:32:59 +01:00
GonnaHetzMe 6ad3d5bbaa Merge pull request 'Základní backend: migrace, autentizace JWT, role, Swagger' (#27) from feature/backend-zaklad into main
Reviewed-on: #27
2026-11-18 17:34:16 +01:00
86 changed files with 5142 additions and 338 deletions

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
**
!backend/Directory.Build.props
!backend/Directory.Packages.props
!backend/src/
!db/migrations/
backend/**/bin
backend/**/obj
**/.env
**/*.env
**/*.pem
**/*.pfx
+14 -6
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,23 +34,31 @@ 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
Vyžaduje .NET SDK 10. Unit testy: Vyžaduje .NET SDK 10. Unit testy:
```bash ```bash
dotnet test --solution backend/Helpdesk.sln dotnet run --project backend/tests/Helpdesk.UnitTests/Helpdesk.UnitTests.csproj
``` ```
## Mobilní aplikace ## Mobilní aplikace
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
{ {
@@ -0,0 +1,24 @@
using Helpdesk.Api.Infrastructure;
using Helpdesk.Application.Issues;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Api.Controllers;
[ApiController]
[Authorize]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
[Route(ApiRoutes.V1 + "/attachments")]
public sealed class AttachmentsController(IssueService issues) : ControllerBase
{
[HttpGet("{id:int}")]
[ProducesResponseType<FileStreamResult>(StatusCodes.Status200OK, "application/octet-stream")]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Download(int id, CancellationToken ct)
{
var file = await issues.DownloadAsync(id, ct);
Response.Headers["X-Content-Type-Options"] = "nosniff";
return File(file.Content, file.ContentType, file.FileName);
}
}
@@ -10,7 +10,7 @@ namespace Helpdesk.Api.Controllers;
/// <summary>Registrace, přihlášení a správa tokenů.</summary> /// <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();
}
}
@@ -0,0 +1,188 @@
using System.Globalization;
using System.Text.Json;
using Helpdesk.Api.Infrastructure;
using Helpdesk.Application.Common;
using Helpdesk.Application.Issues;
using Helpdesk.Domain.Issues;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.RateLimiting;
namespace Helpdesk.Api.Controllers;
[ApiController]
[Authorize]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
[Route(ApiRoutes.V1 + "/issues")]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public sealed class IssuesController(IssueService issues) : ControllerBase
{
// Pro popis o velikosti 65 535 bajtů ponechá prostor i při JSON escapování znaků.
private const int MaxJsonCreateBytes = 1024 * 1024;
[HttpGet]
public Task<PagedResult<IssueSummary>> List([FromQuery] IssueQuery query, CancellationToken ct) =>
issues.ListAsync(query, ct);
[HttpGet("{id:int}")]
public Task<IssueDetail> Get(int id, CancellationToken ct) => issues.GetAsync(id, ct);
[HttpPost]
[ReadIssueBodyManually]
[EnableRateLimiting(RateLimitPolicies.IssueWrites)]
[Consumes("application/json", "multipart/form-data")]
[RequestSizeLimit(AttachmentLimits.MaxRequestBytes)]
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)]
[ProducesResponseType<IssueDetail>(StatusCodes.Status201Created)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
public async Task<ActionResult<IssueDetail>> Create(CancellationToken ct)
{
CreateIssueRequest request;
AttachmentUpload[] uploads = [];
try
{
if (Request.HasFormContentType)
{
var form = await ReadFormAsync(ct);
request = new CreateIssueRequest(
form["title"].ToString(), form["description"].ToString(),
ReadId(form, "categoryId") ?? throw new BadRequestException("Kategorie je povinná."),
ReadId(form, "buildingId"), form["locationDetail"].ToString());
uploads = ReadUploads(form.Files);
}
else
{
if (Request.ContentType is null && Request.ContentLength is null or 0)
throw new BadRequestException("Vyplňte údaje závady.");
if (!Request.HasJsonContentType())
return Problem(statusCode: StatusCodes.Status415UnsupportedMediaType);
var contentType = Request.GetTypedHeaders().ContentType;
if (contentType is { Charset.HasValue: true, Encoding: null })
return Problem(statusCode: StatusCodes.Status415UnsupportedMediaType);
if (HttpContext.Features.Get<IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false } sizeLimit)
sizeLimit.MaxRequestBodySize = MaxJsonCreateBytes;
request = await Request.ReadFromJsonAsync<CreateIssueRequest>(ct)
?? throw new BadRequestException("Vyplňte údaje závady.");
}
}
catch (JsonException)
{
throw new BadRequestException("Neplatný formát požadavku.");
}
var result = await issues.CreateAsync(request, uploads, ct);
return CreatedAtAction(nameof(Get), new { id = result.Id }, result);
}
[HttpPut("{id:int}")]
public Task<IssueDetail> Edit(int id, EditIssueRequest request, CancellationToken ct) =>
issues.EditAsync(id, request, ct);
[HttpPost("{id:int}/assign")]
public Task<IssueDetail> Assign(int id, AssignIssueRequest request, CancellationToken ct) =>
issues.AssignAsync(id, request, ct);
[HttpPost("{id:int}/start")]
public Task<IssueDetail> Start(int id, IssueVersionRequest request, CancellationToken ct) =>
issues.TransitionAsync(id, IssueAction.StartWork, request.RowVersion, null, ct);
[HttpPost("{id:int}/submit-for-verification")]
public Task<IssueDetail> SubmitForVerification(int id, VerifyIssueRequest request, CancellationToken ct) =>
issues.TransitionAsync(id, IssueAction.SubmitForVerification, request.RowVersion, request.Note, ct);
[HttpPost("{id:int}/confirm")]
public Task<IssueDetail> Confirm(int id, IssueVersionRequest request, CancellationToken ct) =>
issues.TransitionAsync(id, IssueAction.Confirm, request.RowVersion, null, ct);
[HttpPost("{id:int}/reopen")]
public Task<IssueDetail> Reopen(int id, IssueReasonRequest request, CancellationToken ct) =>
issues.TransitionAsync(id, IssueAction.Reopen, request.RowVersion, request.Reason, ct);
[HttpPost("{id:int}/reject")]
public Task<IssueDetail> Reject(int id, IssueReasonRequest request, CancellationToken ct) =>
issues.TransitionAsync(id, IssueAction.Reject, request.RowVersion, request.Reason, ct);
[HttpGet("{id:int}/events")]
public Task<IReadOnlyList<IssueEventDto>> Events(int id, CancellationToken ct) => issues.GetEventsAsync(id, ct);
[HttpPost("{id:int}/comments")]
[EnableRateLimiting(RateLimitPolicies.IssueWrites)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
public Task<IssueEventDto> Comment(int id, CommentRequest request, CancellationToken ct) =>
issues.CommentAsync(id, request, ct);
[HttpPost("{id:int}/attachments")]
[ReadIssueBodyManually]
[EnableRateLimiting(RateLimitPolicies.IssueWrites)]
[Consumes("multipart/form-data")]
[RequestSizeLimit(AttachmentLimits.MaxRequestBytes)]
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
public async Task<ActionResult<IReadOnlyList<AttachmentDto>>> Upload(int id, CancellationToken ct)
{
if (!Request.HasFormContentType)
return Problem(statusCode: StatusCodes.Status415UnsupportedMediaType);
var attachments = await issues.AddAttachmentsAsync(id, async token =>
ReadUploads((await ReadFormAsync(token)).Files), ct);
return Ok(attachments);
}
private async Task<IFormCollection> ReadFormAsync(CancellationToken ct)
{
try
{
return await Request.ReadFormAsync(ct);
}
catch (InvalidDataException)
{
throw new BadRequestException("Neplatný formát požadavku.");
}
}
private static int? ReadId(IFormCollection form, string key)
{
var value = form[key].ToString();
if (string.IsNullOrWhiteSpace(value))
return null;
if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var id))
throw new BadRequestException($"Neplatná hodnota {key}.");
return id;
}
private static AttachmentUpload[] ReadUploads(IFormFileCollection files)
{
if (files.Count > AttachmentLimits.MaxFiles)
throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů.");
if (files.Any(file => file.Name != "files"))
throw new BadRequestException("Přílohy patří do pole files.");
return files.Select(file => new AttachmentUpload(file.FileName, file.Length, file.OpenReadStream)).ToArray();
}
}
internal sealed class ReadIssueBodyManuallyAttribute : Attribute, IResourceFilter
{
public void OnResourceExecuting(ResourceExecutingContext context)
{
context.ValueProviderFactories.RemoveType<FormValueProviderFactory>();
context.ValueProviderFactories.RemoveType<FormFileValueProviderFactory>();
context.ValueProviderFactories.RemoveType<JQueryFormValueProviderFactory>();
}
public void OnResourceExecuted(ResourceExecutedContext context) { }
}
@@ -0,0 +1,40 @@
using Helpdesk.Application.Common;
using Helpdesk.Api.Infrastructure;
using Helpdesk.Application.Notifications;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Api.Controllers;
[ApiController]
[Authorize]
[Route(ApiRoutes.V1 + "/notifications")]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
public sealed class NotificationsController(NotificationService notifications) : ControllerBase
{
[HttpGet]
public Task<PagedResult<NotificationDto>> List(
[FromQuery] bool unreadOnly = false, [FromQuery] int page = 1, [FromQuery] int pageSize = 20,
CancellationToken ct = default) => notifications.ListAsync(unreadOnly, page, pageSize, ct);
[HttpGet("unread-count")]
public Task<UnreadCountDto> CountUnread(CancellationToken ct) => notifications.CountUnreadAsync(ct);
[HttpPost("{id:int}/read")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
public async Task<IActionResult> MarkRead(int id, CancellationToken ct)
{
await notifications.MarkReadAsync(id, ct);
return NoContent();
}
[HttpPost("read-all")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> MarkAllRead(CancellationToken ct)
{
await notifications.MarkAllReadAsync(ct);
return NoContent();
}
}
@@ -0,0 +1,69 @@
using Helpdesk.Api.Infrastructure;
using Helpdesk.Application.Common;
using Helpdesk.Application.Proposals;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Api.Controllers;
[ApiController]
[Authorize]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
[Route(ApiRoutes.V1 + "/proposals")]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public sealed class ProposalsController(ProposalService proposals) : ControllerBase
{
/// <summary>Seznam návrhů s volitelným filtrem podle data podání.</summary>
/// <param name="query">Filtry, řazení a stránkování.</param>
/// <param name="from">Dolní hranice data podání včetně.</param>
/// <param name="to">Horní hranice data podání bez uvedeného okamžiku.</param>
/// <param name="ct">Token pro zrušení požadavku.</param>
[HttpGet]
public Task<PagedResult<ProposalSummary>> List([FromQuery] ProposalQuery query,
[FromQuery] DateTimeOffset? from, [FromQuery] DateTimeOffset? to, CancellationToken ct) =>
proposals.ListAsync(query, from, to, ct);
[HttpGet("{id:int}")]
public Task<ProposalDetail> Get(int id, CancellationToken ct) => proposals.GetAsync(id, ct);
[HttpPost]
[RequestSizeLimit(1024 * 1024)]
[ProducesResponseType<ProposalDetail>(StatusCodes.Status201Created)]
public async Task<ActionResult<ProposalDetail>> Create(SaveProposalRequest request, CancellationToken ct)
{
var proposal = await proposals.CreateAsync(request, ct);
return CreatedAtAction(nameof(Get), new { id = proposal.Id }, proposal);
}
[HttpPut("{id:int}")]
[RequestSizeLimit(1024 * 1024)]
public Task<ProposalDetail> Edit(int id, SaveProposalRequest request, CancellationToken ct) =>
proposals.EditAsync(id, request, ct);
[HttpPut("{id:int}/vote")]
[RequestSizeLimit(1024 * 1024)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> SetVote(int id, VoteRequest request, CancellationToken ct)
{
await proposals.SetVoteAsync(id, request.Value, ct);
return NoContent();
}
[HttpDelete("{id:int}/vote")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> RemoveVote(int id, CancellationToken ct)
{
await proposals.RemoveVoteAsync(id, ct);
return NoContent();
}
[HttpPost("{id:int}/status")]
[Authorize(Roles = Roles.Management)]
[RequestSizeLimit(1024 * 1024)]
public Task<ProposalDetail> ChangeStatus(int id, ChangeProposalStatusRequest request, CancellationToken ct) =>
proposals.ChangeStatusAsync(id, request, ct);
}
@@ -0,0 +1,61 @@
using System.ComponentModel.DataAnnotations;
using Helpdesk.Api.Infrastructure;
using Helpdesk.Application.Statistics;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Helpdesk.Api.Controllers;
/// <summary>Statistiky pro vedení školy. 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);
}
@@ -1,5 +1,7 @@
using Helpdesk.Application.Abstractions; using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Issues;
using Helpdesk.Application.Users; using Helpdesk.Application.Users;
using Helpdesk.Api.Infrastructure;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@@ -8,9 +10,9 @@ 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) : ControllerBase public sealed class UsersController(UserService users, ICurrentUser currentUser, IssueService issues) : ControllerBase
{ {
/// <summary>Můj profil.</summary> /// <summary>Můj profil.</summary>
[HttpGet("me")] [HttpGet("me")]
@@ -21,4 +23,11 @@ public sealed class UsersController(UserService users, ICurrentUser currentUser)
[ProducesResponseType<UserDto>(StatusCodes.Status200OK)] [ProducesResponseType<UserDto>(StatusCodes.Status200OK)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)] [ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
public Task<UserDto> UpdateMe(UpdateProfileRequest request, CancellationToken ct) => users.UpdateMeAsync(currentUser, request, ct); public Task<UserDto> UpdateMe(UpdateProfileRequest request, CancellationToken ct) => users.UpdateMeAsync(currentUser, request, ct);
/// <summary>Aktivní řešitelé s počtem otevřených závad.</summary>
[HttpGet("assignable")]
[Authorize(Roles = Roles.Management)]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
public Task<IReadOnlyList<AssignableUserDto>> GetAssignable(CancellationToken ct) => issues.GetAssignableAsync(ct);
} }
@@ -0,0 +1,6 @@
namespace Helpdesk.Api.Infrastructure;
internal static class ApiRoutes
{
public const string V1 = "api/v1";
}
@@ -21,6 +21,7 @@ internal sealed class AppExceptionHandler(IProblemDetailsService problemDetails)
Title = "Neplatná vstupní data.", Title = "Neplatná vstupní data.",
}, },
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message }, AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message },
BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode },
_ => null, _ => null,
}; };
@@ -42,4 +42,5 @@ public static class AuthenticationSetup
public static class RateLimitPolicies public static class RateLimitPolicies
{ {
public const string Auth = "auth"; public const string Auth = "auth";
public const string IssueWrites = "issue-writes";
} }
@@ -1,4 +1,7 @@
using Microsoft.OpenApi; using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
using Helpdesk.Api.Controllers;
using Helpdesk.Application.Issues;
namespace Helpdesk.Api.Infrastructure; namespace Helpdesk.Api.Infrastructure;
@@ -16,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
@@ -30,6 +33,7 @@ public static class SwaggerSetup
{ {
[new OpenApiSecuritySchemeReference(SchemeId, document)] = [], [new OpenApiSecuritySchemeReference(SchemeId, document)] = [],
}); });
options.OperationFilter<IssueRequestBody>();
var xml = Path.Combine(AppContext.BaseDirectory, "Helpdesk.Api.xml"); var xml = Path.Combine(AppContext.BaseDirectory, "Helpdesk.Api.xml");
if (File.Exists(xml)) if (File.Exists(xml))
@@ -38,3 +42,63 @@ public static class SwaggerSetup
return services; return services;
} }
} }
internal sealed class IssueRequestBody : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (context.MethodInfo.DeclaringType != typeof(IssuesController))
return;
var create = context.MethodInfo.Name == nameof(IssuesController.Create);
if (!create && context.MethodInfo.Name != nameof(IssuesController.Upload))
return;
var properties = new Dictionary<string, IOpenApiSchema>
{
["files"] = new OpenApiSchema
{
Type = JsonSchemaType.Array,
MinItems = 1,
MaxItems = AttachmentLimits.MaxFiles,
Items = new OpenApiSchema { Type = JsonSchemaType.String, Format = "binary" },
},
};
var required = new HashSet<string> { "files" };
if (create)
{
required = ["title", "description", "categoryId"];
properties["title"] = new OpenApiSchema { Type = JsonSchemaType.String, MaxLength = 200 };
properties["description"] = new OpenApiSchema { Type = JsonSchemaType.String };
properties["categoryId"] = new OpenApiSchema { Type = JsonSchemaType.Integer };
properties["buildingId"] = new OpenApiSchema { Type = JsonSchemaType.Integer };
properties["locationDetail"] = new OpenApiSchema { Type = JsonSchemaType.String, MaxLength = 255 };
}
var content = new Dictionary<string, OpenApiMediaType>
{
["multipart/form-data"] = new()
{
Schema = new OpenApiSchema
{
Type = JsonSchemaType.Object,
Required = required,
Properties = properties,
},
},
};
if (create)
{
content["application/json"] = new OpenApiMediaType
{
Schema = context.SchemaGenerator.GenerateSchema(typeof(CreateIssueRequest), context.SchemaRepository),
};
}
operation.RequestBody = new OpenApiRequestBody
{
Required = true,
Content = content,
};
}
}
+39 -3
View File
@@ -1,13 +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;
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>();
@@ -20,17 +30,43 @@ builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<AppExceptionHandler>(); builder.Services.AddExceptionHandler<AppExceptionHandler>();
builder.Services.AddHelpdeskSwagger(); builder.Services.AddHelpdeskSwagger();
// Ochrana /api/auth/* proti hádání hesel a zahlcení (kap. 10). 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).
builder.Services.AddRateLimiter(options => builder.Services.AddRateLimiter(options =>
{ {
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter( options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter(
http.Connection.RemoteIpAddress?.ToString() ?? "unknown", http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) })); _ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) }));
options.AddPolicy(RateLimitPolicies.IssueWrites, http => RateLimitPartition.GetSlidingWindowLimiter(
http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown",
_ => new SlidingWindowRateLimiterOptions
{
PermitLimit = 10,
Window = TimeSpan.FromMinutes(1),
SegmentsPerWindow = 6,
}));
}); });
var app = builder.Build(); var app = builder.Build();
if (!string.IsNullOrWhiteSpace(trustedProxy))
app.UseForwardedHeaders();
app.UseExceptionHandler(); app.UseExceptionHandler();
app.UseStatusCodePages(); app.UseStatusCodePages();
@@ -41,9 +77,9 @@ app.UseSwaggerUI(options =>
options.DocumentTitle = "Helpdesk API"; options.DocumentTitle = "Helpdesk API";
}); });
app.UseRateLimiter();
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.UseRateLimiter();
app.MapControllers(); app.MapControllers();
@@ -1,7 +1,12 @@
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.Notifications;
using Helpdesk.Domain.Proposals;
using Helpdesk.Domain.Users; using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
namespace Helpdesk.Application.Abstractions; namespace Helpdesk.Application.Abstractions;
@@ -12,8 +17,22 @@ public interface IAppDbContext
DbSet<Building> Buildings { get; } DbSet<Building> Buildings { get; }
DbSet<IssueCategory> IssueCategories { get; } DbSet<IssueCategory> IssueCategories { get; }
DbSet<ProposalCategory> ProposalCategories { get; } DbSet<ProposalCategory> ProposalCategories { get; }
DbSet<Issue> Issues { get; }
DbSet<IssueEvent> IssueEvents { get; }
IQueryable<IssueTiming> IssueTimings { get; }
DbSet<Attachment> Attachments { get; }
DbSet<Proposal> Proposals { get; }
DbSet<ProposalEvent> ProposalEvents { get; }
DbSet<ProposalVote> ProposalVotes { get; }
DbSet<ProposalScore> ProposalScores { get; }
DbSet<Notification> Notifications { get; }
DbSet<NotificationDelivery> NotificationDeliveries { get; }
DbSet<PushDevice> PushDevices { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default); Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct);
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
} }
public interface IPasswordHasher public interface IPasswordHasher
@@ -32,12 +32,17 @@ public sealed class AuthService(
?? throw new BadRequestException("Registrace je možná jen s univerzitním e-mailem."); ?? throw new BadRequestException("Registrace je možná jen s univerzitním e-mailem.");
var normalized = User.NormalizeEmail(request.Email); var normalized = User.NormalizeEmail(request.Email);
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, ct)) var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
if (user is null)
{
user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role);
db.Users.Add(user);
await db.SaveChangesAsync(ct);
}
else if (!user.IsActive || user.EmailConfirmed || !passwordHasher.Verify(request.Password, user.PasswordHash))
{
throw new ConflictException("Účet s tímto e-mailem už existuje."); throw new ConflictException("Účet s tímto e-mailem už existuje.");
}
var user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role);
db.Users.Add(user);
await db.SaveChangesAsync(ct);
await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct); await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
return UserDto.From(user); return UserDto.From(user);
@@ -123,8 +128,17 @@ public sealed class AuthService(
{ {
var normalized = User.NormalizeEmail(request.Email ?? ""); var normalized = User.NormalizeEmail(request.Email ?? "");
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized && u.IsActive, ct); var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized && u.IsActive, ct);
if (user is not null) if (user is null)
return;
try
{
await SendEmailTokenAsync(user, TokenType.PasswordReset, ct); await SendEmailTokenAsync(user, TokenType.PasswordReset, ct);
}
catch (EmailDeliveryException)
{
// SMTP zapisuje typ chyby. Odpověď na obnovu hesla zůstává pro všechny adresy stejná.
}
} }
public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct) public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct)
@@ -12,6 +12,8 @@ public sealed record CategoryDto(int Id, string Name, string? Description, bool
public sealed record SaveBuildingRequest(string Code, string Name, string? Address); public sealed record SaveBuildingRequest(string Code, string Name, string? Address);
public sealed record SaveCategoryRequest(string Name, string? Description);
public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildingRequest> public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildingRequest>
{ {
public SaveBuildingRequestValidator() public SaveBuildingRequestValidator()
@@ -22,8 +24,18 @@ public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildin
} }
} }
public sealed class SaveCategoryRequestValidator : AbstractValidator<SaveCategoryRequest>
{
public SaveCategoryRequestValidator()
{
RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
RuleFor(x => x.Description).MaximumLength(500);
}
}
/// <summary>Číselníky pro formuláře a jejich správa administrátorem. Mazání = deaktivace.</summary> /// <summary>Číselníky pro formuláře a jejich správa administrátorem. Mazání = deaktivace.</summary>
public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequest> buildingValidator) public sealed class CatalogService(
IAppDbContext db, IValidator<SaveBuildingRequest> buildingValidator, IValidator<SaveCategoryRequest> categoryValidator)
{ {
public async Task<IReadOnlyList<BuildingDto>> GetBuildingsAsync(bool includeInactive, CancellationToken ct) => public async Task<IReadOnlyList<BuildingDto>> GetBuildingsAsync(bool includeInactive, CancellationToken ct) =>
await db.Buildings.AsNoTracking() await db.Buildings.AsNoTracking()
@@ -32,16 +44,16 @@ public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequ
.Select(b => new BuildingDto(b.Id, b.Code, b.Name, b.Address, b.IsActive)) .Select(b => new BuildingDto(b.Id, b.Code, b.Name, b.Address, b.IsActive))
.ToListAsync(ct); .ToListAsync(ct);
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(CancellationToken ct) => public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(bool includeInactive, CancellationToken ct) =>
await db.IssueCategories.AsNoTracking() await db.IssueCategories.AsNoTracking()
.Where(c => c.IsActive) .Where(c => includeInactive || c.IsActive)
.OrderBy(c => c.Id) .OrderBy(c => c.Id)
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive)) .Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
.ToListAsync(ct); .ToListAsync(ct);
public async Task<IReadOnlyList<CategoryDto>> GetProposalCategoriesAsync(CancellationToken ct) => public async Task<IReadOnlyList<CategoryDto>> GetProposalCategoriesAsync(bool includeInactive, CancellationToken ct) =>
await db.ProposalCategories.AsNoTracking() await db.ProposalCategories.AsNoTracking()
.Where(c => c.IsActive) .Where(c => includeInactive || c.IsActive)
.OrderBy(c => c.Id) .OrderBy(c => c.Id)
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive)) .Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
.ToListAsync(ct); .ToListAsync(ct);
@@ -75,10 +87,68 @@ public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequ
await db.SaveChangesAsync(ct); await db.SaveChangesAsync(ct);
} }
public async Task<CategoryDto> CreateIssueCategoryAsync(SaveCategoryRequest request, CancellationToken ct)
{
await categoryValidator.ValidateAndThrowAsync(request, ct);
var category = new IssueCategory(request.Name, request.Description);
db.IssueCategories.Add(category);
await db.SaveChangesAsync(ct);
return ToDto(category);
}
public async Task<CategoryDto> UpdateIssueCategoryAsync(int id, SaveCategoryRequest request, CancellationToken ct)
{
await categoryValidator.ValidateAndThrowAsync(request, ct);
var category = await GetIssueCategoryAsync(id, ct);
category.Update(request.Name, request.Description);
await db.SaveChangesAsync(ct);
return ToDto(category);
}
public async Task DeactivateIssueCategoryAsync(int id, CancellationToken ct)
{
var category = await GetIssueCategoryAsync(id, ct);
category.Deactivate();
await db.SaveChangesAsync(ct);
}
public async Task<CategoryDto> CreateProposalCategoryAsync(SaveCategoryRequest request, CancellationToken ct)
{
await categoryValidator.ValidateAndThrowAsync(request, ct);
var category = new ProposalCategory(request.Name, request.Description);
db.ProposalCategories.Add(category);
await db.SaveChangesAsync(ct);
return ToDto(category);
}
public async Task<CategoryDto> UpdateProposalCategoryAsync(int id, SaveCategoryRequest request, CancellationToken ct)
{
await categoryValidator.ValidateAndThrowAsync(request, ct);
var category = await GetProposalCategoryAsync(id, ct);
category.Update(request.Name, request.Description);
await db.SaveChangesAsync(ct);
return ToDto(category);
}
public async Task DeactivateProposalCategoryAsync(int id, CancellationToken ct)
{
var category = await GetProposalCategoryAsync(id, ct);
category.Deactivate();
await db.SaveChangesAsync(ct);
}
private async Task<Building> GetBuildingAsync(int id, CancellationToken ct) => private async Task<Building> GetBuildingAsync(int id, CancellationToken ct) =>
await db.Buildings.SingleOrDefaultAsync(b => b.Id == id, ct) await db.Buildings.SingleOrDefaultAsync(b => b.Id == id, ct)
?? throw new NotFoundException($"Budova {id} neexistuje."); ?? throw new NotFoundException($"Budova {id} neexistuje.");
private async Task<IssueCategory> GetIssueCategoryAsync(int id, CancellationToken ct) =>
await db.IssueCategories.SingleOrDefaultAsync(c => c.Id == id, ct)
?? throw new NotFoundException($"Kategorie závad {id} neexistuje.");
private async Task<ProposalCategory> GetProposalCategoryAsync(int id, CancellationToken ct) =>
await db.ProposalCategories.SingleOrDefaultAsync(c => c.Id == id, ct)
?? throw new NotFoundException($"Kategorie návrhů {id} neexistuje.");
private async Task EnsureUniqueCodeAsync(string code, int? exceptId, CancellationToken ct) private async Task EnsureUniqueCodeAsync(string code, int? exceptId, CancellationToken ct)
{ {
var trimmed = code.Trim(); var trimmed = code.Trim();
@@ -87,4 +157,6 @@ public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequ
} }
private static BuildingDto ToDto(Building b) => new(b.Id, b.Code, b.Name, b.Address, b.IsActive); private static BuildingDto ToDto(Building b) => new(b.Id, b.Code, b.Name, b.Address, b.IsActive);
private static CategoryDto ToDto(IssueCategory c) => new(c.Id, c.Name, c.Description, c.IsActive);
private static CategoryDto ToDto(ProposalCategory c) => new(c.Id, c.Name, c.Description, c.IsActive);
} }
@@ -31,4 +31,12 @@ public sealed class BadRequestException(string message) : AppException(message)
public override int StatusCode => 400; public override int StatusCode => 400;
} }
public sealed class EmailDeliveryException(string reason, bool retryable)
: AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.")
{
public string Reason { get; } = reason;
public bool Retryable { get; } = retryable;
public override int StatusCode => 503;
}
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize); public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize);
@@ -1,6 +1,10 @@
using FluentValidation; using FluentValidation;
using Helpdesk.Application.Auth; using Helpdesk.Application.Auth;
using Helpdesk.Application.Catalogs; using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Issues;
using Helpdesk.Application.Notifications;
using Helpdesk.Application.Proposals;
using Helpdesk.Application.Statistics;
using Helpdesk.Application.Users; using Helpdesk.Application.Users;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@@ -18,6 +22,13 @@ public static class DependencyInjection
services.AddScoped<AuthService>(); services.AddScoped<AuthService>();
services.AddScoped<UserService>(); services.AddScoped<UserService>();
services.AddScoped<CatalogService>(); services.AddScoped<CatalogService>();
services.AddScoped<IssueService>();
services.AddScoped<NotificationService>();
services.AddScoped<NotificationDeliveryService>();
services.AddScoped<NotificationWriter>();
services.AddScoped<PushDeviceService>();
services.AddScoped<ProposalService>();
services.AddScoped<StatisticsService>();
return services; return services;
} }
} }
@@ -0,0 +1,85 @@
using System.ComponentModel.DataAnnotations;
using Helpdesk.Domain;
using Helpdesk.Domain.Issues;
namespace Helpdesk.Application.Issues;
public record CreateIssueRequest(
[Required, StringLength(200)] string Title,
[Required] string Description,
[Range(1, int.MaxValue)] int CategoryId,
[Range(1, int.MaxValue)] int? BuildingId,
[StringLength(255)] string? LocationDetail);
public sealed record EditIssueRequest(
string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail,
[Required, Range(0, int.MaxValue)] int? RowVersion)
: CreateIssueRequest(Title, Description, CategoryId, BuildingId, LocationDetail);
public sealed record AssignIssueRequest(
int AssigneeId, string? Priority, [Required, Range(0, int.MaxValue)] int? RowVersion);
public record IssueVersionRequest([Required, Range(0, int.MaxValue)] int? RowVersion);
public sealed record VerifyIssueRequest(int? RowVersion, string? Note) : IssueVersionRequest(RowVersion);
public sealed record IssueReasonRequest(int? RowVersion, string Reason) : IssueVersionRequest(RowVersion);
public sealed record CommentRequest(string Text);
public sealed class IssueQuery
{
public string? Status { get; init; }
public int? CategoryId { get; init; }
public int? BuildingId { get; init; }
public int? AssigneeId { get; init; }
public int? ReporterId { get; init; }
public DateTimeOffset? From { get; init; }
public DateTimeOffset? To { get; init; }
public string? Q { get; init; }
public bool Mine { get; init; }
public string? Sort { get; init; }
public int Page { get; init; } = 1;
public int PageSize { get; init; } = 20;
}
public sealed record IssueSummary(
int Id, string Title, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
string Priority, int ReporterId, int? AssigneeId, DateTime CreatedAt)
{
internal static IssueSummary From(Issue issue) => new(
issue.Id, issue.Title, issue.CategoryId, issue.BuildingId, issue.LocationDetail, issue.Status.ToCode(),
issue.Priority.ToCode(), issue.ReporterId, issue.AssigneeId, issue.CreatedAt);
}
public sealed record IssueDetail(
int Id, string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
string Priority, int ReporterId, int? AssigneeId, DateTime CreatedAt, int RowVersion,
IReadOnlyList<string> AllowedActions, IReadOnlyList<AttachmentDto> Attachments);
public sealed record IssueEventDto(
int Id, string EventType, string? FromStatus, string ToStatus, int ActorId, string ActorName, string? Note,
DateTime OccurredAt);
public sealed record AssignableUserDto(int Id, string FirstName, string LastName, string Role, int OpenIssues);
public sealed record AttachmentDto(int Id, string FileName, string ContentType, long SizeBytes, DateTime CreatedAt)
{
internal static AttachmentDto From(Attachment attachment) => new(
attachment.Id, attachment.OriginalFileName, attachment.ContentType, attachment.SizeBytes, attachment.CreatedAt);
}
public sealed record AttachmentUpload(string FileName, long SizeBytes, Func<Stream> OpenRead);
public sealed record StoredAttachment(string OriginalFileName, string StoredFileName, string ContentType, long SizeBytes);
public sealed record AttachmentDownload(Stream Content, string FileName, string ContentType);
public interface IAttachmentStore
{
Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct);
Stream OpenRead(string storedFileName);
void Delete(string storedFileName);
}
public static class AttachmentLimits
{
public const int MaxFiles = 5;
public const int MaxFileBytes = 10 * 1024 * 1024;
public const int MaxRequestBytes = MaxFiles * MaxFileBytes + 1024 * 1024;
}
@@ -0,0 +1,128 @@
using Helpdesk.Application.Common;
using Helpdesk.Domain;
using Helpdesk.Domain.Issues;
using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Issues;
public sealed partial class IssueService
{
public async Task<PagedResult<IssueSummary>> ListAsync(IssueQuery filters, CancellationToken ct)
{
var actor = await GetActorAsync(ct);
var issues = db.Issues.AsNoTracking();
if (filters.Mine || !Issue.CanReadAll(actor.Role))
issues = issues.Where(i => i.ReporterId == actor.Id);
if (filters.Status is { } statusCode)
{
var status = ParseCode<IssueStatus>(statusCode);
issues = issues.Where(i => i.Status == status);
}
if (filters.CategoryId is int categoryId)
issues = issues.Where(i => i.CategoryId == categoryId);
if (filters.BuildingId is int buildingId)
issues = issues.Where(i => i.BuildingId == buildingId);
if (filters.AssigneeId is int assigneeId)
issues = issues.Where(i => i.AssigneeId == assigneeId);
if (filters.ReporterId is int reporterId)
issues = issues.Where(i => i.ReporterId == reporterId);
if (filters.From >= filters.To)
throw new BadRequestException("Začátek období musí předcházet jeho konci.");
if (filters.From?.UtcDateTime is DateTime from)
issues = issues.Where(i => i.CreatedAt >= from);
if (filters.To?.UtcDateTime is DateTime to)
issues = issues.Where(i => i.CreatedAt < to);
if (!string.IsNullOrWhiteSpace(filters.Q))
{
var term = filters.Q.Trim();
issues = issues.Where(i => i.Title.Contains(term) || i.Description.Contains(term));
}
var ordered = filters.Sort switch
{
null or "newest" => issues.OrderByDescending(i => i.CreatedAt).ThenByDescending(i => i.Id),
"oldest" => issues.OrderBy(i => i.CreatedAt).ThenBy(i => i.Id),
_ => throw new BadRequestException("Řazení musí být newest nebo oldest."),
};
var page = Math.Max(1, filters.Page);
var pageSize = Math.Clamp(filters.PageSize, 1, 100);
var total = await issues.CountAsync(ct);
var offset = (long)(page - 1) * pageSize;
if (offset >= total)
return new PagedResult<IssueSummary>([], total, page, pageSize);
var pageItems = await ordered.Skip((int)offset).Take(pageSize).ToListAsync(ct);
return new PagedResult<IssueSummary>(pageItems.Select(IssueSummary.From).ToArray(), total, page, pageSize);
}
public async Task<IssueDetail> GetAsync(int id, CancellationToken ct)
{
var actor = await GetActorAsync(ct);
var issue = await LoadIssueAsync(id, actor, tracking: false, ct);
return await LoadDetailAsync(issue, actor, ct);
}
public async Task<IReadOnlyList<IssueEventDto>> GetEventsAsync(int id, CancellationToken ct)
{
var actor = await GetActorAsync(ct);
await LoadIssueAsync(id, actor, tracking: false, ct);
var entries = await (
from entry in db.IssueEvents.AsNoTracking()
join user in db.Users on entry.ActorId equals user.Id
where entry.IssueId == id
orderby entry.OccurredAt, entry.Id
select new { Entry = entry, user.FirstName, user.LastName }).ToListAsync(ct);
return entries.Select(entry => ToEvent(entry.Entry, $"{entry.FirstName} {entry.LastName}")).ToArray();
}
public async Task<IReadOnlyList<AssignableUserDto>> GetAssignableAsync(CancellationToken ct)
{
var actor = await GetActorAsync(ct);
if (actor.Role != UserRole.Management)
throw new ForbiddenException("Přehled řešitelů je určen vedení.");
var users = await db.Users.Where(u => u.IsActive && (u.Role == UserRole.Management || u.Role == UserRole.FacilityManager))
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
.Select(u => new
{
u.Id, u.FirstName, u.LastName, u.Role,
OpenIssues = db.Issues.Count(i => i.AssigneeId == u.Id &&
(i.Status == IssueStatus.Assigned || i.Status == IssueStatus.InProgress || i.Status == IssueStatus.PendingVerification)),
}).ToListAsync(ct);
return users.Select(u => new AssignableUserDto(u.Id, u.FirstName, u.LastName, u.Role.ToCode(), u.OpenIssues)).ToArray();
}
public async Task<AttachmentDownload> DownloadAsync(int id, CancellationToken ct)
{
var actor = await GetActorAsync(ct);
var attachment = await db.Attachments.AsNoTracking().Include(a => a.Issue).SingleOrDefaultAsync(a => a.Id == id, ct)
?? throw new NotFoundException("Příloha neexistuje.");
if (!attachment.Issue.CanRead(actor.Id, actor.Role))
throw new ForbiddenException("K příloze nemáte přístup.");
return new AttachmentDownload(files.OpenRead(attachment.StoredFileName), attachment.OriginalFileName, attachment.ContentType);
}
private async Task<IssueDetail> LoadDetailAsync(Issue issue, User actor, CancellationToken ct)
{
var attachments = await db.Attachments.AsNoTracking().Where(a => a.IssueId == issue.Id).OrderBy(a => a.Id)
.Select(a => new AttachmentDto(a.Id, a.OriginalFileName, a.ContentType, a.SizeBytes, a.CreatedAt)).ToListAsync(ct);
return ToDetail(issue, actor, attachments);
}
private static IssueDetail ToDetail(Issue issue, User actor, IReadOnlyList<AttachmentDto> attachments)
{
var actions = Enum.GetValues<IssueAction>()
.Where(action => issue.Availability(action, actor.Id, actor.Role) == IssueActionAvailability.Allowed)
.Select(action => action.ToCode()).ToArray();
return new IssueDetail(issue.Id, issue.Title, issue.Description, issue.CategoryId, issue.BuildingId, issue.LocationDetail,
issue.Status.ToCode(), issue.Priority.ToCode(), issue.ReporterId, issue.AssigneeId, issue.CreatedAt,
issue.RowVersion, actions, attachments);
}
private static IssueEventDto ToEvent(IssueEvent entry, string actorName) =>
new(entry.Id, entry.EventType.ToCode(), entry.FromStatus?.ToCode(), entry.ToStatus.ToCode(),
entry.ActorId, actorName, entry.Note, entry.OccurredAt);
}
@@ -0,0 +1,235 @@
using System.Text;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Application.Notifications;
using Helpdesk.Domain;
using Helpdesk.Domain.Issues;
using Helpdesk.Domain.Notifications;
using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Issues;
public sealed partial class IssueService(
IAppDbContext db, ICurrentUser currentUser, IAttachmentStore files, TimeProvider clock, NotificationWriter notificationWriter)
{
public async Task<IssueDetail> CreateAsync(CreateIssueRequest request, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
{
var actor = await GetActorAsync(ct);
await ValidateDetailsAsync(request, null, ct);
var issue = new Issue(actor.Id, request.Title, request.Description, request.CategoryId, request.BuildingId, request.LocationDetail);
db.Issues.Add(issue);
AddEvent(issue, IssueEventType.Created, null, actor, null);
var managementIds = await db.Users.Where(u => u.IsActive && u.Role == UserRole.Management)
.Select(u => u.Id).ToArrayAsync(ct);
await notificationWriter.ForIssueAsync(issue, actor.Id, managementIds, NotificationType.IssueCreated, "Nové hlášení závady", ct);
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
return ToDetail(issue, actor, attachments.Select(AttachmentDto.From).ToArray());
}
public async Task<IssueDetail> EditAsync(int id, EditIssueRequest request, CancellationToken ct)
{
var (issue, actor) = await LoadActionAsync(id, IssueAction.Edit, ct);
CheckVersion(issue, request.RowVersion);
await ValidateDetailsAsync(request, issue, ct);
issue.Edit(actor.Id, actor.Role, request.Title, request.Description, request.CategoryId, request.BuildingId, request.LocationDetail);
AddEvent(issue, IssueEventType.Updated, null, actor, null);
await SaveAsync(ct);
return await LoadDetailAsync(issue, actor, ct);
}
public async Task<IssueDetail> AssignAsync(int id, AssignIssueRequest request, CancellationToken ct)
{
var (issue, actor) = await LoadActionAsync(id, IssueAction.Assign, ct);
CheckVersion(issue, request.RowVersion);
var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct);
if (assignee is null || !Issue.CanBeAssigned(assignee.Role))
throw new BadRequestException("Vyberte aktivního správce budov nebo člena vedení.");
if (issue.AssigneeId == assignee.Id)
throw new ConflictException("Závada je již přiřazena tomuto řešiteli.");
IssuePriority? priority = request.Priority is null ? null : ParseCode<IssuePriority>(request.Priority);
var from = issue.Status;
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName);
await notificationWriter.ForIssueAsync(issue, actor.Id, [assignee.Id], NotificationType.IssueAssigned, "Závada byla přiřazena", ct);
if (from == IssueStatus.Received && issue.ReporterId != assignee.Id)
await notificationWriter.ForIssueAsync(issue, actor.Id, [issue.ReporterId], NotificationType.IssueStatusChanged, "Závada byla přiřazena", ct);
await SaveAsync(ct);
return await LoadDetailAsync(issue, actor, ct);
}
public async Task<IssueDetail> TransitionAsync(int id, IssueAction action, int? version, string? note, CancellationToken ct)
{
var (issue, actor) = await LoadActionAsync(id, action, ct);
CheckVersion(issue, version);
note = action is IssueAction.Reopen or IssueAction.Reject
? RequiredText(note, "Důvod", MaxTextBytes)
: OptionalText(note, "Poznámka", MaxTextBytes);
var from = issue.Status;
issue.Transition(action, actor.Id, actor.Role, note);
AddEvent(issue, IssueEventType.StatusChanged, from, actor, note);
int? recipient = action is IssueAction.Confirm or IssueAction.Reopen ? issue.AssigneeId : issue.ReporterId;
if (recipient is int recipientId)
{
var (type, title) = action == IssueAction.Reopen
? (NotificationType.IssueReopened, "Závada byla znovu otevřena")
: (NotificationType.IssueStatusChanged, "Stav závady se změnil");
await notificationWriter.ForIssueAsync(issue, actor.Id, [recipientId], type, title, ct);
}
await SaveAsync(ct);
return await LoadDetailAsync(issue, actor, ct);
}
public async Task<IssueEventDto> CommentAsync(int id, CommentRequest request, CancellationToken ct)
{
var (issue, actor) = await LoadActionAsync(id, IssueAction.Comment, ct);
var text = RequiredText(request.Text, "Komentář", MaxTextBytes);
issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role);
var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text);
int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId];
await notificationWriter.ForIssueAsync(issue, actor.Id, recipients, NotificationType.IssueCommentAdded, "Nový komentář k závadě", ct);
await SaveAsync(ct);
return ToEvent(entry, actor.FullName);
}
public async Task<IReadOnlyList<AttachmentDto>> AddAttachmentsAsync(
int id, Func<CancellationToken, Task<AttachmentUpload[]>> readUploads, CancellationToken ct)
{
var (issue, actor) = await LoadActionAsync(id, IssueAction.AddAttachments, ct);
var uploads = await readUploads(ct);
if (uploads.Length == 0)
throw new BadRequestException("Vyberte alespoň jeden soubor.");
issue.RecordParticipation(IssueAction.AddAttachments, actor.Id, actor.Role);
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
return attachments.Select(AttachmentDto.From).ToArray();
}
private async Task<IReadOnlyList<Attachment>> SaveWithAttachmentsAsync(
Issue issue, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
{
if (uploads.Count > AttachmentLimits.MaxFiles)
throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů.");
var attachments = new List<Attachment>(uploads.Count);
var saving = false;
try
{
foreach (var upload in uploads)
{
var stored = await files.SaveAsync(upload, ct);
var attachment = new Attachment(issue, stored.OriginalFileName, stored.StoredFileName,
stored.ContentType, stored.SizeBytes);
attachments.Add(attachment);
db.Attachments.Add(attachment);
}
ct.ThrowIfCancellationRequested();
saving = true;
await SaveAsync(ct);
return attachments;
}
catch (Exception exception) when (!saving || exception is ConflictException)
{
// Po chybě s neznámým výsledkem commitu soubory ponecháme, aby metadata nemohla odkazovat na smazaná data.
foreach (var attachment in attachments)
files.Delete(attachment.StoredFileName);
throw;
}
}
private async Task<User> GetActorAsync(CancellationToken ct) =>
await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == currentUser.Id && u.IsActive, ct)
?? throw new UnauthorizedException("Účet není aktivní.");
private async Task<Issue> LoadIssueAsync(int id, User actor, bool tracking, CancellationToken ct)
{
var query = tracking ? db.Issues : db.Issues.AsNoTracking();
var issue = await query.SingleOrDefaultAsync(i => i.Id == id, ct)
?? throw new NotFoundException("Závada neexistuje.");
if (!issue.CanRead(actor.Id, actor.Role))
throw new ForbiddenException("K závadě nemáte přístup.");
return issue;
}
private async Task<(Issue Issue, User Actor)> LoadActionAsync(int id, IssueAction action, CancellationToken ct)
{
var actor = await GetActorAsync(ct);
var issue = await LoadIssueAsync(id, actor, tracking: true, ct);
switch (issue.Availability(action, actor.Id, actor.Role))
{
case IssueActionAvailability.Forbidden:
throw new ForbiddenException("Tuto akci nemůžete provést.");
case IssueActionAvailability.InvalidState:
throw new ConflictException("Akce není v aktuálním stavu závady možná.");
}
return (issue, actor);
}
private async Task ValidateDetailsAsync(CreateIssueRequest request, Issue? original, CancellationToken ct)
{
var title = RequiredText(request.Title, "Název", MaxTextBytes);
RequiredText(request.Description, "Popis", MaxTextBytes);
if (title.Length > 200 || request.LocationDetail?.Trim().Length > 255)
throw new BadRequestException("Název smí mít nejvýše 200 znaků a upřesnění místa 255 znaků.");
if (original?.CategoryId != request.CategoryId &&
!await db.IssueCategories.AnyAsync(c => c.Id == request.CategoryId && c.IsActive, ct))
throw new BadRequestException("Vyberte aktivní kategorii závady.");
if (request.BuildingId is int buildingId && original?.BuildingId != buildingId &&
!await db.Buildings.AnyAsync(b => b.Id == buildingId && b.IsActive, ct))
throw new BadRequestException("Vyberte aktivní budovu.");
}
private IssueEvent AddEvent(Issue issue, IssueEventType type, IssueStatus? fromStatus, User actor, string? note)
{
var entry = new IssueEvent(issue, type, fromStatus, actor.Id, note, clock.GetUtcNow().UtcDateTime);
db.IssueEvents.Add(entry);
return entry;
}
private async Task SaveAsync(CancellationToken ct)
{
try
{
await db.SaveChangesAsync(ct);
}
catch (DbUpdateConcurrencyException)
{
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
}
}
private static void CheckVersion(Issue issue, int? supplied)
{
if (supplied is null or < 0)
throw new BadRequestException("Zadejte platnou hodnotu rowVersion.");
if (issue.RowVersion != supplied)
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
}
private const int MaxTextBytes = 65_535;
private static string RequiredText(string? input, string name, int maxBytes) =>
OptionalText(input, name, maxBytes) ?? throw new BadRequestException($"{name}: hodnota je povinná.");
private static string? OptionalText(string? input, string name, int maxBytes)
{
var text = input?.Trim();
if (string.IsNullOrEmpty(text))
return null;
if (Encoding.UTF8.GetByteCount(text) > maxBytes)
throw new BadRequestException($"{name}: hodnota je příliš dlouhá.");
return text;
}
private static T ParseCode<T>(string code) where T : struct, Enum =>
EnumCode.TryParse<T>(code, out var result)
? result
: throw new BadRequestException($"Neplatný kód '{code}'.");
}
@@ -0,0 +1,53 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Domain;
using Helpdesk.Domain.Notifications;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Notifications;
public sealed record NotificationDeliveryDto(
int Id, int NotificationId, string Channel, string Status, int AttemptCount,
string? LastError, DateTime? NextAttemptAt, DateTime? SentAt);
public sealed class NotificationDeliveryService(IAppDbContext db, TimeProvider clock)
{
public async Task<PagedResult<NotificationDeliveryDto>> ListAsync(string status, int page, int pageSize, CancellationToken ct)
{
if (!EnumCode.TryParse<DeliveryStatus>(status, out var deliveryStatus))
throw new BadRequestException("Neplatný stav doručení.");
page = Math.Max(1, page);
pageSize = Math.Clamp(pageSize, 1, 100);
var query = db.NotificationDeliveries.AsNoTracking().Where(d => d.Status == deliveryStatus);
var count = await query.CountAsync(ct);
var offset = (long)(page - 1) * pageSize;
if (offset >= count)
return new PagedResult<NotificationDeliveryDto>([], count, page, pageSize);
var rows = await query.OrderByDescending(d => d.Id).Skip((int)offset).Take(pageSize).ToListAsync(ct);
var items = rows.Select(d => new NotificationDeliveryDto(d.Id, d.NotificationId, d.Channel.ToCode(),
d.Status.ToCode(), d.AttemptCount, d.LastError, d.NextAttemptAt, d.SentAt)).ToArray();
return new PagedResult<NotificationDeliveryDto>(items, count, page, pageSize);
}
public async Task RetryAsync(int id, CancellationToken ct)
{
var now = clock.GetUtcNow().UtcDateTime;
var delivery = db.NotificationDeliveries.Where(d => d.Id == id);
var updated = await delivery.Where(d => d.Status == DeliveryStatus.Failed)
.ExecuteUpdateAsync(setters => setters
.SetProperty(d => d.Status, DeliveryStatus.Pending)
.SetProperty(d => d.AttemptCount, 0)
.SetProperty(d => d.NextAttemptAt, now)
.SetProperty(d => d.LastError, (string?)null)
.SetProperty(d => d.SentAt, (DateTime?)null), ct);
if (updated == 1)
return;
if (!await delivery.AnyAsync(ct))
throw new NotFoundException("Doručení neexistuje.");
throw new ConflictException("Zopakovat lze pouze neúspěšné doručení.");
}
}
@@ -0,0 +1,61 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Domain;
using Helpdesk.Domain.Notifications;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Notifications;
public sealed record NotificationDto(
int Id, string Type, string Title, string Message, int? IssueId, int? ProposalId, DateTime CreatedAt, DateTime? ReadAt);
public sealed record UnreadCountDto(int Count);
public sealed class NotificationService(IAppDbContext db, ICurrentUser currentUser, TimeProvider clock)
{
public async Task<PagedResult<NotificationDto>> ListAsync(bool unreadOnly, int page, int pageSize, CancellationToken ct)
{
page = Math.Max(1, page);
pageSize = Math.Clamp(pageSize, 1, 100);
var query = Inbox().AsNoTracking();
if (unreadOnly)
query = query.Where(n => n.ReadAt == null);
var total = await query.CountAsync(ct);
var offset = (long)(page - 1) * pageSize;
if (offset >= total)
return new PagedResult<NotificationDto>([], total, page, pageSize);
var rows = await query.OrderByDescending(n => n.CreatedAt).ThenByDescending(n => n.Id)
.Skip((int)offset).Take(pageSize).ToListAsync(ct);
var items = rows.Select(n => new NotificationDto(
n.Id, n.Type.ToCode(), n.Title, n.Message, n.IssueId, n.ProposalId, n.CreatedAt, n.ReadAt)).ToArray();
return new PagedResult<NotificationDto>(items, total, page, pageSize);
}
public async Task<UnreadCountDto> CountUnreadAsync(CancellationToken ct) =>
new(await Inbox().CountAsync(n => n.ReadAt == null, ct));
public async Task MarkReadAsync(int id, CancellationToken ct)
{
var match = Inbox().Where(n => n.Id == id);
if (await MarkUnreadRowsAsync(match, ct) == 0 && !await match.AnyAsync(ct))
throw new NotFoundException("Notifikace neexistuje.");
}
public async Task MarkAllReadAsync(CancellationToken ct) => await MarkUnreadRowsAsync(Inbox(), ct);
private IQueryable<Notification> Inbox()
{
var userId = currentUser.Id;
return db.Notifications.Where(n => n.UserId == userId);
}
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
{
var now = clock.GetUtcNow().UtcDateTime;
return query.Where(n => n.ReadAt == null)
.ExecuteUpdateAsync(update => update.SetProperty(n => n.ReadAt, now), ct);
}
}
@@ -0,0 +1,52 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Domain.Issues;
using Helpdesk.Domain.Notifications;
using Helpdesk.Domain.Proposals;
using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Notifications;
/// <summary>Připraví notifikace a záznamy outboxu pro uložení spolu s událostí.</summary>
public sealed class NotificationWriter(IAppDbContext db, TimeProvider clock)
{
public Task ForIssueAsync(Issue issue, int actorId, int[] recipientIds, NotificationType type, string title,
CancellationToken ct)
{
var reporterId = issue.ReporterId;
var eligibleUsers = db.Users.Where(u =>
u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management);
return QueueAsync(eligibleUsers, actorId, recipientIds,
id => new Notification(issue, id, type, title, issue.Title), ct);
}
public Task ForProposalStatusAsync(Proposal proposal, int actorId, CancellationToken ct) =>
QueueAsync(db.Users, actorId, [proposal.AuthorId],
id => new Notification(proposal, id, "Stav návrhu se změnil"), ct);
private async Task QueueAsync(IQueryable<User> eligibleUsers, int actorId, int[] recipientIds,
Func<int, Notification> create, CancellationToken ct)
{
var ids = recipientIds.Where(id => id != actorId).Distinct().ToArray();
if (ids.Length == 0)
return;
var recipients = await eligibleUsers.Where(u => u.IsActive && ids.Contains(u.Id))
.Select(u => new
{
u.Id,
Email = u.EmailNotificationsEnabled && u.EmailConfirmed,
Push = db.PushDevices.Any(device => device.UserId == u.Id),
}).ToListAsync(ct);
var now = clock.GetUtcNow().UtcDateTime;
foreach (var recipient in recipients)
{
var notification = create(recipient.Id);
db.Notifications.Add(notification);
db.NotificationDeliveries.AddRange(
new NotificationDelivery(notification, DeliveryChannel.Email, recipient.Email, now),
new NotificationDelivery(notification, DeliveryChannel.Push, recipient.Push, now));
}
}
}
@@ -0,0 +1,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í.");
}
}
@@ -0,0 +1,29 @@
namespace Helpdesk.Application.Proposals;
public sealed record SaveProposalRequest(string Title, string Description, int CategoryId);
public sealed record ChangeProposalStatusRequest(string Status, string? Note);
public sealed record VoteRequest(int Value);
public sealed class ProposalQuery
{
public string? Status { get; init; }
public int? CategoryId { get; init; }
public int? AuthorId { get; init; }
public string? Q { get; init; }
public string? Sort { get; init; }
public int Page { get; init; } = 1;
public int PageSize { get; init; } = 20;
}
public record ProposalSummary(
int Id, string Title, int CategoryId, int AuthorId, string Status, DateTime CreatedAt,
long VotesFor, long VotesAgainst, long Score, int? MyVote);
public sealed record ProposalDetail(
int Id, string Title, int CategoryId, int AuthorId, string Status, DateTime CreatedAt,
long VotesFor, long VotesAgainst, long Score, int? MyVote, string Description, IReadOnlyList<ProposalEventDto> Events)
: ProposalSummary(Id, Title, CategoryId, AuthorId, Status, CreatedAt, VotesFor, VotesAgainst, Score, MyVote);
public sealed record ProposalEventDto(
int Id, string EventType, string? FromStatus, string ToStatus, int ActorId, string ActorName, string? Note,
DateTime OccurredAt);
@@ -0,0 +1,111 @@
using Helpdesk.Application.Common;
using Helpdesk.Domain;
using Helpdesk.Domain.Proposals;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Proposals;
public sealed partial class ProposalService
{
public async Task<PagedResult<ProposalSummary>> ListAsync(
ProposalQuery filters, DateTimeOffset? from, DateTimeOffset? to, CancellationToken ct)
{
await GetActorRoleAsync(ct);
var proposals = db.Proposals.AsNoTracking();
if (filters.Status is { } code)
{
var status = ParseStatus(code);
proposals = proposals.Where(p => p.Status == status);
}
if (filters.CategoryId is int categoryId)
proposals = proposals.Where(p => p.CategoryId == categoryId);
if (filters.AuthorId is int authorId)
proposals = proposals.Where(p => p.AuthorId == authorId);
if (from >= to)
throw new BadRequestException("Začátek období musí předcházet jeho konci.");
if (from?.UtcDateTime is DateTime fromUtc)
proposals = proposals.Where(p => p.CreatedAt >= fromUtc);
if (to?.UtcDateTime is DateTime toUtc)
proposals = proposals.Where(p => p.CreatedAt < toUtc);
if (!string.IsNullOrWhiteSpace(filters.Q))
{
var term = filters.Q.Trim();
proposals = proposals.Where(p => p.Title.Contains(term) || p.Description.Contains(term));
}
var rows = WithScores(proposals);
var ordered = filters.Sort switch
{
null or "newest" => rows.OrderByDescending(r => r.Proposal.CreatedAt).ThenByDescending(r => r.Proposal.Id),
"score" => rows.OrderByDescending(r => r.Score).ThenByDescending(r => r.Proposal.CreatedAt)
.ThenByDescending(r => r.Proposal.Id),
_ => throw new BadRequestException("Řazení musí být newest nebo score."),
};
var page = Math.Max(1, filters.Page);
var pageSize = Math.Clamp(filters.PageSize, 1, 100);
var total = await proposals.CountAsync(ct);
var offset = (long)(page - 1) * pageSize;
if (offset >= total)
return new PagedResult<ProposalSummary>([], total, page, pageSize);
var pageRows = await ordered.Skip((int)offset).Take(pageSize).ToListAsync(ct);
return new PagedResult<ProposalSummary>(pageRows.Select(ToSummary).ToArray(), total, page, pageSize);
}
public async Task<ProposalDetail> GetAsync(int id, CancellationToken ct)
{
await GetActorRoleAsync(ct);
return await LoadDetailAsync(id, ct);
}
private async Task<ProposalDetail> LoadDetailAsync(int id, CancellationToken ct)
{
var row = await WithScores(db.Proposals.AsNoTracking().Where(p => p.Id == id)).SingleOrDefaultAsync(ct)
?? throw new NotFoundException("Návrh neexistuje.");
var entries = await (
from entry in db.ProposalEvents.AsNoTracking()
join actor in db.Users on entry.ActorId equals actor.Id
where entry.ProposalId == id
orderby entry.OccurredAt, entry.Id
select new { Entry = entry, actor.FirstName, actor.LastName }).ToListAsync(ct);
var events = entries.Select(e => new ProposalEventDto(
e.Entry.Id, e.Entry.EventType.ToCode(), e.Entry.FromStatus?.ToCode(), e.Entry.ToStatus.ToCode(),
e.Entry.ActorId, $"{e.FirstName} {e.LastName}", e.Entry.Note, e.Entry.OccurredAt)).ToArray();
var summary = ToSummary(row);
return new ProposalDetail(summary.Id, summary.Title, summary.CategoryId, summary.AuthorId, summary.Status,
summary.CreatedAt, summary.VotesFor, summary.VotesAgainst, summary.Score, summary.MyVote, row.Proposal.Description, events);
}
private IQueryable<ScoredProposal> WithScores(IQueryable<Proposal> proposals)
{
var actorId = currentUser.Id;
return from proposal in proposals
join score in db.ProposalScores on proposal.Id equals score.ProposalId
select new ScoredProposal
{
Proposal = proposal,
VotesFor = score.VotesFor,
VotesAgainst = score.VotesAgainst,
Score = score.Score,
MyVote = db.ProposalVotes.Where(v => v.ProposalId == proposal.Id && v.UserId == actorId)
.Select(v => (sbyte?)v.Value).FirstOrDefault(),
};
}
private static ProposalSummary ToSummary(ScoredProposal row)
{
var proposal = row.Proposal;
return new ProposalSummary(proposal.Id, proposal.Title, proposal.CategoryId, proposal.AuthorId,
proposal.Status.ToCode(), proposal.CreatedAt, (long)row.VotesFor, (long)row.VotesAgainst, (long)row.Score, row.MyVote);
}
private sealed class ScoredProposal
{
public required Proposal Proposal { get; init; }
public decimal VotesFor { get; init; }
public decimal VotesAgainst { get; init; }
public decimal Score { get; init; }
public sbyte? MyVote { get; init; }
}
}
@@ -0,0 +1,156 @@
using System.Text;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Application.Notifications;
using Helpdesk.Domain;
using Helpdesk.Domain.Proposals;
using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Proposals;
public sealed partial class ProposalService(
IAppDbContext db, ICurrentUser currentUser, NotificationWriter notifications, TimeProvider clock)
{
private const int MaxTextBytes = 65_535;
public async Task<ProposalDetail> CreateAsync(SaveProposalRequest request, CancellationToken ct)
{
await GetActorRoleAsync(ct);
var (title, description) = ValidateDetails(request);
await RequireActiveCategoryAsync(request.CategoryId, ct);
var proposal = new Proposal(currentUser.Id, title, description, request.CategoryId);
db.Proposals.Add(proposal);
AddEvent(proposal, ProposalEventType.Created);
await db.SaveChangesAsync(ct);
return await LoadDetailAsync(proposal.Id, ct);
}
public async Task<ProposalDetail> EditAsync(int id, SaveProposalRequest request, CancellationToken ct)
{
await GetActorRoleAsync(ct);
var (title, description) = ValidateDetails(request);
await using (var transaction = await db.BeginProposalWriteAsync(ct))
{
var proposal = await LockProposalAsync(id, ct);
if (!proposal.IsAuthor(currentUser.Id))
throw new ForbiddenException("Návrh může upravit jen jeho autor.");
if (!proposal.IsEditable)
throw new ConflictException("Návrh lze upravit jen ve stavu Podán.");
if (proposal.CategoryId != request.CategoryId)
await RequireActiveCategoryAsync(request.CategoryId, ct);
proposal.Edit(currentUser.Id, title, description, request.CategoryId);
AddEvent(proposal, ProposalEventType.Updated);
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
}
return await LoadDetailAsync(id, ct);
}
public async Task<ProposalDetail> ChangeStatusAsync(int id, ChangeProposalStatusRequest request, CancellationToken ct)
{
var role = await GetActorRoleAsync(ct);
if (role != UserRole.Management)
throw new ForbiddenException("Stav návrhu může změnit jen vedení školy.");
var target = ParseStatus(request.Status);
var note = string.IsNullOrWhiteSpace(request.Note) ? null : request.Note.Trim();
if (target == ProposalStatus.Rejected && note is null)
throw new BadRequestException("Zamítnutí vyžaduje vyjádření.");
if (note is not null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes)
throw new BadRequestException("Vyjádření je příliš dlouhé.");
await using (var transaction = await db.BeginProposalWriteAsync(ct))
{
var proposal = await LockProposalAsync(id, ct);
var previous = proposal.Status;
if (!proposal.CanTransitionTo(target))
throw new ConflictException("Přechod do požadovaného stavu není povolen.");
proposal.ChangeStatus(target, role, note);
AddEvent(proposal, ProposalEventType.StatusChanged, previous, note);
await notifications.ForProposalStatusAsync(proposal, currentUser.Id, ct);
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
}
return await LoadDetailAsync(id, ct);
}
public Task SetVoteAsync(int id, int value, CancellationToken ct)
{
if (value is not (1 or -1))
throw new BadRequestException("Hlas musí mít hodnotu 1 nebo -1.");
return ChangeVoteAsync(id, (sbyte)value, ct);
}
public Task RemoveVoteAsync(int id, CancellationToken ct) => ChangeVoteAsync(id, null, ct);
private async Task ChangeVoteAsync(int id, sbyte? value, CancellationToken ct)
{
await GetActorRoleAsync(ct);
var actorId = currentUser.Id;
await using var transaction = await db.BeginProposalWriteAsync(ct);
var proposal = await LockProposalAsync(id, ct);
if (proposal.IsAuthor(actorId))
throw new ForbiddenException("Autor nemůže hlasovat o vlastním návrhu.");
if (!proposal.IsVotingOpen)
throw new ConflictException("Hlasování je uzavřeno.");
var vote = await db.ProposalVotes.SingleOrDefaultAsync(v => v.ProposalId == id && v.UserId == actorId, ct);
if (value is sbyte newValue)
{
var now = clock.GetUtcNow().UtcDateTime;
if (vote is null)
db.ProposalVotes.Add(new ProposalVote(proposal, actorId, newValue, now));
else
vote.SetValue(proposal, newValue, now);
}
else if (vote is not null)
{
db.ProposalVotes.Remove(vote);
}
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
}
private async Task<UserRole> GetActorRoleAsync(CancellationToken ct)
{
var id = currentUser.Id;
return await db.Users.Where(u => u.Id == id && u.IsActive).Select(u => (UserRole?)u.Role).SingleOrDefaultAsync(ct)
?? throw new UnauthorizedException("Účet není aktivní.");
}
private async Task<Proposal> LockProposalAsync(int id, CancellationToken ct) =>
await db.LockProposalAsync(id, ct) ?? throw new NotFoundException("Návrh neexistuje.");
private async Task RequireActiveCategoryAsync(int id, CancellationToken ct)
{
if (!await db.ProposalCategories.AnyAsync(c => c.Id == id && c.IsActive, ct))
throw new BadRequestException("Vyberte aktivní oblast návrhu.");
}
private static (string Title, string Description) ValidateDetails(SaveProposalRequest request)
{
var title = request.Title?.Trim();
var description = request.Description?.Trim();
if (string.IsNullOrEmpty(title) || title.Length > 200)
throw new BadRequestException("Název návrhu musí mít 1 až 200 znaků.");
if (string.IsNullOrEmpty(description) || Encoding.UTF8.GetByteCount(description) > MaxTextBytes)
throw new BadRequestException("Vyplňte popis návrhu v povolené délce.");
return (title, description);
}
private void AddEvent(Proposal proposal, ProposalEventType type, ProposalStatus? previous = null, string? note = null) =>
db.ProposalEvents.Add(new ProposalEvent(proposal, type, previous, currentUser.Id, note, clock.GetUtcNow().UtcDateTime));
private static ProposalStatus ParseStatus(string status) =>
EnumCode.TryParse<ProposalStatus>(status, out var value)
? value
: throw new BadRequestException("Neplatný stav návrhu.");
}
@@ -0,0 +1,26 @@
using Helpdesk.Application.Common;
namespace Helpdesk.Application.Statistics;
public sealed record StatisticsPeriod(DateTimeOffset? From, DateTimeOffset? To)
{
internal (DateTime? From, DateTime? To) UtcBounds()
{
if (From >= To)
throw new BadRequestException("Začátek období musí předcházet jeho konci.");
return (From?.UtcDateTime, To?.UtcDateTime);
}
}
public sealed record IssueTiming(int IssueId, long? MicrosecondsToAssignment, long? MicrosecondsToClosure);
public sealed record StatisticsOverview(
int TotalIssues, IReadOnlyDictionary<string, int> IssuesByStatus,
decimal? AverageHoursToAssignment, decimal? AverageHoursToClosure);
public sealed record IssueCategoryStatistics(int CategoryId, string Name, int IssueCount, decimal? AverageHoursToResolution);
public sealed record IssueBuildingStatistics(int? BuildingId, string? Name, int IssueCount);
public sealed record IssueAssigneeStatistics(int AssigneeId, string Name, int OpenIssues, int ResolvedIssues, int RejectedIssues);
public sealed record IssueTrendPoint(DateOnly Month, int CreatedIssues, int ClosedIssues);
public sealed record TopProposal(int Id, string Title, string Status, long VotesFor, long VotesAgainst, long Score);
@@ -0,0 +1,141 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Domain;
using Helpdesk.Domain.Issues;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Statistics;
public sealed class StatisticsService(IAppDbContext db)
{
private const decimal MicrosecondsPerHour = 3_600_000_000m;
public async Task<StatisticsOverview> GetOverviewAsync(StatisticsPeriod period, CancellationToken ct)
{
var byStatus = await (
from issue in IssuesInPeriod(period)
join timing in db.IssueTimings on issue.Id equals timing.IssueId into timings
from timing in timings.DefaultIfEmpty()
group timing by issue.Status into rows
select new
{
Status = rows.Key,
Count = rows.Count(),
AssignedCount = rows.Count(t => t.MicrosecondsToAssignment != null),
ClosedCount = rows.Count(t => t.MicrosecondsToClosure != null),
AssignmentTime = rows.Sum(t => (decimal?)t.MicrosecondsToAssignment),
ClosureTime = rows.Sum(t => (decimal?)t.MicrosecondsToClosure),
}).ToDictionaryAsync(row => row.Status, ct);
var counts = Enum.GetValues<IssueStatus>()
.ToDictionary(status => status.ToCode(), status => byStatus.GetValueOrDefault(status)?.Count ?? 0);
return new StatisticsOverview(
counts.Values.Sum(),
counts,
AverageHours(byStatus.Values.Sum(row => row.AssignmentTime), byStatus.Values.Sum(row => row.AssignedCount)),
AverageHours(byStatus.Values.Sum(row => row.ClosureTime), byStatus.Values.Sum(row => row.ClosedCount)));
}
public async Task<IReadOnlyList<IssueCategoryStatistics>> GetByCategoryAsync(StatisticsPeriod period, CancellationToken ct)
{
var groups = await (
from issue in IssuesInPeriod(period)
join category in db.IssueCategories on issue.CategoryId equals category.Id
join timing in db.IssueTimings on issue.Id equals timing.IssueId into timings
from timing in timings.DefaultIfEmpty()
group new { issue.Status, timing.MicrosecondsToClosure } by new { category.Id, category.Name } into rows
orderby rows.Key.Id
select new
{
rows.Key.Id,
rows.Key.Name,
Count = rows.Count(),
ResolutionTime = rows.Average(row => row.Status == IssueStatus.Resolved
? (decimal?)row.MicrosecondsToClosure : null),
}).ToListAsync(ct);
return groups.Select(row => new IssueCategoryStatistics(
row.Id, row.Name, row.Count, row.ResolutionTime / MicrosecondsPerHour)).ToArray();
}
public async Task<IReadOnlyList<IssueBuildingStatistics>> GetByBuildingAsync(StatisticsPeriod period, CancellationToken ct) =>
await (
from issue in IssuesInPeriod(period)
join building in db.Buildings on issue.BuildingId equals building.Id into buildings
from building in buildings.DefaultIfEmpty()
group issue by new { issue.BuildingId, building.Name } into rows
orderby rows.Key.BuildingId
select new IssueBuildingStatistics(rows.Key.BuildingId, rows.Key.Name, rows.Count())).ToListAsync(ct);
public async Task<IReadOnlyList<IssueAssigneeStatistics>> GetByAssigneeAsync(StatisticsPeriod period, CancellationToken ct) =>
await (
from issue in IssuesInPeriod(period)
join assignee in db.Users on issue.AssigneeId equals assignee.Id
group issue by new { assignee.Id, assignee.FirstName, assignee.LastName } into rows
orderby rows.Key.LastName, rows.Key.FirstName, rows.Key.Id
select new IssueAssigneeStatistics(
rows.Key.Id,
rows.Key.FirstName + " " + rows.Key.LastName,
rows.Count(i => i.Status == IssueStatus.Assigned || i.Status == IssueStatus.InProgress ||
i.Status == IssueStatus.PendingVerification),
rows.Count(i => i.Status == IssueStatus.Resolved),
rows.Count(i => i.Status == IssueStatus.Rejected))).ToListAsync(ct);
public async Task<IReadOnlyList<IssueTrendPoint>> GetTrendAsync(StatisticsPeriod period, CancellationToken ct)
{
var (from, to) = period.UtcBounds();
var created = await CountByMonthAsync(db.Issues.Select(i => i.CreatedAt), from, to, ct);
var closed = await CountByMonthAsync(
db.IssueEvents.Where(e => e.EventType == IssueEventType.StatusChanged &&
(e.ToStatus == IssueStatus.Resolved || e.ToStatus == IssueStatus.Rejected)).Select(e => e.OccurredAt),
from, to, ct);
var observed = created.Keys.Concat(closed.Keys).ToArray();
if (observed.Length == 0 && (from is null || to is null))
return [];
var first = from is DateTime start ? MonthIndex(start) : observed.Min();
var last = to is DateTime end ? MonthIndex(end.AddTicks(-1)) : observed.Max();
var result = new List<IssueTrendPoint>();
for (var month = first; month <= last; month++)
{
var date = new DateOnly(month / 12 + 1, month % 12 + 1, 1);
result.Add(new IssueTrendPoint(date, created.GetValueOrDefault(month), closed.GetValueOrDefault(month)));
}
return result;
}
public async Task<IReadOnlyList<TopProposal>> GetTopProposalsAsync(StatisticsPeriod period, int limit, CancellationToken ct)
{
var (start, end) = period.UtcBounds();
var top = await (
from proposal in db.Proposals
where (start == null || proposal.CreatedAt >= start) && (end == null || proposal.CreatedAt < end)
join score in db.ProposalScores on proposal.Id equals score.ProposalId
orderby score.Score descending, score.VotesFor descending, proposal.CreatedAt, proposal.Id
select new { proposal.Id, proposal.Title, proposal.Status, score.VotesFor, score.VotesAgainst, score.Score })
.Take(limit).ToListAsync(ct);
return top.Select(row => new TopProposal(row.Id, row.Title, row.Status.ToCode(),
(long)row.VotesFor, (long)row.VotesAgainst, (long)row.Score)).ToArray();
}
private IQueryable<Issue> IssuesInPeriod(StatisticsPeriod period)
{
var (from, to) = period.UtcBounds();
return db.Issues.Where(i => (from == null || i.CreatedAt >= from) && (to == null || i.CreatedAt < to));
}
private static Task<Dictionary<int, int>> CountByMonthAsync(
IQueryable<DateTime> dates, DateTime? from, DateTime? to, CancellationToken ct) =>
dates.Where(date => (from == null || date >= from) && (to == null || date < to))
.GroupBy(date => (date.Year - 1) * 12 + date.Month - 1)
.Select(rows => new { Month = rows.Key, Count = rows.Count() })
.ToDictionaryAsync(row => row.Month, row => row.Count, ct);
private static int MonthIndex(DateTime date) => (date.Year - 1) * 12 + date.Month - 1;
private static decimal? AverageHours(decimal? microseconds, int count) =>
count == 0 ? null : microseconds / count / MicrosecondsPerHour;
}
@@ -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;
} }
+137
View File
@@ -0,0 +1,137 @@
using Helpdesk.Domain.Users;
namespace Helpdesk.Domain.Issues;
public enum IssueStatus { Received, Assigned, InProgress, PendingVerification, Resolved, Rejected }
public enum IssuePriority { Low, Normal, High }
public enum IssueEventType { Created, Updated, Assigned, StatusChanged, Commented }
public enum IssueAction { Edit, Assign, StartWork, SubmitForVerification, Confirm, Reopen, Reject, Comment, AddAttachments }
public enum IssueActionAvailability { Allowed, Forbidden, InvalidState }
public sealed class Issue : IHasCreatedAt
{
private Issue() { }
public Issue(int reporterId, string title, string description, int categoryId, int? buildingId, string? locationDetail)
{
ReporterId = reporterId;
SetDetails(title, description, categoryId, buildingId, locationDetail);
}
public int Id { get; private set; }
public string Title { get; private set; } = null!;
public string Description { get; private set; } = null!;
public int CategoryId { get; private set; }
public int? BuildingId { get; private set; }
public string? LocationDetail { get; private set; }
public IssueStatus Status { get; private set; } = IssueStatus.Received;
public IssuePriority Priority { get; private set; } = IssuePriority.Normal;
public int ReporterId { get; private set; }
public int? AssigneeId { get; private set; }
public int RowVersion { get; private set; }
public DateTime CreatedAt { get; set; }
public static bool CanReadAll(UserRole role) => role is UserRole.FacilityManager or UserRole.Management;
public static bool CanBeAssigned(UserRole role) => role is UserRole.FacilityManager or UserRole.Management;
public bool CanRead(int userId, UserRole role) => CanReadAll(role) || ReporterId == userId;
public IssueActionAvailability Availability(IssueAction action, int actorId, UserRole role)
{
var reporter = ReporterId == actorId;
var assignee = AssigneeId == actorId && CanBeAssigned(role);
var management = role == UserRole.Management;
var authorized = action switch
{
IssueAction.Edit or IssueAction.Confirm or IssueAction.Reopen => reporter,
IssueAction.Assign => management,
IssueAction.StartWork or IssueAction.SubmitForVerification => assignee,
IssueAction.Reject => assignee || (management && AssigneeId is null),
IssueAction.Comment or IssueAction.AddAttachments => reporter || assignee,
_ => false,
};
if (!authorized)
return IssueActionAvailability.Forbidden;
var permittedState = action switch
{
IssueAction.Edit => Status == IssueStatus.Received,
IssueAction.Assign => Status is IssueStatus.Received or IssueStatus.Assigned or IssueStatus.InProgress,
IssueAction.StartWork => Status == IssueStatus.Assigned,
IssueAction.SubmitForVerification => Status == IssueStatus.InProgress,
IssueAction.Confirm or IssueAction.Reopen => Status == IssueStatus.PendingVerification,
IssueAction.Reject => Status == IssueStatus.Received
? management
: assignee && Status is (IssueStatus.Assigned or IssueStatus.InProgress),
IssueAction.Comment or IssueAction.AddAttachments => Status is not (IssueStatus.Resolved or IssueStatus.Rejected),
_ => false,
};
return permittedState ? IssueActionAvailability.Allowed : IssueActionAvailability.InvalidState;
}
public void Edit(int actorId, UserRole role, string title, string description, int categoryId,
int? buildingId, string? locationDetail)
{
Require(IssueAction.Edit, actorId, role);
SetDetails(title, description, categoryId, buildingId, locationDetail);
RowVersion++;
}
public void Assign(int actorId, UserRole role, int assigneeId, UserRole assigneeRole, IssuePriority? priority)
{
Require(IssueAction.Assign, actorId, role);
if (!CanBeAssigned(assigneeRole))
throw new ArgumentException("Neplatná role řešitele.", nameof(assigneeRole));
if (AssigneeId == assigneeId)
throw new ArgumentException("Nový řešitel musí být jiný než stávající.", nameof(assigneeId));
AssigneeId = assigneeId;
Priority = priority ?? Priority;
Status = IssueStatus.Assigned;
RowVersion++;
}
public void Transition(IssueAction action, int actorId, UserRole role, string? reason)
{
Require(action, actorId, role);
if (action is (IssueAction.Reject or IssueAction.Reopen) && string.IsNullOrWhiteSpace(reason))
throw new ArgumentException("Důvod je povinný.", nameof(reason));
Status = action switch
{
IssueAction.StartWork or IssueAction.Reopen => IssueStatus.InProgress,
IssueAction.SubmitForVerification => IssueStatus.PendingVerification,
IssueAction.Confirm => IssueStatus.Resolved,
IssueAction.Reject => IssueStatus.Rejected,
_ => throw new ArgumentOutOfRangeException(nameof(action)),
};
RowVersion++;
}
public void RecordParticipation(IssueAction action, int actorId, UserRole role)
{
if (action is not (IssueAction.Comment or IssueAction.AddAttachments))
throw new ArgumentOutOfRangeException(nameof(action));
Require(action, actorId, role);
RowVersion++;
}
private void Require(IssueAction action, int actorId, UserRole role)
{
if (Availability(action, actorId, role) != IssueActionAvailability.Allowed)
throw new InvalidOperationException("Akce není pro tuto závadu povolena.");
}
private void SetDetails(string title, string description, int categoryId, int? buildingId, string? locationDetail)
{
Title = title.Trim();
Description = description.Trim();
CategoryId = categoryId;
BuildingId = buildingId;
LocationDetail = string.IsNullOrWhiteSpace(locationDetail) ? null : locationDetail.Trim();
}
}
@@ -0,0 +1,43 @@
namespace Helpdesk.Domain.Issues;
public sealed class IssueEvent
{
private IssueEvent() { }
public IssueEvent(Issue issue, IssueEventType eventType, IssueStatus? fromStatus, int actorId, string? note,
DateTime occurredAt)
{
Issue = issue;
EventType = eventType;
FromStatus = fromStatus;
ToStatus = issue.Status;
ActorId = actorId;
Note = note;
OccurredAt = occurredAt;
}
public int Id { get; private set; }
public int IssueId { get; private set; }
public Issue Issue { get; private set; } = null!;
public IssueEventType EventType { get; private set; }
public IssueStatus? FromStatus { get; private set; }
public IssueStatus ToStatus { get; private set; }
public int ActorId { get; private set; }
public string? Note { get; private set; }
public DateTime OccurredAt { get; private set; }
}
public sealed class Attachment(
Issue issue, string originalFileName, string storedFileName, string contentType, long sizeBytes) : IHasCreatedAt
{
private Attachment() : this(null!, null!, null!, null!, 0) { }
public int Id { get; private set; }
public int IssueId { get; private set; }
public Issue Issue { get; private set; } = issue;
public string OriginalFileName { get; private set; } = originalFileName;
public string StoredFileName { get; private set; } = storedFileName;
public string ContentType { get; private set; } = contentType;
public long SizeBytes { get; private set; } = sizeBytes;
public DateTime CreatedAt { get; set; }
}
@@ -0,0 +1,100 @@
using Helpdesk.Domain.Issues;
using Helpdesk.Domain.Proposals;
namespace Helpdesk.Domain.Notifications;
public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged }
public enum DeliveryChannel { Email, Push }
public enum DeliveryStatus { Pending, Sent, Failed, Skipped }
public sealed class Notification : IHasCreatedAt
{
private Notification() { }
public Notification(Issue issue, int userId, NotificationType type, string title, string message)
: this(userId, type, title, message)
{
Issue = issue;
}
public Notification(Proposal proposal, int userId, string title)
: this(userId, NotificationType.ProposalStatusChanged, title, proposal.Title)
{
ProposalId = proposal.Id;
}
private Notification(int userId, NotificationType type, string title, string message)
{
UserId = userId;
Type = type;
Title = title;
Message = message;
}
public int Id { get; private set; }
public int? IssueId { get; private set; }
public int? ProposalId { get; private set; }
public Issue? Issue { get; private set; }
public int UserId { get; private set; }
public NotificationType Type { get; private set; }
public string Title { get; private set; } = null!;
public string Message { get; private set; } = null!;
public DateTime CreatedAt { get; set; }
public DateTime? ReadAt { get; private set; }
}
public sealed class NotificationDelivery(
Notification notification, DeliveryChannel channel, bool enabled, DateTime now)
{
private static readonly TimeSpan[] RetryDelays =
[TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(30), TimeSpan.FromHours(2)];
private NotificationDelivery() : this(null!, default, false, default) { }
public int Id { get; private set; }
public int NotificationId { get; private set; }
public Notification Notification { get; private set; } = notification;
public DeliveryChannel Channel { get; private set; } = channel;
public DeliveryStatus Status { get; private set; } = enabled ? DeliveryStatus.Pending : DeliveryStatus.Skipped;
public int AttemptCount { get; private set; }
public DateTime? NextAttemptAt { get; private set; } = enabled ? now : null;
public string? LastError { get; private set; }
public DateTime? SentAt { get; private set; }
public void RecordSent(DateTime now)
{
AttemptCount++;
Status = DeliveryStatus.Sent;
SentAt = now;
NextAttemptAt = null;
LastError = null;
}
public void RecordFailure(DateTime now, string reason, bool retryable)
{
AttemptCount++;
LastError = reason;
if (retryable && AttemptCount <= RetryDelays.Length)
{
NextAttemptAt = now + RetryDelays[AttemptCount - 1];
return;
}
Status = DeliveryStatus.Failed;
NextAttemptAt = null;
}
public void Skip()
{
Status = DeliveryStatus.Skipped;
NextAttemptAt = null;
LastError = null;
}
}
public sealed class PushDevice
{
public int Id { get; private set; }
public int UserId { get; private set; }
public string FcmToken { get; private set; } = null!;
}
@@ -0,0 +1,64 @@
using Helpdesk.Domain.Users;
namespace Helpdesk.Domain.Proposals;
public enum ProposalStatus { Submitted, UnderReview, Accepted, Rejected, Implemented }
public enum ProposalEventType { Created, Updated, StatusChanged }
public sealed class Proposal : IHasCreatedAt
{
private Proposal() { }
public Proposal(int authorId, string title, string description, int categoryId)
{
AuthorId = authorId;
SetDetails(title, description, categoryId);
}
public int Id { get; private set; }
public int AuthorId { get; private set; }
public string Title { get; private set; } = null!;
public string Description { get; private set; } = null!;
public int CategoryId { get; private set; }
public ProposalStatus Status { get; private set; } = ProposalStatus.Submitted;
public DateTime CreatedAt { get; set; }
public bool IsAuthor(int userId) => AuthorId == userId;
public bool IsEditable => Status == ProposalStatus.Submitted;
public bool IsVotingOpen => Status is ProposalStatus.Submitted or ProposalStatus.UnderReview;
public bool CanEdit(int userId) => IsAuthor(userId) && IsEditable;
public bool CanVote(int userId) => !IsAuthor(userId) && IsVotingOpen;
public bool CanTransitionTo(ProposalStatus target) => Status switch
{
ProposalStatus.Submitted => target is ProposalStatus.UnderReview or ProposalStatus.Accepted or ProposalStatus.Rejected,
ProposalStatus.UnderReview => target is ProposalStatus.Accepted or ProposalStatus.Rejected,
ProposalStatus.Accepted => target == ProposalStatus.Implemented,
_ => false,
};
public void Edit(int actorId, string title, string description, int categoryId)
{
if (!CanEdit(actorId))
throw new InvalidOperationException("Návrh nelze upravit.");
SetDetails(title, description, categoryId);
}
public void ChangeStatus(ProposalStatus target, UserRole role, string? note)
{
if (role != UserRole.Management || !CanTransitionTo(target))
throw new InvalidOperationException("Stav návrhu nelze změnit.");
if (target == ProposalStatus.Rejected && string.IsNullOrWhiteSpace(note))
throw new ArgumentException("Zamítnutí vyžaduje vyjádření.", nameof(note));
Status = target;
}
private void SetDetails(string title, string description, int categoryId)
{
Title = title;
Description = description;
CategoryId = categoryId;
}
}
@@ -0,0 +1,66 @@
namespace Helpdesk.Domain.Proposals;
public sealed class ProposalEvent
{
private ProposalEvent() { }
public ProposalEvent(Proposal proposal, ProposalEventType eventType, ProposalStatus? fromStatus, int actorId,
string? note, DateTime occurredAt)
{
Proposal = proposal;
EventType = eventType;
FromStatus = fromStatus;
ToStatus = proposal.Status;
ActorId = actorId;
Note = note;
OccurredAt = occurredAt;
}
public int Id { get; private set; }
public int ProposalId { get; private set; }
public Proposal Proposal { get; private set; } = null!;
public ProposalEventType EventType { get; private set; }
public ProposalStatus? FromStatus { get; private set; }
public ProposalStatus ToStatus { get; private set; }
public int ActorId { get; private set; }
public string? Note { get; private set; }
public DateTime OccurredAt { get; private set; }
}
public sealed class ProposalVote
{
private ProposalVote() { }
public ProposalVote(Proposal proposal, int userId, sbyte value, DateTime now)
{
ProposalId = proposal.Id;
UserId = userId;
SetValue(proposal, value, now);
}
public int ProposalId { get; private set; }
public int UserId { get; private set; }
public sbyte Value { get; private set; }
public DateTime VotedAt { get; private set; }
public void SetValue(Proposal proposal, sbyte value, DateTime now)
{
if (proposal.Id != ProposalId || !proposal.CanVote(UserId))
throw new InvalidOperationException("O návrhu nelze hlasovat.");
if (value is not (1 or -1))
throw new ArgumentOutOfRangeException(nameof(value));
if (Value == value)
return;
Value = value;
VotedAt = now;
}
}
public sealed class ProposalScore
{
public int ProposalId { get; private set; }
public decimal VotesFor { get; private set; }
public decimal VotesAgainst { get; private set; }
public decimal Score { get; private set; }
}
@@ -0,0 +1,121 @@
using System.Data;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Domain.Notifications;
using Helpdesk.Infrastructure.Email;
using Helpdesk.Infrastructure.Notifications;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Helpdesk.Infrastructure.Background;
internal sealed partial class NotificationDispatcher(
IServiceScopeFactory scopes, IEmailSender email, TimeProvider clock, ILogger<NotificationDispatcher> logger,
FirebasePushSender? push = null) : BackgroundService
{
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(2);
private readonly bool emailEnabled = email is not LoggingEmailSender;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!emailEnabled && push is null)
return;
while (!stoppingToken.IsCancellationRequested)
{
try
{
if (await DeliverNextAsync(stoppingToken))
continue;
}
catch (Exception failure) when (!stoppingToken.IsCancellationRequested)
{
LogDispatchFailure(failure.GetType().Name);
}
await Task.Delay(PollInterval, clock, stoppingToken);
}
}
private async Task<bool> DeliverNextAsync(CancellationToken ct)
{
using var scope = scopes.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
await using var transaction = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
var now = clock.GetUtcNow().UtcDateTime;
var rows = await db.NotificationDeliveries.FromSql($"""
SELECT * FROM notification_delivery
WHERE status = 'PENDING' AND next_attempt_at <= {now}
AND (({emailEnabled} AND channel = 'EMAIL') OR ({push is not null} AND channel = 'PUSH'))
ORDER BY next_attempt_at, id LIMIT 1 FOR UPDATE SKIP LOCKED
""").ToListAsync(ct);
if (rows.SingleOrDefault() is not { } delivery)
return false;
var recipient = await (
from notification in db.Notifications.AsNoTracking()
join user in db.Users on notification.UserId equals user.Id
where notification.Id == delivery.NotificationId
select new { Notification = notification, user.Id, user.Email, user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled }
).SingleAsync(ct);
if (!recipient.IsActive)
delivery.Skip();
else if (delivery.Channel == DeliveryChannel.Email)
{
if (recipient.EmailConfirmed && recipient.EmailNotificationsEnabled)
await SendEmailAsync(delivery, recipient.Notification, recipient.Email, ct);
else
delivery.Skip();
}
else
{
await SendPushAsync(db, delivery, recipient.Notification, recipient.Id, ct);
}
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
return true;
}
private async Task SendEmailAsync(NotificationDelivery delivery, Notification notification, string address, CancellationToken ct)
{
try
{
await email.SendAsync(address, notification.Title, notification.Message, ct);
delivery.RecordSent(clock.GetUtcNow().UtcDateTime);
}
catch (EmailDeliveryException failure)
{
delivery.RecordFailure(clock.GetUtcNow().UtcDateTime, failure.Reason, failure.Retryable);
}
}
private async Task SendPushAsync(
HelpdeskDbContext db, NotificationDelivery delivery, Notification notification, int userId, CancellationToken ct)
{
var devices = db.PushDevices.Where(d => d.UserId == userId);
var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct);
if (tokens.Length == 0)
{
delivery.Skip();
return;
}
var result = await push!.SendAsync(notification, tokens, ct);
foreach (var invalidToken in result.InvalidTokens)
await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct);
var now = clock.GetUtcNow().UtcDateTime;
if (result.Sent)
delivery.RecordSent(now);
else
delivery.RecordFailure(now, result.FailureReason, result.Retryable);
}
[LoggerMessage(Level = LogLevel.Error, Message = "Zpracování notifikační fronty selhalo ({FailureType}).")]
private partial void LogDispatchFailure(string failureType);
}
@@ -1,17 +1,23 @@
using Helpdesk.Application.Abstractions; using Helpdesk.Application.Abstractions;
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.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.");
@@ -31,11 +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.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>();
}
} }
@@ -4,8 +4,7 @@ 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) : IEmailSender internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger) : IEmailSender
{ {
@@ -0,0 +1,63 @@
using System.Net.Sockets;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using MailKit;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MimeKit;
namespace Helpdesk.Infrastructure.Email;
internal sealed class SmtpOptions
{
public string Host { get; set; } = "smtp.seznam.cz";
public int Port { get; set; } = 465;
public string Mailbox { get; set; } = "";
public string Password { get; set; } = "";
}
internal sealed partial class SmtpEmailSender(IOptions<SmtpOptions> options, ILogger<SmtpEmailSender> logger) : IEmailSender
{
public async Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
{
if (!MailboxAddress.TryParse(to, out var recipient))
{
LogDeliveryFailure("InvalidRecipient");
throw new EmailDeliveryException("SMTP_INVALID_RECIPIENT", retryable: false);
}
var settings = options.Value;
using var message = new MimeMessage { Subject = subject, Body = new TextPart("plain") { Text = body } };
message.From.Add(MailboxAddress.Parse(settings.Mailbox));
message.To.Add(recipient);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(15));
using var client = new SmtpClient();
try
{
await client.ConnectAsync(settings.Host, settings.Port, SecureSocketOptions.SslOnConnect, timeout.Token);
await client.AuthenticateAsync(settings.Mailbox, settings.Password, timeout.Token);
await client.SendAsync(message, timeout.Token);
}
catch (Exception exception) when (!cancellationToken.IsCancellationRequested &&
exception is (IOException or SocketException or CommandException or ProtocolException or
AuthenticationException or SslHandshakeException or NotSupportedException or TimeoutException or
OperationCanceledException))
{
LogDeliveryFailure(exception.GetType().Name);
if (exception is SmtpCommandException command)
{
var status = (int)command.StatusCode;
throw new EmailDeliveryException($"SMTP_{status}", retryable: status is < 500 or >= 600);
}
throw new EmailDeliveryException($"SMTP_{exception.GetType().Name}", retryable: true);
}
}
[LoggerMessage(Level = LogLevel.Warning, Message = "Doručení e-mailu přes SMTP selhalo ({FailureType}).")]
private partial void LogDeliveryFailure(string failureType);
}
@@ -0,0 +1,155 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Helpdesk.Application.Common;
using Helpdesk.Application.Issues;
using Microsoft.Extensions.Logging;
namespace Helpdesk.Infrastructure.Files;
internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) : IAttachmentStore
{
private readonly string directory = Path.Combine(AppContext.BaseDirectory, "uploads");
public async Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct)
{
if (upload.SizeBytes is <= 0 or > AttachmentLimits.MaxFileBytes)
throw new BadRequestException("Příloha musí mít velikost od 1 B do 10 MB.");
var name = Path.GetFileName(upload.FileName.Replace('\\', '/')).Trim();
if (name.Length is 0 or > 255 || name.Any(char.IsControl))
throw new BadRequestException("Neplatný název přílohy.");
var extension = Path.GetExtension(name).ToLowerInvariant();
var contentType = extension switch
{
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".heic" => "image/heic",
".pdf" => "application/pdf",
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
_ => throw new BadRequestException("Tento typ přílohy není povolen."),
};
Directory.CreateDirectory(directory);
var key = Guid.NewGuid().ToString("D");
var path = FilePath(key);
var created = false;
try
{
await using var input = upload.OpenRead();
await using var output = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None,
bufferSize: 64 * 1024, useAsync: true);
created = true;
var buffer = new byte[64 * 1024];
long written = 0;
int read;
while ((read = await input.ReadAsync(buffer, ct)) > 0)
{
written += read;
if (written > upload.SizeBytes)
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
await output.WriteAsync(buffer.AsMemory(0, read), ct);
}
if (written != upload.SizeBytes)
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
output.Position = 0;
if (!await HasExpectedFormatAsync(output, extension, ct))
throw new BadRequestException("Obsah přílohy neodpovídá její příponě.");
return new StoredAttachment(name, key, contentType, written);
}
catch
{
if (created)
Delete(key);
throw;
}
}
public Stream OpenRead(string storedFileName)
{
try
{
return new FileStream(FilePath(storedFileName), FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 64 * 1024, useAsync: true);
}
catch (IOException exception) when (exception is FileNotFoundException or DirectoryNotFoundException)
{
logger.LogError(exception, "Soubor přílohy {AttachmentKey} v úložišti chybí.", storedFileName);
throw new NotFoundException("Soubor přílohy není dostupný.");
}
}
public void Delete(string storedFileName)
{
try
{
File.Delete(FilePath(storedFileName));
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
logger.LogError(exception, "Soubor přílohy {AttachmentKey} se nepodařilo uklidit.", storedFileName);
}
}
private string FilePath(string key) => Guid.TryParseExact(key, "D", out _)
? Path.Combine(directory, key)
: throw new InvalidOperationException("Neplatný klíč souboru přílohy.");
private static async Task<bool> HasExpectedFormatAsync(Stream stream, string extension, CancellationToken ct)
{
var header = new byte[(int)Math.Min(stream.Length, 512)];
await stream.ReadExactlyAsync(header, ct);
return extension switch
{
".jpg" or ".jpeg" => header.AsSpan().StartsWith(new byte[] { 0xff, 0xd8, 0xff }),
".png" => header.AsSpan().StartsWith(new byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a }),
".pdf" => header.AsSpan().StartsWith("%PDF-"u8),
".heic" => IsHeic(header, stream.Length),
".docx" => IsDocx(stream, header),
_ => false,
};
}
private static bool IsHeic(ReadOnlySpan<byte> header, long length)
{
if (header.Length < 16 || !header.Slice(4, 4).SequenceEqual("ftyp"u8))
return false;
var boxLength = BinaryPrimitives.ReadUInt32BigEndian(header);
if (boxLength < 16 || boxLength > length)
return false;
for (var offset = 8; offset + 4 <= Math.Min(boxLength, header.Length); offset += 4)
{
if (offset == 12)
continue; // minor_version
var brand = header.Slice(offset, 4);
if (brand.SequenceEqual("heic"u8) || brand.SequenceEqual("heix"u8) ||
brand.SequenceEqual("hevc"u8) || brand.SequenceEqual("hevx"u8))
return true;
}
return false;
}
private static bool IsDocx(Stream stream, ReadOnlySpan<byte> header)
{
if (!header.StartsWith(new byte[] { 0x50, 0x4b, 0x03, 0x04 }))
return false;
stream.Position = 0;
try
{
using var zip = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: true);
return zip.GetEntry("[Content_Types].xml") is not null && zip.GetEntry("word/document.xml") is not null;
}
catch (InvalidDataException)
{
return false;
}
}
}
@@ -10,6 +10,8 @@
<PackageReference Include="MySqlConnector" /> <PackageReference Include="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,10 +1,18 @@
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.Notifications;
using Helpdesk.Domain.Proposals;
using Helpdesk.Domain.Users; using Helpdesk.Domain.Users;
using Helpdesk.Infrastructure.Security; using Helpdesk.Infrastructure.Security;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using MySqlConnector;
namespace Helpdesk.Infrastructure.Persistence; namespace Helpdesk.Infrastructure.Persistence;
@@ -20,6 +28,41 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
public DbSet<Building> Buildings => Set<Building>(); public DbSet<Building> Buildings => Set<Building>();
public DbSet<IssueCategory> IssueCategories => Set<IssueCategory>(); public DbSet<IssueCategory> IssueCategories => Set<IssueCategory>();
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>(); public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
public DbSet<Issue> Issues => Set<Issue>();
public DbSet<IssueEvent> IssueEvents => Set<IssueEvent>();
public IQueryable<IssueTiming> IssueTimings => Set<IssueTiming>();
public DbSet<Attachment> Attachments => Set<Attachment>();
public DbSet<Proposal> Proposals => Set<Proposal>();
public DbSet<ProposalEvent> ProposalEvents => Set<ProposalEvent>();
public DbSet<ProposalVote> ProposalVotes => Set<ProposalVote>();
public DbSet<ProposalScore> ProposalScores => Set<ProposalScore>();
public DbSet<Notification> Notifications => Set<Notification>();
public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>();
public DbSet<PushDevice> PushDevices => Set<PushDevice>();
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
try
{
return await base.SaveChangesAsync(cancellationToken);
}
catch (DbUpdateException exception) when (
exception.InnerException is MySqlException { ErrorCode: MySqlErrorCode.DuplicateKeyEntry } &&
exception.Entries is [var entry] && entry.Entity is (IssueCategory or ProposalCategory))
{
throw new ConflictException("Kategorie se stejným názvem již existuje.");
}
}
public Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct) =>
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
public async Task<Proposal?> LockProposalAsync(int id, CancellationToken ct)
{
// Všechny zápisy nad návrhem zamykají stejný řádek před čtením stavu a hlasů.
var rows = await Proposals.FromSql($"SELECT * FROM proposal WHERE id = {id} FOR UPDATE").ToListAsync(ct);
return rows.SingleOrDefault();
}
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
@@ -28,8 +71,33 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
modelBuilder.ApplyConfiguration(new BuildingConfiguration()); modelBuilder.ApplyConfiguration(new BuildingConfiguration());
modelBuilder.ApplyConfiguration(new IssueCategoryConfiguration()); modelBuilder.ApplyConfiguration(new IssueCategoryConfiguration());
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration()); modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
modelBuilder.ApplyConfiguration(new IssueConfiguration());
modelBuilder.ApplyConfiguration(new IssueEventConfiguration());
modelBuilder.Entity<IssueTiming>().HasNoKey().ToSqlQuery("""
SELECT issue_id,
TIMESTAMPDIFF(MICROSECOND, created_at, first_assigned_at) AS microseconds_to_assignment,
TIMESTAMPDIFF(MICROSECOND, created_at, closed_at) AS microseconds_to_closure
FROM v_issue_lifecycle
""");
modelBuilder.ApplyConfiguration(new AttachmentConfiguration());
modelBuilder.ApplyConfiguration(new ProposalConfiguration());
modelBuilder.ApplyConfiguration(new ProposalEventConfiguration());
modelBuilder.ApplyConfiguration(new ProposalVoteConfiguration());
modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score");
modelBuilder.ApplyConfiguration(new NotificationConfiguration());
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
var pushDevice = modelBuilder.Entity<PushDevice>();
pushDevice.ToTable("push_device");
pushDevice.Property(x => x.FcmToken).HasMaxLength(512);
pushDevice.HasIndex(x => x.FcmToken).IsUnique();
} }
public Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct) =>
Database.ExecuteSqlInterpolatedAsync($"""
INSERT INTO push_device (user_id, fcm_token) VALUES ({userId}, {token})
ON DUPLICATE KEY UPDATE user_id = VALUES(user_id)
""", ct);
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) 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".
@@ -0,0 +1,79 @@
using Helpdesk.Domain.Catalogs;
using Helpdesk.Domain.Issues;
using Helpdesk.Domain.Notifications;
using Helpdesk.Domain.Proposals;
using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Helpdesk.Infrastructure.Persistence;
internal sealed class IssueConfiguration : IEntityTypeConfiguration<Issue>
{
public void Configure(EntityTypeBuilder<Issue> b)
{
b.ToTable("issue");
b.Property(x => x.Title).HasMaxLength(200);
b.Property(x => x.Description).HasColumnType("text");
b.Property(x => x.LocationDetail).HasMaxLength(255);
b.Property(x => x.Status).HasConversion<EnumCodeConverter<IssueStatus>>().HasMaxLength(30);
b.Property(x => x.Priority).HasConversion<EnumCodeConverter<IssuePriority>>().HasMaxLength(10);
b.Property(x => x.RowVersion).IsConcurrencyToken();
b.HasOne<IssueCategory>().WithMany().HasForeignKey(x => x.CategoryId);
b.HasOne<Building>().WithMany().HasForeignKey(x => x.BuildingId);
b.HasOne<User>().WithMany().HasForeignKey(x => x.ReporterId);
b.HasOne<User>().WithMany().HasForeignKey(x => x.AssigneeId);
}
}
internal sealed class IssueEventConfiguration : IEntityTypeConfiguration<IssueEvent>
{
public void Configure(EntityTypeBuilder<IssueEvent> b)
{
b.ToTable("issue_event");
b.Property(x => x.EventType).HasConversion<EnumCodeConverter<IssueEventType>>().HasMaxLength(20);
b.Property(x => x.FromStatus).HasConversion<EnumCodeConverter<IssueStatus>>().HasMaxLength(30);
b.Property(x => x.ToStatus).HasConversion<EnumCodeConverter<IssueStatus>>().HasMaxLength(30);
b.Property(x => x.Note).HasColumnType("text");
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId);
b.HasOne<User>().WithMany().HasForeignKey(x => x.ActorId);
}
}
internal sealed class AttachmentConfiguration : IEntityTypeConfiguration<Attachment>
{
public void Configure(EntityTypeBuilder<Attachment> b)
{
b.ToTable("attachment");
b.Property(x => x.OriginalFileName).HasMaxLength(255);
b.Property(x => x.StoredFileName).HasMaxLength(36);
b.Property(x => x.ContentType).HasMaxLength(100);
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId);
}
}
internal sealed class NotificationConfiguration : IEntityTypeConfiguration<Notification>
{
public void Configure(EntityTypeBuilder<Notification> b)
{
b.ToTable("notification");
b.Property(x => x.Type).HasConversion<EnumCodeConverter<NotificationType>>().HasMaxLength(40);
b.Property(x => x.Title).HasMaxLength(200);
b.Property(x => x.Message).HasMaxLength(1000);
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId).IsRequired(false);
b.HasOne<Proposal>().WithMany().HasForeignKey(x => x.ProposalId);
b.HasOne<User>().WithMany().HasForeignKey(x => x.UserId);
}
}
internal sealed class NotificationDeliveryConfiguration : IEntityTypeConfiguration<NotificationDelivery>
{
public void Configure(EntityTypeBuilder<NotificationDelivery> b)
{
b.ToTable("notification_delivery");
b.Property(x => x.Channel).HasConversion<EnumCodeConverter<DeliveryChannel>>().HasMaxLength(10);
b.Property(x => x.Status).HasConversion<EnumCodeConverter<DeliveryStatus>>().HasMaxLength(10);
b.Property(x => x.LastError).HasMaxLength(1000);
b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId);
}
}
@@ -0,0 +1,46 @@
using Helpdesk.Domain.Catalogs;
using Helpdesk.Domain.Proposals;
using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Helpdesk.Infrastructure.Persistence;
internal sealed class ProposalConfiguration : IEntityTypeConfiguration<Proposal>
{
public void Configure(EntityTypeBuilder<Proposal> b)
{
b.ToTable("proposal");
b.Property(x => x.Title).HasMaxLength(200);
b.Property(x => x.Description).HasColumnType("text");
b.Property(x => x.Status).HasConversion<EnumCodeConverter<ProposalStatus>>().HasMaxLength(30);
b.HasOne<ProposalCategory>().WithMany().HasForeignKey(x => x.CategoryId);
b.HasOne<User>().WithMany().HasForeignKey(x => x.AuthorId);
}
}
internal sealed class ProposalEventConfiguration : IEntityTypeConfiguration<ProposalEvent>
{
public void Configure(EntityTypeBuilder<ProposalEvent> b)
{
b.ToTable("proposal_event");
b.Property(x => x.EventType).HasConversion<EnumCodeConverter<ProposalEventType>>().HasMaxLength(20);
b.Property(x => x.FromStatus).HasConversion<EnumCodeConverter<ProposalStatus>>().HasMaxLength(30);
b.Property(x => x.ToStatus).HasConversion<EnumCodeConverter<ProposalStatus>>().HasMaxLength(30);
b.Property(x => x.Note).HasColumnType("text");
b.HasOne(x => x.Proposal).WithMany().HasForeignKey(x => x.ProposalId);
b.HasOne<User>().WithMany().HasForeignKey(x => x.ActorId);
}
}
internal sealed class ProposalVoteConfiguration : IEntityTypeConfiguration<ProposalVote>
{
public void Configure(EntityTypeBuilder<ProposalVote> b)
{
b.ToTable("proposal_vote");
b.HasKey(x => new { x.ProposalId, x.UserId });
b.Property(x => x.Value).HasColumnType("tinyint");
b.HasOne<Proposal>().WithMany().HasForeignKey(x => x.ProposalId);
b.HasOne<User>().WithMany().HasForeignKey(x => x.UserId);
}
}
@@ -0,0 +1,136 @@
using Helpdesk.Domain.Issues;
using Helpdesk.Domain.Users;
namespace Helpdesk.UnitTests;
public sealed class IssueTests
{
private const int Reporter = 1;
private const int Manager = 2;
private const int Assignee = 3;
private const int Replacement = 4;
[Fact]
public void NewIssueStartsReceivedWithNormalPriority()
{
var issue = At(IssueStatus.Received);
Assert.Equal(IssueStatus.Received, issue.Status);
Assert.Equal(IssuePriority.Normal, issue.Priority);
Assert.Equal(0, issue.RowVersion);
Assert.Null(issue.AssigneeId);
}
[Theory]
[InlineData(IssueStatus.Received)]
[InlineData(IssueStatus.Assigned)]
[InlineData(IssueStatus.InProgress)]
public void ManagementCanAssignOrReassign(IssueStatus from)
{
var issue = At(from);
var version = issue.RowVersion;
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Assign, Manager, UserRole.Management));
issue.Assign(Manager, UserRole.Management, Replacement, UserRole.Management, IssuePriority.High);
Assert.Equal(IssueStatus.Assigned, issue.Status);
Assert.Equal(Replacement, issue.AssigneeId);
Assert.Equal(IssuePriority.High, issue.Priority);
Assert.Equal(version + 1, issue.RowVersion);
}
[Theory]
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueStatus.InProgress)]
[InlineData(IssueStatus.InProgress, IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, IssueStatus.PendingVerification)]
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Reporter, UserRole.Admin, IssueStatus.Resolved)]
[InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Reporter, UserRole.Admin, IssueStatus.InProgress)]
[InlineData(IssueStatus.Assigned, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)]
[InlineData(IssueStatus.InProgress, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)]
[InlineData(IssueStatus.Received, IssueAction.Reject, Manager, UserRole.Management, IssueStatus.Rejected)]
public void AllowedTransitionsIncrementVersion(
IssueStatus from, IssueAction action, int actorId, UserRole role, IssueStatus target)
{
var issue = At(from);
var version = issue.RowVersion;
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(action, actorId, role));
issue.Transition(action, actorId, role, "Důvod");
Assert.Equal(target, issue.Status);
Assert.Equal(version + 1, issue.RowVersion);
}
[Theory]
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Replacement, UserRole.FacilityManager, IssueActionAvailability.Forbidden)]
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Assignee, UserRole.Student, IssueActionAvailability.Forbidden)]
[InlineData(IssueStatus.Assigned, IssueAction.Reject, Manager, UserRole.Management, IssueActionAvailability.Forbidden)]
[InlineData(IssueStatus.Assigned, IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)]
[InlineData(IssueStatus.InProgress, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)]
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Assignee, UserRole.FacilityManager, IssueActionAvailability.Forbidden)]
[InlineData(IssueStatus.PendingVerification, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)]
[InlineData(IssueStatus.Resolved, IssueAction.Reopen, Reporter, UserRole.Admin, IssueActionAvailability.InvalidState)]
[InlineData(IssueStatus.Rejected, IssueAction.Reject, Manager, UserRole.Management, IssueActionAvailability.InvalidState)]
public void DisallowedTransitionsMatchAvailability(
IssueStatus from, IssueAction action, int actorId, UserRole role, IssueActionAvailability expected)
{
var issue = At(from);
var version = issue.RowVersion;
Assert.Equal(expected, issue.Availability(action, actorId, role));
Assert.Throws<InvalidOperationException>(() => issue.Transition(action, actorId, role, "Důvod"));
Assert.Equal(from, issue.Status);
Assert.Equal(version, issue.RowVersion);
}
[Theory]
[InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Reporter, UserRole.Admin)]
[InlineData(IssueStatus.Received, IssueAction.Reject, Manager, UserRole.Management)]
public void ReasonsAreRequired(IssueStatus from, IssueAction action, int actorId, UserRole role)
{
var issue = At(from);
Assert.Throws<ArgumentException>(() => issue.Transition(action, actorId, role, " "));
Assert.Equal(from, issue.Status);
}
[Fact]
public void ReassigningToSameUserKeepsWorkInProgress()
{
var issue = At(IssueStatus.InProgress);
var version = issue.RowVersion;
Assert.Throws<ArgumentException>(() =>
issue.Assign(Manager, UserRole.Management, Assignee, UserRole.FacilityManager, IssuePriority.High));
Assert.Equal(IssueStatus.InProgress, issue.Status);
Assert.Equal(version, issue.RowVersion);
}
[Fact]
public void ParticipationFollowsOwnershipAndClosesWithIssue()
{
var issue = At(IssueStatus.Assigned);
Assert.True(issue.CanRead(Reporter, UserRole.Admin));
Assert.False(issue.CanRead(Replacement, UserRole.Admin));
Assert.True(issue.CanRead(Replacement, UserRole.FacilityManager));
Assert.Equal(IssueActionAvailability.Forbidden, issue.Availability(IssueAction.Comment, Manager, UserRole.Management));
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Comment, Reporter, UserRole.Admin));
issue.RecordParticipation(IssueAction.Comment, Reporter, UserRole.Admin);
issue.Transition(IssueAction.Reject, Assignee, UserRole.FacilityManager, "Důvod");
Assert.Equal(IssueActionAvailability.InvalidState, issue.Availability(IssueAction.AddAttachments, Reporter, UserRole.Admin));
}
private static Issue At(IssueStatus result)
{
var issue = new Issue(Reporter, "Projektor", "Nefunguje", 1, null, null);
if (result == IssueStatus.Received)
return issue;
if (result == IssueStatus.Rejected)
{
issue.Transition(IssueAction.Reject, Manager, UserRole.Management, "Důvod");
return issue;
}
issue.Assign(Manager, UserRole.Management, Assignee, UserRole.FacilityManager, null);
if (result == IssueStatus.Assigned)
return issue;
issue.Transition(IssueAction.StartWork, Assignee, UserRole.FacilityManager, null);
if (result == IssueStatus.InProgress)
return issue;
issue.Transition(IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, null);
if (result == IssueStatus.Resolved)
issue.Transition(IssueAction.Confirm, Reporter, UserRole.Admin, null);
return issue;
}
}
@@ -0,0 +1,98 @@
using Helpdesk.Domain.Proposals;
using Helpdesk.Domain.Users;
namespace Helpdesk.UnitTests;
public sealed class ProposalTests
{
private const int Author = 1;
private const int Voter = 2;
[Theory]
[InlineData(ProposalStatus.Submitted, ProposalStatus.UnderReview, ProposalStatus.Accepted, ProposalStatus.Rejected)]
[InlineData(ProposalStatus.UnderReview, ProposalStatus.Accepted, ProposalStatus.Rejected)]
[InlineData(ProposalStatus.Accepted, ProposalStatus.Implemented)]
[InlineData(ProposalStatus.Rejected)]
[InlineData(ProposalStatus.Implemented)]
public void EnforcesTransitionTable(ProposalStatus from, params ProposalStatus[] permitted)
{
foreach (var target in Enum.GetValues<ProposalStatus>())
{
var proposal = At(from);
var allowed = permitted.Contains(target);
Assert.Equal(allowed, proposal.CanTransitionTo(target));
if (allowed)
{
proposal.ChangeStatus(target, UserRole.Management, "Vyjádření");
Assert.Equal(target, proposal.Status);
}
else
{
Assert.Throws<InvalidOperationException>(() => proposal.ChangeStatus(target, UserRole.Management, null));
Assert.Equal(from, proposal.Status);
}
}
}
[Fact]
public void ReviewRequiresManagementAndRejectionRequiresNote()
{
var proposal = At(ProposalStatus.Submitted);
Assert.Throws<InvalidOperationException>(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null));
Assert.Throws<ArgumentException>(() => proposal.ChangeStatus(ProposalStatus.Rejected, UserRole.Management, " "));
Assert.Equal(ProposalStatus.Submitted, proposal.Status);
}
[Theory]
[InlineData(ProposalStatus.Submitted, true, true)]
[InlineData(ProposalStatus.UnderReview, false, true)]
[InlineData(ProposalStatus.Accepted, false, false)]
[InlineData(ProposalStatus.Rejected, false, false)]
[InlineData(ProposalStatus.Implemented, false, false)]
public void AuthorEditsAndOtherUserVotesOnlyInEligibleStates(ProposalStatus state, bool mayEdit, bool mayVote)
{
var proposal = At(state);
Assert.Equal(mayEdit, proposal.CanEdit(Author));
Assert.False(proposal.CanEdit(Voter));
Assert.False(proposal.CanVote(Author));
Assert.Equal(mayVote, proposal.CanVote(Voter));
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Voter, "Změna", "Popis", 1));
if (mayEdit)
{
proposal.Edit(Author, "Změna", "Popis", 1);
Assert.Equal("Změna", proposal.Title);
}
else
{
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Author, "Změna", "Popis", 1));
}
}
[Fact]
public void RepeatingVotePreservesTimestampAndClosingPreventsChanges()
{
var proposal = At(ProposalStatus.Submitted);
var now = DateTime.UnixEpoch;
Assert.Throws<InvalidOperationException>(() => new ProposalVote(proposal, Author, 1, now));
Assert.Throws<ArgumentOutOfRangeException>(() => new ProposalVote(proposal, Voter, 0, now));
var vote = new ProposalVote(proposal, Voter, 1, now);
vote.SetValue(proposal, 1, now.AddMinutes(1));
Assert.Equal(now, vote.VotedAt);
vote.SetValue(proposal, -1, now.AddMinutes(2));
Assert.Equal((sbyte)-1, vote.Value);
Assert.Equal(now.AddMinutes(2), vote.VotedAt);
proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Management, null);
Assert.Throws<InvalidOperationException>(() => vote.SetValue(proposal, 1, now.AddMinutes(3)));
}
private static Proposal At(ProposalStatus status)
{
var proposal = new Proposal(Author, "Návrh", "Popis", 1);
if (status == ProposalStatus.Implemented)
proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Management, null);
if (status != ProposalStatus.Submitted)
proposal.ChangeStatus(status, UserRole.Management, "Vyjádření");
return proposal;
}
}
@@ -0,0 +1,3 @@
-- Registrační token FCM rozlišuje velikost písmen.
ALTER TABLE push_device
MODIFY fcm_token VARCHAR(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL;
@@ -0,0 +1 @@
CREATE INDEX ix_proposal_created_at ON proposal (created_at);
+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:
+48 -42
View File
@@ -90,9 +90,9 @@ Legenda: ✅ povoleno, 🔸 povoleno s podmínkou, — nepovoleno
| Centrální přehled všech závad (filtry) | — | ✅ (jen čtení) | ✅ | — | | Centrální přehled všech závad (filtry) | — | ✅ (jen čtení) | ✅ | — |
| Přiřadit / přeřadit závadu řešiteli, nastavit prioritu | — | — | ✅ | — | | Přiřadit / přeřadit závadu řešiteli, nastavit prioritu | — | — | ✅ | — |
| Zahájit řešení, předat k ověření | — | 🔸 jen přiřazené jemu | 🔸 jen přiřazené jemu | — | | Zahájit řešení, předat k ověření | — | 🔸 jen přiřazené jemu | 🔸 jen přiřazené jemu | — |
| Zamítnout závadu (s důvodem) | — | 🔸 jen přiřazené jemu | 🔸 přiřazené jemu + ve stavu *Přijata* | — | | Zamítnout závadu (s důvodem) | — | 🔸 jen přiřazené jemu | 🔸 přiřazené jemu nebo nepřiřazené ve stavu *Přijata* | — |
| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | — | | Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič |
| Komentovat závadu | 🔸 hlásič | 🔸 hlásič nebo řešitel | 🔸 hlásič nebo řešitel; ostatní jen čtení | — | | Komentovat závadu | 🔸 hlásič | 🔸 hlásič nebo řešitel | 🔸 hlásič nebo řešitel; ostatní jen čtení | 🔸 hlásič |
| Podat návrh na zlepšení | ✅ | ✅ | ✅ | ✅ | | Podat návrh na zlepšení | ✅ | ✅ | ✅ | ✅ |
| Zobrazit všechny návrhy | ✅ | ✅ | ✅ | ✅ | | Zobrazit všechny návrhy | ✅ | ✅ | ✅ | ✅ |
| Hlasovat pro návrh | 🔸 ne pro vlastní | 🔸 | 🔸 | 🔸 | | Hlasovat pro návrh | 🔸 ne pro vlastní | 🔸 | 🔸 | 🔸 |
@@ -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,10 +508,11 @@ 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ě. |
| Zápisy závad | Vytvoření závady, přidání komentáře a nahrání příloh mají společný limit 10 požadavků za minutu na účet a instanci API. Překročení vrací 429. |
| Vstupy | Validace DTO (FluentValidation), parametrizované dotazy (EF Core), HTML výstup kódován Razorem (XSS), anti-forgery tokeny ve webových formulářích (CSRF). | | Vstupy | Validace DTO (FluentValidation), parametrizované dotazy (EF Core), HTML výstup kódován Razorem (XSS), anti-forgery tokeny ve webových formulářích (CSRF). |
| Tajemství | JWT klíč, DB heslo, šifrovací klíč, SMTP a Firebase přístupy pouze v proměnných prostředí / `.env` mimo Git. | | Tajemství | JWT klíč, DB heslo, šifrovací klíč, SMTP a Firebase přístupy pouze v proměnných prostředí / `.env` mimo Git. |
@@ -537,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):
@@ -569,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í.
@@ -577,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` |
@@ -595,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`).
@@ -626,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ý
``` ```
@@ -642,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 |
@@ -660,23 +665,24 @@ Všechny endpointy mají prefix `/api`, formát JSON, chyby ve formátu **Proble
### Hlášení závad ### Hlášení závad
| Metoda | Endpoint | Role | Popis | | Metoda | Endpoint | Role | Popis |
|---|---|---|---| |---|---|---|---|
| GET | `/issues` | přihlášený | Seznam; filtry `status`, `categoryId`, `buildingId`, `assigneeId`, `reporterId`, `from`, `to`, `q`, `mine`; řazení `sort`. Student/vyučující dostane jen vlastní. | | GET | `/issues` | přihlášený | Seznam; filtry `status`, `categoryId`, `buildingId`, `assigneeId`, `reporterId`, `from`, `to`, `q`, `mine`; řazení `sort=newest\|oldest`. Student, vyučující a administrátor vidí jen vlastní. |
| POST | `/issues` | přihlášený | Vytvoření hlášení (T1) | | POST | `/issues` | přihlášený | Vytvoření hlášení (T1), JSON do 1 MiB nebo multipart s poli hlášení a soubory v poli `files` |
| GET | `/issues/{id}` | účastník / správce / vedení | Detail vč. `allowedActions` a `rowVersion` | | GET | `/issues/{id}` | účastník / správce / vedení | Detail vč. `allowedActions` a `rowVersion` |
| PUT | `/issues/{id}` | hlásič | Úprava ve stavu Přijata | | PUT | `/issues/{id}` | hlásič | Úprava ve stavu Přijata s `rowVersion` |
| POST | `/issues/{id}/assign` | vedení | `{ assigneeId, priority?, rowVersion }` (T2, T3) | | POST | `/issues/{id}/assign` | vedení | `{ assigneeId, priority?, rowVersion }` (T2, T3) |
| POST | `/issues/{id}/start` | řešitel | T4 | | POST | `/issues/{id}/start` | řešitel | `{ rowVersion }` (T4) |
| POST | `/issues/{id}/submit-for-verification` | řešitel | `{ note? }` (T5) | | POST | `/issues/{id}/submit-for-verification` | řešitel | `{ rowVersion, note? }` (T5) |
| POST | `/issues/{id}/confirm` | hlásič | T6 | | POST | `/issues/{id}/confirm` | hlásič | `{ rowVersion }` (T6) |
| POST | `/issues/{id}/reopen` | hlásič | `{ reason }` (T7) | | POST | `/issues/{id}/reopen` | hlásič | `{ rowVersion, reason }` (T7) |
| POST | `/issues/{id}/reject` | řešitel / vedení | `{ reason }` (T8, T9) | | POST | `/issues/{id}/reject` | řešitel / vedení | `{ rowVersion, reason }` (T8, T9) |
| GET | `/issues/{id}/events` | jako detail | Časová osa – všechny události včetně komentářů (`issue_event`) | | GET | `/issues/{id}/events` | jako detail | Časová osa – všechny události včetně komentářů (`issue_event`) |
| POST | `/issues/{id}/comments` | hlásič, řešitel | `{ text }` – zapíše událost `COMMENTED` | | POST | `/issues/{id}/comments` | hlásič, řešitel | `{ text }` – zapíše událost `COMMENTED` |
| POST | `/issues/{id}/attachments` | hlásič, řešitel | `multipart/form-data` | | POST | `/issues/{id}/attachments` | hlásič, řešitel | `multipart/form-data`, 1–5 souborů v poli `files` |
| GET | `/attachments/{id}` | jako detail závady | Stažení souboru | | GET | `/attachments/{id}` | jako detail závady | Stažení souboru |
| GET | `/users/assignable` | vedení | Možní řešitelé s počtem otevřených závad | | GET | `/users/assignable` | vedení | Možní řešitelé s počtem otevřených závad |
Přechody stavů jsou záměrně **samostatné akční endpointy** místo obecného `PATCH status` – každý má vlastní vstupní data, oprávnění a je jednoznačně zdokumentovaný ve Swaggeru. Přechody stavů jsou záměrně **samostatné akční endpointy** místo obecného `PATCH status` – každý má vlastní vstupní data, oprávnění a je jednoznačně zdokumentovaný ve Swaggeru.
Po přidání komentáře nebo příloh klient znovu načte detail, aby získal aktuální `rowVersion`.
### Návrhy na zlepšení ### Návrhy na zlepšení
| Metoda | Endpoint | Role | Popis | | Metoda | Endpoint | Role | Popis |
@@ -1121,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
@@ -1143,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
@@ -1153,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 |
@@ -1164,7 +1170,7 @@ flowchart LR
| Služba | Image | Sítě | Porty | Úložiště | Poznámka | | Služba | Image | Sítě | Porty | Úložiště | Poznámka |
|---|---|---|---|---|---| |---|---|---|---|---|---|
| `proxy` | `nginx` | frontend | **80, 443 publikované** | certifikáty | TLS (vývoj: `mkcert`, produkce: Let's Encrypt), HSTS, limit velikosti požadavku 50 MB (5 příloh × 10 MB) | | `proxy` | `nginx` | frontend | **80, 443 publikované** | certifikáty | TLS (vývoj: `mkcert`, produkce: Let's Encrypt), HSTS, limit velikosti požadavku 51 MiB (5 příloh × 10 MiB a režie multipart) |
| `web` | vlastní (`dotnet/aspnet`) | frontend | interně 8080 | `web-keys` | klíče ASP.NET Core Data Protection pro šifrované cookie (bez persistence by restart odhlásil všechny uživatele) | | `web` | vlastní (`dotnet/aspnet`) | frontend | interně 8080 | `web-keys` | klíče ASP.NET Core Data Protection pro šifrované cookie (bez persistence by restart odhlásil všechny uživatele) |
| `api` | vlastní (`dotnet/aspnet`) | frontend, backend | interně 8080 | `uploads` | Swagger na `/swagger`, `GET /health`, vytvoření admin účtu z env | | `api` | vlastní (`dotnet/aspnet`) | frontend, backend | interně 8080 | `uploads` | Swagger na `/swagger`, `GET /health`, vytvoření admin účtu z env |
| `migrator` | vlastní (`dotnet/runtime`) | backend | — | — | aplikuje nové migrace z `db/migrations` a skončí | | `migrator` | vlastní (`dotnet/runtime`) | backend | — | — | aplikuje nové migrace z `db/migrations` a skončí |
@@ -1234,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 {
authorized { api.buildings(it) }, authorized { api.issueCategories(it) }, authorized { api.proposalCategories(it) }, // 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) },
).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> {
api.issues(it, page, query.takeIf(String::isNotBlank), status, !assigned, if (assigned) requireSession().user.id else null) val result = authorized {
api.issues(it, page, query.takeIf(String::isNotBlank), status, !assigned, if (assigned) requireSession().user.id else null)
}
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 issue(id: Int): Issue = authorized(planned = true) { bearer -> override suspend fun issue(id: Int): Issue {
val issue = api.issue(bearer, id) val detail = authorized { api.issue(it, id) }
issue.copy(events = api.events(bearer, id)) val events = authorized { api.events(it, id) }
return detail.toModel(catalogs(), requireSession().user, events)
} }
override suspend fun createIssue(issue: NewIssue): Issue = authorized(planned = true) { api.createIssue(it, issue) } override suspend fun createIssue(issue: NewIssue): Issue {
override suspend fun updateIssue(id: Int, issue: NewIssue, rowVersion: Int): Issue = authorized(planned = true) { val catalog = catalogs()
api.updateIssue(it, id, UpdateIssueRequest(issue.title, issue.description, issue.categoryId, issue.buildingId, issue.location, rowVersion)) 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) { override suspend fun proposals(page: Int, query: String, sort: String): Page<Proposal> {
api.proposals(it, page, query.takeIf(String::isNotBlank), sort) 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 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 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 {
repository.register(email.trim(), password, firstName.trim(), lastName.trim()) try {
state.update { it.copy(authMessage = "Registrace je hotová. Ověřte e-mail odkazem ze zprávy a pak se přihlaste.") } repository.register(email.trim(), password, firstName.trim(), lastName.trim())
} catch (error: ApiException) {
// Main saves an unconfirmed account before sending its verification email.
// A manual retry with the same credentials resends the email instead of duplicating it.
if (error.status == 503) throw ApiException(503, "${error.message}\nZkuste registraci znovu se stejným e-mailem a heslem.")
throw error
}
state.update { it.copy(authMessage = "Registrace je hotová. Ověřte e-mail odkazem ze zprávy a pak se přihlaste.", authOutcome = AuthOutcome.REGISTERED) }
} }
fun forgotPassword(email: String) = operation { fun forgotPassword(email: String) = operation {
repository.forgotPassword(email.trim()) repository.forgotPassword(email.trim())
state.update { it.copy(authMessage = "Pokud účet existuje, obdržíte e-mail s odkazem pro obnovu hesla.") } state.update { it.copy(authMessage = "Požadavek byl přijat. Pokud účet existuje a e-mail se podaří doručit, obdržíte odkaz pro obnovu hesla.") }
} }
fun confirmEmail(token: String) = operation { fun confirmEmail(token: String) = operation {
repository.confirmEmail(extractToken(token)) repository.confirmEmail(extractEmailActionToken(token, EmailAction.CONFIRM))
state.update { it.copy(authMessage = "E-mail je ověřený. Nyní se můžete přihlásit.") } state.update { it.copy(authMessage = "E-mail je ověřený. Nyní se můžete přihlásit.", authOutcome = AuthOutcome.EMAIL_CONFIRMED) }
} }
fun resetPassword(token: String, password: String) = operation { fun resetPassword(token: String, password: String) = operation {
repository.resetPassword(extractToken(token), password) repository.resetPassword(extractEmailActionToken(token, EmailAction.RESET), password)
state.update { it.copy(authMessage = "Heslo bylo změněno. Přihlaste se novým heslem.") } state.update { it.copy(authMessage = "Heslo bylo změněno. Přihlaste se novým heslem.", authOutcome = AuthOutcome.PASSWORD_RESET) }
} }
fun clearFeedback() { state.update { it.copy(error = null, message = null, authMessage = null) } } fun consumeAuthOutcome(outcome: AuthOutcome) {
state.update { if (it.authOutcome == outcome) it.copy(authOutcome = null) else it }
}
fun clearFeedback() { state.update { it.copy(error = null, message = null, authMessage = null, authOutcome = null) } }
fun dismissMessage() { state.update { it.copy(message = null) } } fun dismissMessage() { state.update { it.copy(message = null) } }
fun logout(allDevices: Boolean) { fun logout(allDevices: Boolean) {
@@ -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)
val detail = repository.issue(id) onSaved()
state.update { it.copy(issue = detail, message = "Přílohy byly přidány.") } 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)
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,50 +85,69 @@ 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
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { val canVote = enabled && proposal.authorId != userId && votingOpen
FilterChip(selected = proposal.myVote == 1, onClick = { onVote(if (proposal.myVote == 1) null else 1) }, enabled = canVote, Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
label = { Text("Pro") }, leadingIcon = { Icon(Icons.Rounded.ThumbUp, null, Modifier.size(16.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("Proti") }, leadingIcon = { Icon(Icons.Rounded.ThumbDown, null, Modifier.size(16.dp)) }) label = { Text("Pro") }, leadingIcon = { Icon(Icons.Rounded.ThumbUp, null, Modifier.size(16.dp)) })
Spacer(Modifier.weight(1f)) FilterChip(selected = proposal.myVote == -1, onClick = { if (canVote) onVote(if (proposal.myVote == -1) null else -1) }, enabled = canVote,
Column(horizontalAlignment = Alignment.End) { label = { Text("Proti") }, leadingIcon = { Icon(Icons.Rounded.ThumbDown, null, Modifier.size(16.dp)) })
Text(proposal.score.toString(), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary) Spacer(Modifier.weight(1f))
Text("skóre", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant) Column(horizontalAlignment = Alignment.End) {
Text(proposal.score.toString(), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)
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
fun NewProposalScreen(catalogs: Catalogs, busy: Boolean, onSubmit: (NewProposal) -> Unit) { fun NewProposalScreen(catalogs: Catalogs, busy: Boolean, onSubmit: (NewProposal) -> Unit) {
var title by rememberSaveable { mutableStateOf("") } var title by rememberSaveable { mutableStateOf("") }
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 })
}
}