Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46f3b21a0b | ||
|
|
c4fe447d9d | ||
|
|
a1bf12ba72 | ||
|
|
79772e10ce | ||
|
|
a65516b810 | ||
|
|
d056b54f50 |
No files matched your search
@@ -3,13 +3,8 @@
|
|||||||
!backend/Directory.Packages.props
|
!backend/Directory.Packages.props
|
||||||
!backend/src/
|
!backend/src/
|
||||||
!db/migrations/
|
!db/migrations/
|
||||||
!web/Directory.Build.props
|
|
||||||
!web/Directory.Packages.props
|
|
||||||
!web/Helpdesk.Web/
|
|
||||||
backend/**/bin
|
backend/**/bin
|
||||||
backend/**/obj
|
backend/**/obj
|
||||||
web/**/bin
|
|
||||||
web/**/obj
|
|
||||||
**/.env
|
**/.env
|
||||||
**/*.env
|
**/*.env
|
||||||
**/*.pem
|
**/*.pem
|
||||||
|
|||||||
@@ -2,3 +2,5 @@
|
|||||||
* text=auto
|
* text=auto
|
||||||
*.sh text eol=lf
|
*.sh text eol=lf
|
||||||
*.sql text eol=lf
|
*.sql text eol=lf
|
||||||
|
gradlew text eol=lf
|
||||||
|
*.bat text eol=crlf
|
||||||
@@ -55,6 +55,7 @@ replay_pid*
|
|||||||
|
|
||||||
# Gradle wrapper se do repozitáře commituje (jinak by šablona výše vyřadila *.jar)
|
# Gradle wrapper se do repozitáře commituje (jinak by šablona výše vyřadila *.jar)
|
||||||
!gradle/wrapper/gradle-wrapper.jar
|
!gradle/wrapper/gradle-wrapper.jar
|
||||||
|
!**/gradle/wrapper/gradle-wrapper.jar
|
||||||
|
|
||||||
# ---> Android / Gradle
|
# ---> Android / Gradle
|
||||||
.gradle/
|
.gradle/
|
||||||
|
|||||||
@@ -11,10 +11,10 @@ Univerzitní helpdesk a portál návrhů na zlepšení – semestrální práce
|
|||||||
| [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) – schéma, číselníky a porovnávání FCM tokenů |
|
| [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) |
|
||||||
| [web/](web/) | Webová aplikace ASP.NET Core MVC – tenký klient REST API |
|
| [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` |
|
||||||
|
|
||||||
## Spuštění (Docker)
|
## Spuštění backendu (Docker)
|
||||||
|
|
||||||
Potřeba je jen Docker Desktop.
|
Potřeba je jen Docker Desktop.
|
||||||
|
|
||||||
@@ -24,23 +24,25 @@ Potřeba je jen Docker Desktop.
|
|||||||
cp deploy/.env.example deploy/.env
|
cp deploy/.env.example deploy/.env
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Spusťte databázi, migrace, API a web:
|
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:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
|
docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Webová aplikace: <http://localhost:8081> · Swagger UI po přihlášení administrátora: <http://localhost:8081/swagger> · stav a verze schématu: <http://localhost:8080/health>
|
3. Swagger UI: <http://localhost:8080/swagger> · stav a verze schématu: <http://localhost:8080/health>
|
||||||
|
|
||||||
Lokálně bez reverse proxy nastavte `PUBLIC_BASE_URL=http://localhost:8081`, aby odkazy pro ověření e-mailu a obnovu hesla vedly na web v Dockeru.
|
Při 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, 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`.
|
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.
|
Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adresu webu v `PUBLIC_BASE_URL` a skutečné univerzitní domény v `STUDENT_EMAIL_DOMAIN` a `TEACHER_EMAIL_DOMAIN`. Pro Email Profi vyplňte `SMTP_MAILBOX` celou adresou schránky a nastavte `SMTP_PASSWORD`. API odesílá přes `smtp.seznam.cz:465` s TLS.
|
||||||
|
|
||||||
Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS`: `/api/*` na port `API_HTTP_PORT` (výchozí `8080`) a ostatní cesty včetně `/swagger` na web na port `WEB_HTTP_PORT` (výchozí `8081`). Výchozí adresa `127.0.0.1` odpovídá proxy běžící přímo na stejném hostiteli. Swagger UI ověřuje administrátorskou relaci webu. Funkce **Try it out** vyžaduje, aby stejná adresa přes proxy směrovala i `/api/*`, a chráněná volání autorizuje access tokenem.
|
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.
|
||||||
|
|
||||||
Serverová reverse proxy předává IP klienta v `X-Forwarded-For` a schéma v `X-Forwarded-Proto`. Nastavte `TRUSTED_REVERSE_PROXY_IP` na IP bezprostředního protějšku, kterou vidí API a web. Tato IP se může při průchodu Docker sítí lišit od adresy, na kterou je API vázáno. Compose automaticky nastaví privátní síť a důvěryhodnou adresu webu, přes kterou web předává IP klienta dál do API.
|
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.
|
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.
|
||||||
|
|
||||||
@@ -52,43 +54,18 @@ Vyžaduje .NET SDK 10. Unit testy:
|
|||||||
dotnet run --project backend/tests/Helpdesk.UnitTests/Helpdesk.UnitTests.csproj
|
dotnet run --project backend/tests/Helpdesk.UnitTests/Helpdesk.UnitTests.csproj
|
||||||
```
|
```
|
||||||
|
|
||||||
Webová aplikace proti API běžícímu v Dockeru (otevře se na <http://localhost:5080>):
|
## Mobilní aplikace
|
||||||
|
|
||||||
```bash
|
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/`.
|
||||||
dotnet run --project web/Helpdesk.Web
|
|
||||||
```
|
|
||||||
|
|
||||||
Testy webové aplikace:
|
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.
|
||||||
|
|
||||||
```bash
|
Podrobný postup sestavení, rozsah funkcí a stav napojení na API: [mobile/README.md](mobile/README.md).
|
||||||
dotnet test --solution web/Helpdesk.Web.sln
|
|
||||||
```
|
|
||||||
|
|
||||||
### Integrační testy backendu
|
|
||||||
|
|
||||||
Vyžadují .NET SDK 10 a spuštěný Docker. Testcontainers vytvoří dočasnou MariaDB 11.4 a testy spustí skutečné migrace.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
dotnet run --project backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj
|
|
||||||
```
|
|
||||||
|
|
||||||
Pokrytí backendu integračními testy se ukládá jako Cobertura XML do `TestResults` ve výstupu testovacího projektu.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
dotnet run --project backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj -- \
|
|
||||||
--coverage --coverage-output-format cobertura --coverage-output backend-coverage.cobertura.xml \
|
|
||||||
--coverage-settings "$PWD/backend/tests/Helpdesk.IntegrationTests/coverage.settings.xml"
|
|
||||||
```
|
|
||||||
|
|
||||||
## Verzování databáze
|
## Verzování databáze
|
||||||
|
|
||||||
Schéma se mění výhradně novými číslovanými skripty `db/migrations/V{NNN}__{popis}.sql`. Provedený skript se nikdy neupravuje. Migrace spouští DbUp (`Helpdesk.Migrator`) před startem API a eviduje je v tabulce `schema_version`.
|
Schéma se mění výhradně novými číslovanými skripty `db/migrations/V{NNN}__{popis}.sql`. Provedený skript se nikdy neupravuje. Migrace spouští DbUp (`Helpdesk.Migrator`) před startem API a eviduje je v tabulce `schema_version`.
|
||||||
|
|
||||||
## Verzování webové aplikace
|
|
||||||
|
|
||||||
- **Verze API:** web volá REST API `/api/v1`. Verze je na jednom místě, `ApiOptions.ApiVersion` v `web/Helpdesk.Web/Api/ApiOptions.cs`. Klienti API používají jen relativní cesty (`issues`, `auth/login`), takže přechod na `/api/v2` znamená změnit tuto konstantu a upravit DTO, která se ve v2 změnila.
|
|
||||||
- **Verze webu:** `<Version>` v `web/Helpdesk.Web/Helpdesk.Web.csproj` podle semver – před vydáním 1.0 zvyšujeme MINOR za novou část aplikace (závady, návrhy, …) a PATCH za opravy. Verze se zobrazuje v patičce webu spolu s krátkým hashem commitu, ze kterého byl web sestaven.
|
|
||||||
|
|
||||||
## Technologie
|
## Technologie
|
||||||
|
|
||||||
Backend C# / ASP.NET Core Web API · EF Core + Pomelo (MariaDB) · DbUp · JWT (RFC 7519) · Swagger · Web ASP.NET Core MVC · Mobil Kotlin + Jetpack Compose · Docker
|
Backend C# / ASP.NET Core Web API · EF Core + Pomelo (MariaDB) · DbUp · JWT (RFC 7519) · Swagger · Web ASP.NET Core MVC · Mobil Kotlin + Jetpack Compose · Docker
|
||||||
|
|||||||
@@ -15,17 +15,14 @@
|
|||||||
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.14" />
|
<PackageVersion Include="Microsoft.Extensions.Caching.Memory" Version="10.0.14" />
|
||||||
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.14" />
|
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.14" />
|
||||||
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.14" />
|
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.14" />
|
||||||
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerGen" 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="MailKit" Version="5.0.0" />
|
||||||
<PackageVersion Include="FirebaseAdmin" Version="3.7.1" />
|
<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 -->
|
||||||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
|
|
||||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
||||||
<PackageVersion Include="Microsoft.Testing.Extensions.CodeCoverage" Version="18.12.0" />
|
|
||||||
<PackageVersion Include="Testcontainers.MariaDb" Version="4.16.0" />
|
|
||||||
<PackageVersion Include="xunit.v3" Version="4.0.2" />
|
<PackageVersion Include="xunit.v3" Version="4.0.2" />
|
||||||
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
|
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Migrator", "src\He
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.UnitTests", "tests\Helpdesk.UnitTests\Helpdesk.UnitTests.csproj", "{AB40F473-EB15-47C7-B179-A8EB066325EC}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.UnitTests", "tests\Helpdesk.UnitTests\Helpdesk.UnitTests.csproj", "{AB40F473-EB15-47C7-B179-A8EB066325EC}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.IntegrationTests", "tests\Helpdesk.IntegrationTests\Helpdesk.IntegrationTests.csproj", "{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}"
|
|
||||||
EndProject
|
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -99,18 +97,6 @@ Global
|
|||||||
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x64.Build.0 = Release|Any CPU
|
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.ActiveCfg = Release|Any CPU
|
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.Build.0 = Release|Any CPU
|
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.Build.0 = Release|Any CPU
|
||||||
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x64.ActiveCfg = Debug|Any CPU
|
|
||||||
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x64.Build.0 = Debug|Any CPU
|
|
||||||
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x86.ActiveCfg = Debug|Any CPU
|
|
||||||
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x86.Build.0 = Debug|Any CPU
|
|
||||||
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x64.ActiveCfg = Release|Any CPU
|
|
||||||
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x64.Build.0 = Release|Any CPU
|
|
||||||
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x86.ActiveCfg = Release|Any CPU
|
|
||||||
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x86.Build.0 = Release|Any CPU
|
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ public sealed class ProposalsController(ProposalService proposals) : ControllerB
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost("{id:int}/status")]
|
[HttpPost("{id:int}/status")]
|
||||||
[Authorize(Roles = Roles.ManagementOrAdmin)]
|
[Authorize(Roles = Roles.Management)]
|
||||||
[RequestSizeLimit(1024 * 1024)]
|
[RequestSizeLimit(1024 * 1024)]
|
||||||
public Task<ProposalDetail> ChangeStatus(int id, ChangeProposalStatusRequest request, CancellationToken ct) =>
|
public Task<ProposalDetail> ChangeStatus(int id, ChangeProposalStatusRequest request, CancellationToken ct) =>
|
||||||
proposals.ChangeStatusAsync(id, request, ct);
|
proposals.ChangeStatusAsync(id, request, ct);
|
||||||
|
|||||||
@@ -6,9 +6,9 @@ using Microsoft.AspNetCore.Mvc;
|
|||||||
|
|
||||||
namespace Helpdesk.Api.Controllers;
|
namespace Helpdesk.Api.Controllers;
|
||||||
|
|
||||||
/// <summary>Statistiky pro vedení školy a administrátory. Období v UTC zahrnuje začátek a vylučuje konec.</summary>
|
/// <summary>Statistiky pro vedení školy. Období v UTC zahrnuje začátek a vylučuje konec.</summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Authorize(Roles = Roles.ManagementOrAdmin)]
|
[Authorize(Roles = Roles.Management)]
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
[Route(ApiRoutes.V1 + "/statistics")]
|
[Route(ApiRoutes.V1 + "/statistics")]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ public sealed class UsersController(UserService users, ICurrentUser currentUser,
|
|||||||
|
|
||||||
/// <summary>Aktivní řešitelé s počtem otevřených závad.</summary>
|
/// <summary>Aktivní řešitelé s počtem otevřených závad.</summary>
|
||||||
[HttpGet("assignable")]
|
[HttpGet("assignable")]
|
||||||
[Authorize(Roles = Roles.ManagementOrAdmin)]
|
[Authorize(Roles = Roles.Management)]
|
||||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||||
public Task<IReadOnlyList<AssignableUserDto>> GetAssignable(CancellationToken ct) => issues.GetAssignableAsync(ct);
|
public Task<IReadOnlyList<AssignableUserDto>> GetAssignable(CancellationToken ct) => issues.GetAssignableAsync(ct);
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" />
|
<PackageReference Include="Swashbuckle.AspNetCore" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -8,5 +8,4 @@ public static class Roles
|
|||||||
public const string FacilityManager = "FACILITY_MANAGER";
|
public const string FacilityManager = "FACILITY_MANAGER";
|
||||||
public const string Management = "MANAGEMENT";
|
public const string Management = "MANAGEMENT";
|
||||||
public const string Admin = "ADMIN";
|
public const string Admin = "ADMIN";
|
||||||
public const string ManagementOrAdmin = Management + "," + Admin;
|
|
||||||
}
|
}
|
||||||
@@ -9,7 +9,7 @@ public static class SwaggerSetup
|
|||||||
{
|
{
|
||||||
private const string SchemeId = "Bearer";
|
private const string SchemeId = "Bearer";
|
||||||
|
|
||||||
/// <summary>Generování OpenAPI dokumentu pro administrátorské Swagger UI (NFR-04).</summary>
|
/// <summary>Swagger UI na <c>/swagger</c> včetně přihlášení access tokenem (NFR-04).</summary>
|
||||||
public static IServiceCollection AddHelpdeskSwagger(this IServiceCollection services)
|
public static IServiceCollection AddHelpdeskSwagger(this IServiceCollection services)
|
||||||
{
|
{
|
||||||
services.AddEndpointsApiExplorer();
|
services.AddEndpointsApiExplorer();
|
||||||
|
|||||||
@@ -30,21 +30,18 @@ builder.Services.AddProblemDetails();
|
|||||||
builder.Services.AddExceptionHandler<AppExceptionHandler>();
|
builder.Services.AddExceptionHandler<AppExceptionHandler>();
|
||||||
builder.Services.AddHelpdeskSwagger();
|
builder.Services.AddHelpdeskSwagger();
|
||||||
|
|
||||||
var trustedProxies = new[] { "ReverseProxy:TrustedIp", "ReverseProxy:TrustedWebIp" }
|
var trustedProxy = builder.Configuration["ReverseProxy:TrustedIp"];
|
||||||
.Where(key => !string.IsNullOrWhiteSpace(builder.Configuration[key]))
|
if (!string.IsNullOrWhiteSpace(trustedProxy))
|
||||||
.Select(key => IPAddress.TryParse(builder.Configuration[key], out var address) ? address
|
|
||||||
: throw new InvalidOperationException($"Nastavte platnou IP adresu v {key}."))
|
|
||||||
.ToArray();
|
|
||||||
|
|
||||||
if (trustedProxies.Length > 0)
|
|
||||||
{
|
{
|
||||||
|
if (!IPAddress.TryParse(trustedProxy, out var proxyAddress))
|
||||||
|
throw new InvalidOperationException("Nastavte platnou IP adresu důvěryhodné reverse proxy.");
|
||||||
|
|
||||||
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
||||||
{
|
{
|
||||||
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
||||||
options.KnownIPNetworks.Clear();
|
options.KnownIPNetworks.Clear();
|
||||||
options.KnownProxies.Clear();
|
options.KnownProxies.Clear();
|
||||||
foreach (var address in trustedProxies)
|
options.KnownProxies.Add(proxyAddress);
|
||||||
options.KnownProxies.Add(address);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,14 +49,9 @@ if (trustedProxies.Length > 0)
|
|||||||
builder.Services.AddRateLimiter(options =>
|
builder.Services.AddRateLimiter(options =>
|
||||||
{
|
{
|
||||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
options.AddPolicy(RateLimitPolicies.Auth, http =>
|
options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter(
|
||||||
{
|
http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
|
||||||
var address = http.Connection.RemoteIpAddress;
|
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) }));
|
||||||
if (address is { IsIPv4MappedToIPv6: true })
|
|
||||||
address = address.MapToIPv4();
|
|
||||||
return RateLimitPartition.GetFixedWindowLimiter(address?.ToString() ?? "unknown",
|
|
||||||
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) });
|
|
||||||
});
|
|
||||||
options.AddPolicy(RateLimitPolicies.IssueWrites, http => RateLimitPartition.GetSlidingWindowLimiter(
|
options.AddPolicy(RateLimitPolicies.IssueWrites, http => RateLimitPartition.GetSlidingWindowLimiter(
|
||||||
http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown",
|
http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown",
|
||||||
_ => new SlidingWindowRateLimiterOptions
|
_ => new SlidingWindowRateLimiterOptions
|
||||||
@@ -72,18 +64,23 @@ builder.Services.AddRateLimiter(options =>
|
|||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
if (trustedProxies.Length > 0)
|
if (!string.IsNullOrWhiteSpace(trustedProxy))
|
||||||
app.UseForwardedHeaders();
|
app.UseForwardedHeaders();
|
||||||
|
|
||||||
app.UseExceptionHandler();
|
app.UseExceptionHandler();
|
||||||
app.UseStatusCodePages();
|
app.UseStatusCodePages();
|
||||||
|
|
||||||
|
app.UseSwagger();
|
||||||
|
app.UseSwaggerUI(options =>
|
||||||
|
{
|
||||||
|
options.SwaggerEndpoint("/swagger/v1/swagger.json", "Helpdesk API v1");
|
||||||
|
options.DocumentTitle = "Helpdesk API";
|
||||||
|
});
|
||||||
|
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
app.UseRateLimiter();
|
app.UseRateLimiter();
|
||||||
|
|
||||||
app.MapSwagger(ApiRoutes.V1 + "/admin/openapi/{documentName}.json")
|
|
||||||
.RequireAuthorization(policy => policy.RequireRole(Roles.Admin));
|
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ public interface IAppDbContext
|
|||||||
DbSet<PushDevice> PushDevices { get; }
|
DbSet<PushDevice> PushDevices { get; }
|
||||||
|
|
||||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
||||||
Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct);
|
Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct);
|
||||||
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
||||||
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
|
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -95,23 +95,17 @@ public sealed class AuthService(
|
|||||||
var token = await tokens.ValidateAsync(request.RefreshToken, TokenType.Refresh)
|
var token = await tokens.ValidateAsync(request.RefreshToken, TokenType.Refresh)
|
||||||
?? throw new UnauthorizedException("Neplatný refresh token.");
|
?? throw new UnauthorizedException("Neplatný refresh token.");
|
||||||
|
|
||||||
// Původní token zůstane zamčený, dokud není nový pár uložený.
|
if (!await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
|
||||||
await using (var transaction = await db.BeginWriteAsync(ct))
|
|
||||||
{
|
{
|
||||||
if (await revocation.TryConsumeAsync(token.Jti, TokenType.Refresh, ct))
|
await revocation.RevokeAllAsync(token.UserId, RevokeReason.ReuseDetected, ct);
|
||||||
{
|
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
|
||||||
var user = await db.Users.SingleOrDefaultAsync(u => u.Id == token.UserId, ct);
|
|
||||||
if (user is null || !user.IsActive)
|
|
||||||
throw new UnauthorizedException("Účet neexistuje nebo je deaktivován.");
|
|
||||||
|
|
||||||
var response = await IssueTokenPairAsync(user, ct);
|
|
||||||
await transaction.CommitAsync(ct);
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await revocation.RevokeAllAsync(token.UserId, RevokeReason.ReuseDetected, ct);
|
var user = await db.Users.SingleOrDefaultAsync(u => u.Id == token.UserId, ct);
|
||||||
throw new UnauthorizedException("Refresh token už byl použit. Přihlaste se znovu.");
|
if (user is null || !user.IsActive)
|
||||||
|
throw new UnauthorizedException("Účet neexistuje nebo je deaktivován.");
|
||||||
|
|
||||||
|
return await IssueTokenPairAsync(user, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>Odhlášení jednoho zařízení – zneplatní aktuální access token a k němu předaný refresh token.</summary>
|
/// <summary>Odhlášení jednoho zařízení – zneplatní aktuální access token a k němu předaný refresh token.</summary>
|
||||||
|
|||||||
@@ -80,11 +80,10 @@ public sealed partial class IssueService
|
|||||||
public async Task<IReadOnlyList<AssignableUserDto>> GetAssignableAsync(CancellationToken ct)
|
public async Task<IReadOnlyList<AssignableUserDto>> GetAssignableAsync(CancellationToken ct)
|
||||||
{
|
{
|
||||||
var actor = await GetActorAsync(ct);
|
var actor = await GetActorAsync(ct);
|
||||||
if (!Issue.CanAssign(actor.Role))
|
if (actor.Role != UserRole.Management)
|
||||||
throw new ForbiddenException("Přehled řešitelů je určen vedení a administrátorům.");
|
throw new ForbiddenException("Přehled řešitelů je určen vedení.");
|
||||||
|
|
||||||
var users = await db.Users.Where(u => u.IsActive &&
|
var users = await db.Users.Where(u => u.IsActive && (u.Role == UserRole.Management || u.Role == UserRole.FacilityManager))
|
||||||
(u.Role == UserRole.Management || u.Role == UserRole.FacilityManager || u.Role == UserRole.Admin))
|
|
||||||
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
|
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
|
||||||
.Select(u => new
|
.Select(u => new
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ public sealed partial class IssueService(
|
|||||||
CheckVersion(issue, request.RowVersion);
|
CheckVersion(issue, request.RowVersion);
|
||||||
var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct);
|
var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct);
|
||||||
if (assignee is null || !Issue.CanBeAssigned(assignee.Role))
|
if (assignee is null || !Issue.CanBeAssigned(assignee.Role))
|
||||||
throw new BadRequestException("Vyberte aktivního správce budov, člena vedení nebo administrátora.");
|
throw new BadRequestException("Vyberte aktivního správce budov nebo člena vedení.");
|
||||||
if (issue.AssigneeId == assignee.Id)
|
if (issue.AssigneeId == assignee.Id)
|
||||||
throw new ConflictException("Závada je již přiřazena tomuto řešiteli.");
|
throw new ConflictException("Závada je již přiřazena tomuto řešiteli.");
|
||||||
|
|
||||||
@@ -53,7 +53,7 @@ public sealed partial class IssueService(
|
|||||||
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
|
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
|
||||||
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName);
|
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);
|
await notificationWriter.ForIssueAsync(issue, actor.Id, [assignee.Id], NotificationType.IssueAssigned, "Závada byla přiřazena", ct);
|
||||||
if (from != issue.Status && issue.ReporterId != assignee.Id)
|
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 notificationWriter.ForIssueAsync(issue, actor.Id, [issue.ReporterId], NotificationType.IssueStatusChanged, "Závada byla přiřazena", ct);
|
||||||
|
|
||||||
await SaveAsync(ct);
|
await SaveAsync(ct);
|
||||||
|
|||||||
@@ -15,8 +15,7 @@ public sealed class NotificationWriter(IAppDbContext db, TimeProvider clock)
|
|||||||
{
|
{
|
||||||
var reporterId = issue.ReporterId;
|
var reporterId = issue.ReporterId;
|
||||||
var eligibleUsers = db.Users.Where(u =>
|
var eligibleUsers = db.Users.Where(u =>
|
||||||
u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management ||
|
u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management);
|
||||||
u.Role == UserRole.Admin);
|
|
||||||
return QueueAsync(eligibleUsers, actorId, recipientIds,
|
return QueueAsync(eligibleUsers, actorId, recipientIds,
|
||||||
id => new Notification(issue, id, type, title, issue.Title), ct);
|
id => new Notification(issue, id, type, title, issue.Title), ct);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,20 +28,20 @@ public sealed partial class ProposalService(
|
|||||||
|
|
||||||
public async Task<ProposalDetail> EditAsync(int id, SaveProposalRequest request, CancellationToken ct)
|
public async Task<ProposalDetail> EditAsync(int id, SaveProposalRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var role = await GetActorRoleAsync(ct);
|
await GetActorRoleAsync(ct);
|
||||||
var (title, description) = ValidateDetails(request);
|
var (title, description) = ValidateDetails(request);
|
||||||
await using (var transaction = await db.BeginWriteAsync(ct))
|
await using (var transaction = await db.BeginProposalWriteAsync(ct))
|
||||||
{
|
{
|
||||||
var proposal = await LockProposalAsync(id, ct);
|
var proposal = await LockProposalAsync(id, ct);
|
||||||
if (!proposal.CanEditAs(currentUser.Id, role))
|
if (!proposal.IsAuthor(currentUser.Id))
|
||||||
throw new ForbiddenException("Návrh může upravit jeho autor nebo administrátor.");
|
throw new ForbiddenException("Návrh může upravit jen jeho autor.");
|
||||||
if (!proposal.IsEditable)
|
if (!proposal.IsEditable)
|
||||||
throw new ConflictException("Návrh lze upravit jen ve stavu Podán.");
|
throw new ConflictException("Návrh lze upravit jen ve stavu Podán.");
|
||||||
|
|
||||||
if (proposal.CategoryId != request.CategoryId)
|
if (proposal.CategoryId != request.CategoryId)
|
||||||
await RequireActiveCategoryAsync(request.CategoryId, ct);
|
await RequireActiveCategoryAsync(request.CategoryId, ct);
|
||||||
|
|
||||||
proposal.Edit(currentUser.Id, role, title, description, request.CategoryId);
|
proposal.Edit(currentUser.Id, title, description, request.CategoryId);
|
||||||
AddEvent(proposal, ProposalEventType.Updated);
|
AddEvent(proposal, ProposalEventType.Updated);
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
await transaction.CommitAsync(ct);
|
await transaction.CommitAsync(ct);
|
||||||
@@ -53,8 +53,8 @@ public sealed partial class ProposalService(
|
|||||||
public async Task<ProposalDetail> ChangeStatusAsync(int id, ChangeProposalStatusRequest request, CancellationToken ct)
|
public async Task<ProposalDetail> ChangeStatusAsync(int id, ChangeProposalStatusRequest request, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var role = await GetActorRoleAsync(ct);
|
var role = await GetActorRoleAsync(ct);
|
||||||
if (!Proposal.CanReview(role))
|
if (role != UserRole.Management)
|
||||||
throw new ForbiddenException("Stav návrhu může změnit vedení školy nebo administrátor.");
|
throw new ForbiddenException("Stav návrhu může změnit jen vedení školy.");
|
||||||
|
|
||||||
var target = ParseStatus(request.Status);
|
var target = ParseStatus(request.Status);
|
||||||
var note = string.IsNullOrWhiteSpace(request.Note) ? null : request.Note.Trim();
|
var note = string.IsNullOrWhiteSpace(request.Note) ? null : request.Note.Trim();
|
||||||
@@ -63,7 +63,7 @@ public sealed partial class ProposalService(
|
|||||||
if (note is not null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes)
|
if (note is not null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes)
|
||||||
throw new BadRequestException("Vyjádření je příliš dlouhé.");
|
throw new BadRequestException("Vyjádření je příliš dlouhé.");
|
||||||
|
|
||||||
await using (var transaction = await db.BeginWriteAsync(ct))
|
await using (var transaction = await db.BeginProposalWriteAsync(ct))
|
||||||
{
|
{
|
||||||
var proposal = await LockProposalAsync(id, ct);
|
var proposal = await LockProposalAsync(id, ct);
|
||||||
var previous = proposal.Status;
|
var previous = proposal.Status;
|
||||||
@@ -94,7 +94,7 @@ public sealed partial class ProposalService(
|
|||||||
{
|
{
|
||||||
await GetActorRoleAsync(ct);
|
await GetActorRoleAsync(ct);
|
||||||
var actorId = currentUser.Id;
|
var actorId = currentUser.Id;
|
||||||
await using var transaction = await db.BeginWriteAsync(ct);
|
await using var transaction = await db.BeginProposalWriteAsync(ct);
|
||||||
var proposal = await LockProposalAsync(id, ct);
|
var proposal = await LockProposalAsync(id, ct);
|
||||||
if (proposal.IsAuthor(actorId))
|
if (proposal.IsAuthor(actorId))
|
||||||
throw new ForbiddenException("Autor nemůže hlasovat o vlastním návrhu.");
|
throw new ForbiddenException("Autor nemůže hlasovat o vlastním návrhu.");
|
||||||
|
|||||||
@@ -31,11 +31,9 @@ public sealed class Issue : IHasCreatedAt
|
|||||||
public int RowVersion { get; private set; }
|
public int RowVersion { get; private set; }
|
||||||
public DateTime CreatedAt { get; set; }
|
public DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
public static bool CanReadAll(UserRole role) => role == UserRole.FacilityManager || CanAssign(role);
|
public static bool CanReadAll(UserRole role) => role is UserRole.FacilityManager or UserRole.Management;
|
||||||
|
|
||||||
public static bool CanAssign(UserRole role) => role is UserRole.Management or UserRole.Admin;
|
public static bool CanBeAssigned(UserRole role) => role is UserRole.FacilityManager or UserRole.Management;
|
||||||
|
|
||||||
public static bool CanBeAssigned(UserRole role) => role is UserRole.FacilityManager or UserRole.Management or UserRole.Admin;
|
|
||||||
|
|
||||||
public bool CanRead(int userId, UserRole role) => CanReadAll(role) || ReporterId == userId;
|
public bool CanRead(int userId, UserRole role) => CanReadAll(role) || ReporterId == userId;
|
||||||
|
|
||||||
@@ -44,15 +42,14 @@ public sealed class Issue : IHasCreatedAt
|
|||||||
var reporter = ReporterId == actorId;
|
var reporter = ReporterId == actorId;
|
||||||
var assignee = AssigneeId == actorId && CanBeAssigned(role);
|
var assignee = AssigneeId == actorId && CanBeAssigned(role);
|
||||||
var management = role == UserRole.Management;
|
var management = role == UserRole.Management;
|
||||||
var admin = role == UserRole.Admin;
|
|
||||||
|
|
||||||
var authorized = action switch
|
var authorized = action switch
|
||||||
{
|
{
|
||||||
IssueAction.Edit or IssueAction.Confirm or IssueAction.Reopen => admin || reporter,
|
IssueAction.Edit or IssueAction.Confirm or IssueAction.Reopen => reporter,
|
||||||
IssueAction.Assign => CanAssign(role),
|
IssueAction.Assign => management,
|
||||||
IssueAction.StartWork or IssueAction.SubmitForVerification => admin || assignee,
|
IssueAction.StartWork or IssueAction.SubmitForVerification => assignee,
|
||||||
IssueAction.Reject => admin || assignee || (management && AssigneeId is null),
|
IssueAction.Reject => assignee || (management && AssigneeId is null),
|
||||||
IssueAction.Comment or IssueAction.AddAttachments => admin || reporter || assignee,
|
IssueAction.Comment or IssueAction.AddAttachments => reporter || assignee,
|
||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -67,8 +64,8 @@ public sealed class Issue : IHasCreatedAt
|
|||||||
IssueAction.SubmitForVerification => Status == IssueStatus.InProgress,
|
IssueAction.SubmitForVerification => Status == IssueStatus.InProgress,
|
||||||
IssueAction.Confirm or IssueAction.Reopen => Status == IssueStatus.PendingVerification,
|
IssueAction.Confirm or IssueAction.Reopen => Status == IssueStatus.PendingVerification,
|
||||||
IssueAction.Reject => Status == IssueStatus.Received
|
IssueAction.Reject => Status == IssueStatus.Received
|
||||||
? admin || management
|
? management
|
||||||
: (admin || assignee) && Status is (IssueStatus.Assigned or IssueStatus.InProgress),
|
: assignee && Status is (IssueStatus.Assigned or IssueStatus.InProgress),
|
||||||
IssueAction.Comment or IssueAction.AddAttachments => Status is not (IssueStatus.Resolved or IssueStatus.Rejected),
|
IssueAction.Comment or IssueAction.AddAttachments => Status is not (IssueStatus.Resolved or IssueStatus.Rejected),
|
||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -26,11 +26,9 @@ public sealed class Proposal : IHasCreatedAt
|
|||||||
public bool IsAuthor(int userId) => AuthorId == userId;
|
public bool IsAuthor(int userId) => AuthorId == userId;
|
||||||
public bool IsEditable => Status == ProposalStatus.Submitted;
|
public bool IsEditable => Status == ProposalStatus.Submitted;
|
||||||
public bool IsVotingOpen => Status is ProposalStatus.Submitted or ProposalStatus.UnderReview;
|
public bool IsVotingOpen => Status is ProposalStatus.Submitted or ProposalStatus.UnderReview;
|
||||||
public bool CanEditAs(int userId, UserRole role) => role == UserRole.Admin || IsAuthor(userId);
|
public bool CanEdit(int userId) => IsAuthor(userId) && IsEditable;
|
||||||
public bool CanVote(int userId) => !IsAuthor(userId) && IsVotingOpen;
|
public bool CanVote(int userId) => !IsAuthor(userId) && IsVotingOpen;
|
||||||
|
|
||||||
public static bool CanReview(UserRole role) => role is UserRole.Management or UserRole.Admin;
|
|
||||||
|
|
||||||
public bool CanTransitionTo(ProposalStatus target) => Status switch
|
public bool CanTransitionTo(ProposalStatus target) => Status switch
|
||||||
{
|
{
|
||||||
ProposalStatus.Submitted => target is ProposalStatus.UnderReview or ProposalStatus.Accepted or ProposalStatus.Rejected,
|
ProposalStatus.Submitted => target is ProposalStatus.UnderReview or ProposalStatus.Accepted or ProposalStatus.Rejected,
|
||||||
@@ -39,9 +37,9 @@ public sealed class Proposal : IHasCreatedAt
|
|||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
|
|
||||||
public void Edit(int actorId, UserRole role, string title, string description, int categoryId)
|
public void Edit(int actorId, string title, string description, int categoryId)
|
||||||
{
|
{
|
||||||
if (!CanEditAs(actorId, role) || !IsEditable)
|
if (!CanEdit(actorId))
|
||||||
throw new InvalidOperationException("Návrh nelze upravit.");
|
throw new InvalidOperationException("Návrh nelze upravit.");
|
||||||
|
|
||||||
SetDetails(title, description, categoryId);
|
SetDetails(title, description, categoryId);
|
||||||
@@ -49,7 +47,7 @@ public sealed class Proposal : IHasCreatedAt
|
|||||||
|
|
||||||
public void ChangeStatus(ProposalStatus target, UserRole role, string? note)
|
public void ChangeStatus(ProposalStatus target, UserRole role, string? note)
|
||||||
{
|
{
|
||||||
if (!CanReview(role) || !CanTransitionTo(target))
|
if (role != UserRole.Management || !CanTransitionTo(target))
|
||||||
throw new InvalidOperationException("Stav návrhu nelze změnit.");
|
throw new InvalidOperationException("Stav návrhu nelze změnit.");
|
||||||
if (target == ProposalStatus.Rejected && string.IsNullOrWhiteSpace(note))
|
if (target == ProposalStatus.Rejected && string.IsNullOrWhiteSpace(note))
|
||||||
throw new ArgumentException("Zamítnutí vyžaduje vyjádření.", nameof(note));
|
throw new ArgumentException("Zamítnutí vyžaduje vyjádření.", nameof(note));
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct) =>
|
public Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct) =>
|
||||||
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
||||||
|
|
||||||
public async Task<Proposal?> LockProposalAsync(int id, CancellationToken ct)
|
public async Task<Proposal?> LockProposalAsync(int id, CancellationToken ct)
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Net.Http.Json;
|
|
||||||
using System.Text;
|
|
||||||
using Helpdesk.Application.Auth;
|
|
||||||
using Helpdesk.Application.Catalogs;
|
|
||||||
using Helpdesk.Application.Common;
|
|
||||||
using Helpdesk.Application.Users;
|
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
|
||||||
|
|
||||||
namespace Helpdesk.IntegrationTests;
|
|
||||||
|
|
||||||
public sealed class AdministrationTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
|
||||||
{
|
|
||||||
[Theory]
|
|
||||||
[InlineData("/api/v1/issue-categories")]
|
|
||||||
[InlineData("/api/v1/proposal-categories")]
|
|
||||||
public async Task AdministratorsCanManageCategories(string route)
|
|
||||||
{
|
|
||||||
using var anonymous = fixture.CreateClient();
|
|
||||||
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
|
||||||
var user = await fixture.RegisterAsync(anonymous);
|
|
||||||
using var member = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
|
||||||
var request = new SaveCategoryRequest("Testovací kategorie", "Popis");
|
|
||||||
await ExpectAsync(member.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Forbidden);
|
|
||||||
var category = await ReadAsync<CategoryDto>(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Created);
|
|
||||||
await ExpectAsync(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Conflict);
|
|
||||||
var path = $"{route}/{category.Id}";
|
|
||||||
var edited = await ReadAsync<CategoryDto>(admin.PutAsJsonAsync(path, request with { Name = "Upravená kategorie" }, Cancellation));
|
|
||||||
Assert.Equal("Upravená kategorie", edited.Name);
|
|
||||||
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
|
|
||||||
|
|
||||||
var active = await ReadAsync<CategoryDto[]>(member.GetAsync(route + "?includeInactive=true", Cancellation));
|
|
||||||
var all = await ReadAsync<CategoryDto[]>(admin.GetAsync(route + "?includeInactive=true", Cancellation));
|
|
||||||
Assert.DoesNotContain(active, item => item.Id == category.Id);
|
|
||||||
Assert.False(Assert.Single(all, item => item.Id == category.Id).IsActive);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task BuildingCodesAreUniqueAndInactiveBuildingsStayAvailableToTheAdministrator()
|
|
||||||
{
|
|
||||||
using var anonymous = fixture.CreateClient();
|
|
||||||
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
|
||||||
const string route = "/api/v1/buildings";
|
|
||||||
var request = new SaveBuildingRequest("TEST", "Testovací budova", null);
|
|
||||||
var building = await ReadAsync<BuildingDto>(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Created);
|
|
||||||
await ExpectAsync(admin.PostAsJsonAsync(route, request with { Code = " TEST " }, Cancellation), HttpStatusCode.Conflict);
|
|
||||||
var path = $"{route}/{building.Id}";
|
|
||||||
var edited = await ReadAsync<BuildingDto>(admin.PutAsJsonAsync(path, request with { Address = "Náměstí 1" }, Cancellation));
|
|
||||||
Assert.Equal("Náměstí 1", edited.Address);
|
|
||||||
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
|
|
||||||
var active = await ReadAsync<BuildingDto[]>(admin.GetAsync(route, Cancellation));
|
|
||||||
var all = await ReadAsync<BuildingDto[]>(admin.GetAsync(route + "?includeInactive=true", Cancellation));
|
|
||||||
Assert.DoesNotContain(active, item => item.Id == building.Id);
|
|
||||||
Assert.False(Assert.Single(all, item => item.Id == building.Id).IsActive);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task ProfileDataRoundTripsAndDeactivationRevokesTheSession()
|
|
||||||
{
|
|
||||||
using var anonymous = fixture.CreateClient();
|
|
||||||
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
|
||||||
var user = await fixture.RegisterAsync(anonymous);
|
|
||||||
using var member = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
|
||||||
const string profile = "/api/v1/users/me";
|
|
||||||
const string phone = "+420 123 456 789";
|
|
||||||
var request = new UpdateProfileRequest("Jana", "Nováková", phone, false);
|
|
||||||
var validation = await ReadAsync<ValidationProblemDetails>(member.PutAsJsonAsync(profile,
|
|
||||||
request with { Phone = "invalid" }, Cancellation), HttpStatusCode.BadRequest);
|
|
||||||
Assert.Contains("phone", validation.Errors.Keys);
|
|
||||||
var updated = await ReadAsync<UserDto>(member.PutAsJsonAsync(profile, request, Cancellation));
|
|
||||||
Assert.Equal(updated, await ReadAsync<UserDto>(member.GetAsync(profile, Cancellation)));
|
|
||||||
Assert.Equal((request.FirstName, request.LastName, phone, false),
|
|
||||||
(updated.FirstName, updated.LastName, updated.Phone, updated.EmailNotificationsEnabled));
|
|
||||||
|
|
||||||
await using var scope = fixture.Services.CreateAsyncScope();
|
|
||||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
|
||||||
var encrypted = await db.Database.SqlQuery<byte[]>($"SELECT phone_encrypted AS Value FROM app_user WHERE id = {user.Id}")
|
|
||||||
.SingleAsync(Cancellation);
|
|
||||||
Assert.NotEmpty(encrypted);
|
|
||||||
Assert.False(Encoding.UTF8.GetBytes(phone).SequenceEqual(encrypted));
|
|
||||||
|
|
||||||
var search = $"/api/v1/admin/users?q={Uri.EscapeDataString(user.Email)}&role=STUDENT&pageSize=1";
|
|
||||||
await ExpectAsync(member.GetAsync(search, Cancellation), HttpStatusCode.Forbidden);
|
|
||||||
var page = await ReadAsync<PagedResult<AdminUserDto>>(admin.GetAsync(search, Cancellation));
|
|
||||||
Assert.Equal(user.Id, Assert.Single(page.Items).Id);
|
|
||||||
var activation = $"/api/v1/admin/users/{user.Id}/active";
|
|
||||||
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(false), Cancellation), HttpStatusCode.NoContent);
|
|
||||||
await ExpectAsync(member.GetAsync(profile, Cancellation), HttpStatusCode.Unauthorized);
|
|
||||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, Password), Cancellation),
|
|
||||||
HttpStatusCode.Forbidden);
|
|
||||||
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(true), Cancellation), HttpStatusCode.NoContent);
|
|
||||||
Assert.Equal(user.Id, (await LoginAsync(anonymous, user.Email)).User.Id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
using System.Globalization;
|
|
||||||
using System.IO.Compression;
|
|
||||||
using System.Net;
|
|
||||||
using System.Net.Http.Json;
|
|
||||||
using Helpdesk.Application.Catalogs;
|
|
||||||
using Helpdesk.Application.Issues;
|
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
|
||||||
|
|
||||||
namespace Helpdesk.IntegrationTests;
|
|
||||||
|
|
||||||
public sealed class AttachmentTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public async Task AttachmentsRespectFormatAndAccessAndFailedBatchesAreNotSaved()
|
|
||||||
{
|
|
||||||
using var anonymous = fixture.CreateClient();
|
|
||||||
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
|
||||||
var authorUser = await fixture.RegisterAsync(anonymous);
|
|
||||||
var otherUser = await fixture.RegisterAsync(anonymous);
|
|
||||||
using var author = fixture.CreateClient((await LoginAsync(anonymous, authorUser.Email)).AccessToken);
|
|
||||||
using var other = fixture.CreateClient((await LoginAsync(anonymous, otherUser.Email)).AccessToken);
|
|
||||||
var categories = await ReadAsync<CategoryDto[]>(author.GetAsync("/api/v1/issue-categories", Cancellation));
|
|
||||||
var png = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6t1sAAAAASUVORK5CYII=");
|
|
||||||
using var createForm = new MultipartFormDataContent();
|
|
||||||
createForm.Add(new StringContent("Rozbitý zámek"), "title");
|
|
||||||
createForm.Add(new StringContent("Dveře nelze odemknout."), "description");
|
|
||||||
createForm.Add(new StringContent(categories[0].Id.ToString(CultureInfo.InvariantCulture)), "categoryId");
|
|
||||||
AddFile(createForm, "zamek.png", png);
|
|
||||||
|
|
||||||
await using var scope = fixture.Services.CreateAsyncScope();
|
|
||||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
|
||||||
var store = scope.ServiceProvider.GetRequiredService<IAttachmentStore>();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var issue = await ReadAsync<IssueDetail>(author.PostAsync("/api/v1/issues", createForm, Cancellation), HttpStatusCode.Created);
|
|
||||||
var pngAttachment = Assert.Single(issue.Attachments);
|
|
||||||
var download = $"/api/v1/attachments/{pngAttachment.Id}";
|
|
||||||
using var fetched = await author.GetAsync(download, Cancellation);
|
|
||||||
Assert.Equal(HttpStatusCode.OK, fetched.StatusCode);
|
|
||||||
Assert.Equal("image/png", fetched.Content.Headers.ContentType?.MediaType);
|
|
||||||
Assert.Equal("nosniff", Assert.Single(fetched.Headers.GetValues("X-Content-Type-Options")));
|
|
||||||
Assert.Equal(png, await fetched.Content.ReadAsByteArrayAsync(Cancellation));
|
|
||||||
await ExpectAsync(other.GetAsync(download, Cancellation), HttpStatusCode.Forbidden);
|
|
||||||
|
|
||||||
var path = $"/api/v1/issues/{issue.Id}/attachments";
|
|
||||||
using var mixed = new MultipartFormDataContent();
|
|
||||||
AddFile(mixed, "spravny.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
|
|
||||||
AddFile(mixed, "podvrzeny.png", "obsah nemá formát PNG"u8.ToArray());
|
|
||||||
await ExpectAsync(author.PostAsync(path, mixed, Cancellation), HttpStatusCode.BadRequest);
|
|
||||||
|
|
||||||
using var wrongField = new MultipartFormDataContent();
|
|
||||||
wrongField.Add(new ByteArrayContent(png), "image", "zamek.png");
|
|
||||||
await ExpectAsync(author.PostAsync(path, wrongField, Cancellation), HttpStatusCode.BadRequest);
|
|
||||||
var afterFailure = await ReadAsync<IssueDetail>(author.GetAsync($"/api/v1/issues/{issue.Id}", Cancellation));
|
|
||||||
Assert.Equal(issue.RowVersion, afterFailure.RowVersion);
|
|
||||||
Assert.Equal(pngAttachment.Id, Assert.Single(afterFailure.Attachments).Id);
|
|
||||||
|
|
||||||
using var files = new MultipartFormDataContent();
|
|
||||||
AddFile(files, "protokol.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
|
|
||||||
AddFile(files, "fotka.jpg", [0xff, 0xd8, 0xff, 0xd9]);
|
|
||||||
AddFile(files, "fotka.heic", [0, 0, 0, 20, .. "ftypmif1"u8, 0, 0, 0, 0, .. "heic"u8]);
|
|
||||||
AddFile(files, "protokol.docx", Docx());
|
|
||||||
var added = await ReadAsync<AttachmentDto[]>(admin.PostAsync(path, files, Cancellation));
|
|
||||||
Assert.Equal(["application/pdf", "image/jpeg", "image/heic",
|
|
||||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"], added.Select(item => item.ContentType));
|
|
||||||
|
|
||||||
var key = await db.Attachments.Where(item => item.Id == pngAttachment.Id).Select(item => item.StoredFileName).SingleAsync(Cancellation);
|
|
||||||
store.Delete(key);
|
|
||||||
await ExpectAsync(author.GetAsync(download, Cancellation), HttpStatusCode.NotFound);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
foreach (var key in await db.Attachments.Select(item => item.StoredFileName).ToListAsync(CancellationToken.None))
|
|
||||||
store.Delete(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void AddFile(MultipartFormDataContent form, string name, byte[] bytes) =>
|
|
||||||
form.Add(new ByteArrayContent(bytes), "files", name);
|
|
||||||
|
|
||||||
private static byte[] Docx()
|
|
||||||
{
|
|
||||||
using var stream = new MemoryStream();
|
|
||||||
using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
|
|
||||||
{
|
|
||||||
using (var contentTypes = zip.CreateEntry("[Content_Types].xml").Open())
|
|
||||||
contentTypes.Write("<Types/>"u8);
|
|
||||||
using (var document = zip.CreateEntry("word/document.xml").Open())
|
|
||||||
document.Write("<document/>"u8);
|
|
||||||
}
|
|
||||||
return stream.ToArray();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Net.Http.Json;
|
|
||||||
using Helpdesk.Application.Auth;
|
|
||||||
using Helpdesk.Domain.Auth;
|
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.IdentityModel.JsonWebTokens;
|
|
||||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
|
||||||
|
|
||||||
namespace Helpdesk.IntegrationTests;
|
|
||||||
|
|
||||||
public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSession()
|
|
||||||
{
|
|
||||||
using var anonymous = fixture.CreateClient();
|
|
||||||
var user = await fixture.RegisterAsync(anonymous);
|
|
||||||
using var oldSession = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
|
||||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password",
|
|
||||||
new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent);
|
|
||||||
|
|
||||||
const string newPassword = "New-integration-password";
|
|
||||||
var reset = new ResetPasswordRequest(await fixture.TakeResetTokenAsync(user.Email), newPassword);
|
|
||||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.NoContent);
|
|
||||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.BadRequest);
|
|
||||||
await ExpectAsync(oldSession.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
|
||||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
|
||||||
new LoginRequest(user.Email, Password), Cancellation), HttpStatusCode.Unauthorized);
|
|
||||||
var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
|
|
||||||
new LoginRequest(user.Email, newPassword), Cancellation));
|
|
||||||
Assert.Equal(user.Id, session.User.Id);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task LogoutRevokesOnlyTheCurrentSession()
|
|
||||||
{
|
|
||||||
using var anonymous = fixture.CreateClient();
|
|
||||||
var user = await fixture.RegisterAsync(anonymous);
|
|
||||||
var session = await LoginAsync(anonymous, user.Email);
|
|
||||||
var otherSession = await LoginAsync(anonymous, user.Email);
|
|
||||||
using var client = fixture.CreateClient(session.AccessToken);
|
|
||||||
using var otherClient = fixture.CreateClient(otherSession.AccessToken);
|
|
||||||
var refresh = new RefreshTokenRequest(session.RefreshToken);
|
|
||||||
|
|
||||||
await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/logout", refresh, Cancellation), HttpStatusCode.NoContent);
|
|
||||||
|
|
||||||
await ExpectAsync(client.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
|
||||||
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.OK);
|
|
||||||
var accessId = new JsonWebToken(session.AccessToken).Id;
|
|
||||||
var refreshId = new JsonWebToken(session.RefreshToken).Id;
|
|
||||||
await using var scope = fixture.Services.CreateAsyncScope();
|
|
||||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
|
||||||
Assert.Equal(2, await db.AuthTokens.CountAsync(token =>
|
|
||||||
token.UserId == user.Id && (token.Jti == accessId || token.Jti == refreshId) &&
|
|
||||||
token.RevokeReason == RevokeReason.Logout, Cancellation));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task ConcurrentRefreshRevokesTheNewPairAndOtherSessions()
|
|
||||||
{
|
|
||||||
using var anonymous = fixture.CreateClient();
|
|
||||||
var user = await fixture.RegisterAsync(anonymous);
|
|
||||||
var session = await LoginAsync(anonymous, user.Email);
|
|
||||||
var otherSession = await LoginAsync(anonymous, user.Email);
|
|
||||||
var refresh = new RefreshTokenRequest(session.RefreshToken);
|
|
||||||
|
|
||||||
var pause = fixture.TokenSaves.PauseNextSave();
|
|
||||||
Task<HttpResponseMessage> first;
|
|
||||||
Task<HttpResponseMessage> duplicate;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
first = anonymous.PostAsJsonAsync("/api/v1/auth/refresh", refresh, Cancellation);
|
|
||||||
await pause.Entered.Task.WaitAsync(TimeSpan.FromSeconds(15), Cancellation);
|
|
||||||
await using var scope = fixture.Services.CreateAsyncScope();
|
|
||||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
|
||||||
Assert.Equal(2, await db.AuthTokens.CountAsync(token =>
|
|
||||||
token.UserId == user.Id && token.TokenType == TokenType.Refresh && token.RevokedAt == null, Cancellation));
|
|
||||||
duplicate = anonymous.PostAsJsonAsync("/api/v1/auth/refresh", refresh, Cancellation);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
pause.Release();
|
|
||||||
}
|
|
||||||
|
|
||||||
var renewed = await ReadAsync<AuthResponse>(first);
|
|
||||||
await ExpectAsync(duplicate, HttpStatusCode.Unauthorized);
|
|
||||||
await using var after = fixture.Services.CreateAsyncScope();
|
|
||||||
var tokens = after.ServiceProvider.GetRequiredService<HelpdeskDbContext>().AuthTokens;
|
|
||||||
Assert.False(await tokens.AnyAsync(token => token.UserId == user.Id && token.RevokedAt == null, Cancellation));
|
|
||||||
|
|
||||||
using var renewedClient = fixture.CreateClient(renewed.AccessToken);
|
|
||||||
using var otherClient = fixture.CreateClient(otherSession.AccessToken);
|
|
||||||
await ExpectAsync(renewedClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
|
||||||
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
using System.Collections.Concurrent;
|
|
||||||
using System.Diagnostics;
|
|
||||||
using System.Net;
|
|
||||||
using System.Net.Http.Headers;
|
|
||||||
using System.Net.Http.Json;
|
|
||||||
using System.Security.Cryptography;
|
|
||||||
using Helpdesk.Application.Abstractions;
|
|
||||||
using Helpdesk.Application.Auth;
|
|
||||||
using Helpdesk.Application.Common;
|
|
||||||
using Helpdesk.Application.Users;
|
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
|
||||||
using Microsoft.AspNetCore.Hosting;
|
|
||||||
using Microsoft.AspNetCore.Mvc.Testing;
|
|
||||||
using Microsoft.AspNetCore.TestHost;
|
|
||||||
using Microsoft.AspNetCore.WebUtilities;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.Extensions.Configuration;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
using Testcontainers.MariaDb;
|
|
||||||
|
|
||||||
namespace Helpdesk.IntegrationTests;
|
|
||||||
|
|
||||||
public sealed class BackendFixture : IAsyncLifetime
|
|
||||||
{
|
|
||||||
internal const string AdminEmail = "[email protected]";
|
|
||||||
internal const string Password = "Integration-test-password";
|
|
||||||
internal static string MigrationsPath => Path.Combine(AppContext.BaseDirectory, "migrations");
|
|
||||||
internal static CancellationToken Cancellation => TestContext.Current.CancellationToken;
|
|
||||||
|
|
||||||
private readonly MariaDbContainer database = new MariaDbBuilder("mariadb:11.4")
|
|
||||||
.WithDatabase("helpdesk")
|
|
||||||
.WithPassword(Convert.ToHexString(RandomNumberGenerator.GetBytes(24)))
|
|
||||||
.WithCommand("--character-set-server=utf8mb4")
|
|
||||||
.Build();
|
|
||||||
private readonly TestEmailSender email = new();
|
|
||||||
private ApiFactory? factory;
|
|
||||||
|
|
||||||
internal TokenSaveGate TokenSaves { get; } = new();
|
|
||||||
internal IServiceProvider Services => factory!.Services;
|
|
||||||
|
|
||||||
public async ValueTask InitializeAsync()
|
|
||||||
{
|
|
||||||
await database.StartAsync(Cancellation);
|
|
||||||
await RunMigratorAsync(database.GetConnectionString());
|
|
||||||
factory = new ApiFactory(database.GetConnectionString(), email, TokenSaves);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async ValueTask DisposeAsync()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (factory is not null)
|
|
||||||
await factory.DisposeAsync();
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
await database.DisposeAsync();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal HttpClient CreateClient(string? accessToken = null)
|
|
||||||
{
|
|
||||||
var client = factory!.CreateClient();
|
|
||||||
if (accessToken is not null)
|
|
||||||
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
|
||||||
return client;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal WebApplicationFactory<Program> CreateApiBehindProxies(string proxyIp, string webIp) =>
|
|
||||||
new ApiFactory(database.GetConnectionString(), email, TokenSaves, proxyIp, webIp);
|
|
||||||
|
|
||||||
internal async Task<UserDto> RegisterAsync(HttpClient client)
|
|
||||||
{
|
|
||||||
var address = $"{Guid.NewGuid():N}@student.example.test";
|
|
||||||
var user = await ReadAsync<UserDto>(client.PostAsJsonAsync("/api/v1/auth/register",
|
|
||||||
new RegisterRequest(address, Password, "Test", "User"), Cancellation), HttpStatusCode.Created);
|
|
||||||
await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email",
|
|
||||||
new EmailTokenRequest(await email.TakeTokenAsync(address, "/confirm-email")), Cancellation), HttpStatusCode.NoContent);
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal async Task<AuthResponse> RegisterStaffAsync(HttpClient anonymous, HttpClient admin, string role)
|
|
||||||
{
|
|
||||||
var user = await RegisterAsync(anonymous);
|
|
||||||
await ExpectAsync(admin.PutAsJsonAsync($"/api/v1/admin/users/{user.Id}/role",
|
|
||||||
new ChangeRoleRequest(role), Cancellation), HttpStatusCode.NoContent);
|
|
||||||
return await LoginAsync(anonymous, user.Email);
|
|
||||||
}
|
|
||||||
|
|
||||||
internal Task<string> TakeResetTokenAsync(string address) => email.TakeTokenAsync(address, "/reset-password");
|
|
||||||
|
|
||||||
internal void FailNextEmail(string address, string reason, bool retryable) =>
|
|
||||||
email.Failures[address] = new EmailDeliveryException(reason, retryable);
|
|
||||||
|
|
||||||
internal static Task<AuthResponse> LoginAsync(HttpClient client, string address) =>
|
|
||||||
ReadAsync<AuthResponse>(client.PostAsJsonAsync("/api/v1/auth/login",
|
|
||||||
new LoginRequest(address, Password), Cancellation));
|
|
||||||
|
|
||||||
internal static async Task<T> ReadAsync<T>(Task<HttpResponseMessage> request, HttpStatusCode expected = HttpStatusCode.OK)
|
|
||||||
where T : class
|
|
||||||
{
|
|
||||||
using var response = await request;
|
|
||||||
Assert.Equal(expected, response.StatusCode);
|
|
||||||
return Assert.IsType<T>(await response.Content.ReadFromJsonAsync<T>(Cancellation));
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static async Task ExpectAsync(Task<HttpResponseMessage> request, HttpStatusCode expected)
|
|
||||||
{
|
|
||||||
using var response = await request;
|
|
||||||
Assert.Equal(expected, response.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task RunMigratorAsync(string connectionString)
|
|
||||||
{
|
|
||||||
var startInfo = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet")
|
|
||||||
{
|
|
||||||
RedirectStandardOutput = true,
|
|
||||||
RedirectStandardError = true,
|
|
||||||
};
|
|
||||||
startInfo.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "Helpdesk.Migrator.dll"));
|
|
||||||
startInfo.Environment["ConnectionStrings__Migrator"] = connectionString;
|
|
||||||
startInfo.Environment["MIGRATIONS_PATH"] = MigrationsPath;
|
|
||||||
using var process = Process.Start(startInfo) ?? throw new InvalidOperationException("Could not start the migrator.");
|
|
||||||
var output = process.StandardOutput.ReadToEndAsync(Cancellation);
|
|
||||||
var errors = process.StandardError.ReadToEndAsync(Cancellation);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await process.WaitForExitAsync(Cancellation);
|
|
||||||
Assert.True(process.ExitCode == 0, $"Migrator failed with exit code {process.ExitCode}.\n{await output}\n{await errors}");
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
if (!process.HasExited)
|
|
||||||
{
|
|
||||||
process.Kill();
|
|
||||||
await process.WaitForExitAsync();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class ApiFactory(string connectionString, TestEmailSender email, TokenSaveGate tokenSaves,
|
|
||||||
string proxyIp = "", string webIp = "")
|
|
||||||
: WebApplicationFactory<Program>
|
|
||||||
{
|
|
||||||
private readonly Dictionary<string, string?> settings = new()
|
|
||||||
{
|
|
||||||
["ConnectionStrings:Helpdesk"] = connectionString,
|
|
||||||
["Jwt:SigningKey"] = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)),
|
|
||||||
["Encryption:Key"] = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)),
|
|
||||||
["Registration:StudentEmailDomains:0"] = "student.example.test",
|
|
||||||
["Registration:WebBaseUrl"] = "https://helpdesk.example.test",
|
|
||||||
["ADMIN_EMAIL"] = AdminEmail,
|
|
||||||
["ADMIN_PASSWORD"] = Password,
|
|
||||||
["Firebase:ServiceAccountJson"] = "",
|
|
||||||
["Smtp:Mailbox"] = "",
|
|
||||||
["Smtp:Password"] = "",
|
|
||||||
["ReverseProxy:TrustedIp"] = proxyIp,
|
|
||||||
["ReverseProxy:TrustedWebIp"] = webIp,
|
|
||||||
};
|
|
||||||
|
|
||||||
protected override IHost CreateHost(IHostBuilder builder)
|
|
||||||
{
|
|
||||||
// Program čte konfiguraci před Build(), proto musí hodnoty dostat už při startu.
|
|
||||||
builder.UseEnvironment(Environments.Development)
|
|
||||||
.ConfigureHostConfiguration(config => config.AddInMemoryCollection(settings));
|
|
||||||
return base.CreateHost(builder);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override void ConfigureWebHost(IWebHostBuilder builder) =>
|
|
||||||
builder.ConfigureTestServices(services =>
|
|
||||||
{
|
|
||||||
services.RemoveAll<IEmailSender>();
|
|
||||||
services.AddSingleton<IEmailSender>(email);
|
|
||||||
services.AddDbContext<HelpdeskDbContext>((_, options) => options.AddInterceptors(tokenSaves));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class TestEmailSender : IEmailSender
|
|
||||||
{
|
|
||||||
private readonly ConcurrentDictionary<(string Address, string Path), TaskCompletionSource<string>> tokens = new();
|
|
||||||
internal ConcurrentDictionary<string, EmailDeliveryException> Failures { get; } = new();
|
|
||||||
|
|
||||||
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
if (Failures.TryRemove(to, out var failure))
|
|
||||||
throw failure;
|
|
||||||
|
|
||||||
if (Uri.TryCreate(body[(body.LastIndexOf('\n') + 1)..], UriKind.Absolute, out var link) &&
|
|
||||||
link.AbsolutePath is "/confirm-email" or "/reset-password")
|
|
||||||
{
|
|
||||||
var token = QueryHelpers.ParseQuery(link.Query)["token"].ToString();
|
|
||||||
GetTokenSlot((to, link.AbsolutePath)).TrySetResult(token);
|
|
||||||
}
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal async Task<string> TakeTokenAsync(string address, string path)
|
|
||||||
{
|
|
||||||
var key = (address, path);
|
|
||||||
var token = await GetTokenSlot(key).Task.WaitAsync(TimeSpan.FromSeconds(10), Cancellation);
|
|
||||||
tokens.TryRemove(key, out _);
|
|
||||||
return token;
|
|
||||||
}
|
|
||||||
|
|
||||||
private TaskCompletionSource<string> GetTokenSlot((string Address, string Path) key) =>
|
|
||||||
tokens.GetOrAdd(key, _ => new(TaskCreationOptions.RunContinuationsAsynchronously));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Text.Json;
|
|
||||||
using Helpdesk.Api.Controllers;
|
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using MySqlConnector;
|
|
||||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
|
||||||
|
|
||||||
namespace Helpdesk.IntegrationTests;
|
|
||||||
|
|
||||||
public sealed class DatabaseTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public async Task MigratorAppliesEveryScriptAndEfCanReadTheSchema()
|
|
||||||
{
|
|
||||||
using var client = fixture.CreateClient();
|
|
||||||
await using var scope = fixture.Services.CreateAsyncScope();
|
|
||||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
|
||||||
var expected = Directory.EnumerateFiles(MigrationsPath, "V*__*.sql")
|
|
||||||
.Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray();
|
|
||||||
var applied = await db.Database
|
|
||||||
.SqlQueryRaw<string>("SELECT scriptname AS Value FROM schema_version ORDER BY schemaversionid")
|
|
||||||
.ToListAsync(Cancellation);
|
|
||||||
Assert.Equal(expected, applied);
|
|
||||||
var health = await ReadAsync<HealthResponse>(client.GetAsync("/health", Cancellation));
|
|
||||||
Assert.Equal(new HealthResponse("Healthy", expected[^1]), health);
|
|
||||||
|
|
||||||
await db.Users.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.AuthTokens.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.Buildings.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.IssueCategories.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.ProposalCategories.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.Issues.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.IssueEvents.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.IssueTimings.ToListAsync(Cancellation);
|
|
||||||
await db.Attachments.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.Proposals.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.ProposalEvents.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.ProposalVotes.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.ProposalScores.ToListAsync(Cancellation);
|
|
||||||
await db.Notifications.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.NotificationDeliveries.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
await db.PushDevices.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task OnlyAdministratorsCanReadTheOpenApiDocument()
|
|
||||||
{
|
|
||||||
using var client = fixture.CreateClient();
|
|
||||||
const string path = "/api/v1/admin/openapi/v1.json";
|
|
||||||
await ExpectAsync(client.GetAsync(path, Cancellation), HttpStatusCode.Unauthorized);
|
|
||||||
var student = await fixture.RegisterAsync(client);
|
|
||||||
using var studentClient = fixture.CreateClient((await LoginAsync(client, student.Email)).AccessToken);
|
|
||||||
await ExpectAsync(studentClient.GetAsync(path, Cancellation), HttpStatusCode.Forbidden);
|
|
||||||
using var admin = fixture.CreateClient((await LoginAsync(client, AdminEmail)).AccessToken);
|
|
||||||
await ExpectAsync(admin.GetAsync("/swagger/index.html", Cancellation), HttpStatusCode.NotFound);
|
|
||||||
await ExpectAsync(admin.GetAsync("/swagger/v1/swagger.json", Cancellation), HttpStatusCode.NotFound);
|
|
||||||
using var document = await ReadAsync<JsonDocument>(admin.GetAsync(path, Cancellation));
|
|
||||||
var paths = document.RootElement.GetProperty("paths");
|
|
||||||
var create = paths.GetProperty("/api/v1/issues").GetProperty("post").GetProperty("requestBody").GetProperty("content");
|
|
||||||
Assert.True(create.TryGetProperty("application/json", out _));
|
|
||||||
var createSchema = create.GetProperty("multipart/form-data").GetProperty("schema");
|
|
||||||
Assert.Contains(createSchema.GetProperty("required").EnumerateArray(), field => field.GetString() == "categoryId");
|
|
||||||
var uploadSchema = paths.GetProperty("/api/v1/issues/{id}/attachments").GetProperty("post")
|
|
||||||
.GetProperty("requestBody").GetProperty("content").GetProperty("multipart/form-data").GetProperty("schema");
|
|
||||||
Assert.Equal("files", Assert.Single(uploadSchema.GetProperty("required").EnumerateArray()).GetString());
|
|
||||||
var files = uploadSchema.GetProperty("properties").GetProperty("files");
|
|
||||||
Assert.Equal(5, files.GetProperty("maxItems").GetInt32());
|
|
||||||
Assert.Equal("binary", files.GetProperty("items").GetProperty("format").GetString());
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task DatabaseRejectsAnAssignedIssueWithoutAnAssignee()
|
|
||||||
{
|
|
||||||
await using var scope = fixture.Services.CreateAsyncScope();
|
|
||||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
|
||||||
var reporterId = await db.Users.Where(user => user.Email == AdminEmail).Select(user => user.Id).SingleAsync(Cancellation);
|
|
||||||
var categoryId = await db.IssueCategories.MinAsync(category => category.Id, Cancellation);
|
|
||||||
|
|
||||||
var error = await Assert.ThrowsAsync<MySqlException>(() => db.Database.ExecuteSqlInterpolatedAsync($"""
|
|
||||||
INSERT INTO issue (title, description, category_id, reporter_id, status)
|
|
||||||
VALUES ('Test', 'Test', {categoryId}, {reporterId}, 'ASSIGNED')
|
|
||||||
""", Cancellation));
|
|
||||||
Assert.Contains("ck_issue_assignee", error.Message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<IsPackable>false</IsPackable>
|
|
||||||
<OutputType>Exe</OutputType>
|
|
||||||
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\..\src\Helpdesk.Api\Helpdesk.Api.csproj" />
|
|
||||||
<ProjectReference Include="..\..\src\Helpdesk.Migrator\Helpdesk.Migrator.csproj" />
|
|
||||||
<None Include="..\..\..\db\migrations\V*__*.sql" Link="migrations\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
|
|
||||||
<PackageReference Include="Microsoft.Testing.Extensions.CodeCoverage" PrivateAssets="all" />
|
|
||||||
<PackageReference Include="MySqlConnector" />
|
|
||||||
<PackageReference Include="Testcontainers.MariaDb" />
|
|
||||||
<PackageReference Include="xunit.v3" />
|
|
||||||
<Using Include="Xunit" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
@@ -1,161 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Net.Http.Json;
|
|
||||||
using Helpdesk.Application.Catalogs;
|
|
||||||
using Helpdesk.Application.Common;
|
|
||||||
using Helpdesk.Application.Issues;
|
|
||||||
using Helpdesk.Application.Notifications;
|
|
||||||
using Helpdesk.Application.Statistics;
|
|
||||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
|
||||||
|
|
||||||
namespace Helpdesk.IntegrationTests;
|
|
||||||
|
|
||||||
public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt()
|
|
||||||
{
|
|
||||||
using var anonymous = fixture.CreateClient();
|
|
||||||
var administrator = await LoginAsync(anonymous, AdminEmail);
|
|
||||||
using var admin = fixture.CreateClient(administrator.AccessToken);
|
|
||||||
var author = await fixture.RegisterAsync(anonymous);
|
|
||||||
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, author.Email)).AccessToken);
|
|
||||||
var management = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
|
|
||||||
var firstAssignee = await fixture.RegisterStaffAsync(anonymous, admin, "FACILITY_MANAGER");
|
|
||||||
var secondAssignee = await fixture.RegisterStaffAsync(anonymous, admin, "FACILITY_MANAGER");
|
|
||||||
using var manager = fixture.CreateClient(management.AccessToken);
|
|
||||||
using var firstSolver = fixture.CreateClient(firstAssignee.AccessToken);
|
|
||||||
using var secondSolver = fixture.CreateClient(secondAssignee.AccessToken);
|
|
||||||
|
|
||||||
var categories = await ReadAsync<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
|
|
||||||
var buildings = await ReadAsync<BuildingDto[]>(reporter.GetAsync("/api/v1/buildings", Cancellation));
|
|
||||||
var request = new CreateIssueRequest("Nefunkční projektor", "Projektor se nezapne.", categories[0].Id, buildings[0].Id, "A101");
|
|
||||||
var issue = await PostIssueAsync(reporter, "/api/v1/issues", request, HttpStatusCode.Created);
|
|
||||||
var path = $"/api/v1/issues/{issue.Id}";
|
|
||||||
Assert.Equal("RECEIVED", issue.Status);
|
|
||||||
await ExpectAsync(anonymous.GetAsync(path, Cancellation), HttpStatusCode.Unauthorized);
|
|
||||||
|
|
||||||
issue = await ReadAsync<IssueDetail>(reporter.PutAsJsonAsync(path,
|
|
||||||
new EditIssueRequest(issue.Title, "Projektor nereaguje ani po restartu.", issue.CategoryId,
|
|
||||||
issue.BuildingId, issue.LocationDetail, issue.RowVersion), Cancellation));
|
|
||||||
Assert.Equal("Projektor nereaguje ani po restartu.", issue.Description);
|
|
||||||
issue = await ReadAsync<IssueDetail>(admin.PutAsJsonAsync(path,
|
|
||||||
new EditIssueRequest(issue.Title, issue.Description, issue.CategoryId,
|
|
||||||
issue.BuildingId, "A102", issue.RowVersion), Cancellation));
|
|
||||||
Assert.Equal(("A102", author.Id), (issue.LocationDetail, issue.ReporterId));
|
|
||||||
var assign = new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion);
|
|
||||||
await ExpectAsync(reporter.PostAsJsonAsync(path + "/assign", assign, Cancellation), HttpStatusCode.Forbidden);
|
|
||||||
issue = await PostIssueAsync(admin, path + "/assign", assign);
|
|
||||||
Assert.Equal(firstAssignee.User.Id, issue.AssigneeId);
|
|
||||||
Assert.Contains("ASSIGN", (await ReadAsync<IssueDetail>(admin.GetAsync(path, Cancellation))).AllowedActions);
|
|
||||||
var adminIssues = await ReadAsync<PagedResult<IssueSummary>>(admin.GetAsync("/api/v1/issues", Cancellation));
|
|
||||||
Assert.Contains(adminIssues.Items, item => item.Id == issue.Id);
|
|
||||||
var assignable = await ReadAsync<AssignableUserDto[]>(admin.GetAsync("/api/v1/users/assignable", Cancellation));
|
|
||||||
Assert.Contains(assignable, user => user.Id == firstAssignee.User.Id);
|
|
||||||
Assert.Contains(assignable, user => user.Id == administrator.User.Id);
|
|
||||||
await ExpectAsync(firstSolver.PostAsJsonAsync(path + "/start",
|
|
||||||
new IssueVersionRequest(assign.RowVersion), Cancellation), HttpStatusCode.Conflict);
|
|
||||||
|
|
||||||
var reporterNotifications = await InboxAsync(reporter, issue.Id);
|
|
||||||
Assert.Equal("ISSUE_STATUS_CHANGED", Assert.Single(reporterNotifications).Type);
|
|
||||||
issue = await PostIssueAsync(manager, path + "/assign", new AssignIssueRequest(secondAssignee.User.Id, null, issue.RowVersion));
|
|
||||||
Assert.Equal("ISSUE_ASSIGNED", Assert.Single(await InboxAsync(secondSolver, issue.Id)).Type);
|
|
||||||
Assert.Equal(reporterNotifications, await InboxAsync(reporter, issue.Id));
|
|
||||||
|
|
||||||
issue = await PostIssueAsync(admin, path + "/start", new IssueVersionRequest(issue.RowVersion));
|
|
||||||
Assert.Equal("IN_PROGRESS", issue.Status);
|
|
||||||
reporterNotifications = await InboxAsync(reporter, issue.Id);
|
|
||||||
issue = await PostIssueAsync(admin, path + "/assign", new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion));
|
|
||||||
Assert.Equal("ASSIGNED", issue.Status);
|
|
||||||
var reassignment = Assert.Single((await InboxAsync(reporter, issue.Id)).Except(reporterNotifications));
|
|
||||||
Assert.Equal("ISSUE_STATUS_CHANGED", reassignment.Type);
|
|
||||||
Assert.Equal(2, (await InboxAsync(firstSolver, issue.Id)).Count(notification => notification.Type == "ISSUE_ASSIGNED"));
|
|
||||||
|
|
||||||
issue = await PostIssueAsync(firstSolver, path + "/start", new IssueVersionRequest(issue.RowVersion));
|
|
||||||
const string commentText = "Porucha stále trvá.";
|
|
||||||
var comment = await ReadAsync<IssueEventDto>(admin.PostAsJsonAsync(path + "/comments",
|
|
||||||
new CommentRequest(commentText), Cancellation));
|
|
||||||
Assert.Equal(administrator.User.Id, comment.ActorId);
|
|
||||||
issue = await ReadAsync<IssueDetail>(firstSolver.GetAsync(path, Cancellation));
|
|
||||||
issue = await PostIssueAsync(firstSolver, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, null));
|
|
||||||
Assert.Equal("PENDING_VERIFICATION", issue.Status);
|
|
||||||
issue = await PostIssueAsync(admin, path + "/reopen", new IssueReasonRequest(issue.RowVersion, "Porucha se vrátila."));
|
|
||||||
Assert.Equal("IN_PROGRESS", issue.Status);
|
|
||||||
Assert.Contains(await InboxAsync(firstSolver, issue.Id), notification => notification.Type == "ISSUE_REOPENED");
|
|
||||||
issue = await PostIssueAsync(admin, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, "Ověřeno."));
|
|
||||||
issue = await PostIssueAsync(admin, path + "/confirm", new IssueVersionRequest(issue.RowVersion));
|
|
||||||
Assert.Equal("RESOLVED", issue.Status);
|
|
||||||
var events = await ReadAsync<IssueEventDto[]>(reporter.GetAsync(path + "/events", Cancellation));
|
|
||||||
Assert.Equal(commentText, Assert.Single(events, entry => entry.Id == comment.Id).Note);
|
|
||||||
Assert.Equal("RESOLVED", events[^1].ToStatus);
|
|
||||||
|
|
||||||
var openIssue = await PostIssueAsync(reporter, "/api/v1/issues",
|
|
||||||
request with { Title = "Porucha osvětlení" }, HttpStatusCode.Created);
|
|
||||||
await VerifyReadsAsync(reporter, manager, issue, openIssue);
|
|
||||||
var rejected = await PostIssueAsync(manager, $"/api/v1/issues/{openIssue.Id}/reject",
|
|
||||||
new IssueReasonRequest(openIssue.RowVersion, "Duplicitní hlášení."));
|
|
||||||
Assert.Equal("REJECTED", rejected.Status);
|
|
||||||
|
|
||||||
var officeIssue = await PostIssueAsync(reporter, "/api/v1/issues",
|
|
||||||
request with { Title = "Porucha v kanceláři" }, HttpStatusCode.Created);
|
|
||||||
var officePath = $"/api/v1/issues/{officeIssue.Id}";
|
|
||||||
officeIssue = await PostIssueAsync(manager, officePath + "/assign",
|
|
||||||
new AssignIssueRequest(administrator.User.Id, null, officeIssue.RowVersion));
|
|
||||||
Assert.Equal(administrator.User.Id, officeIssue.AssigneeId);
|
|
||||||
Assert.Equal("ISSUE_ASSIGNED", Assert.Single(await InboxAsync(admin, officeIssue.Id)).Type);
|
|
||||||
var rejectedByAdmin = await PostIssueAsync(admin, officePath + "/reject",
|
|
||||||
new IssueReasonRequest(officeIssue.RowVersion, "Hlášení je duplicitní."));
|
|
||||||
Assert.Equal("REJECTED", rejectedByAdmin.Status);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task VerifyReadsAsync(HttpClient reporter, HttpClient manager, IssueDetail resolved, IssueDetail open)
|
|
||||||
{
|
|
||||||
var query = $"/api/v1/issues?categoryId={resolved.CategoryId}&buildingId={resolved.BuildingId}&pageSize=1";
|
|
||||||
var first = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&page=1", Cancellation));
|
|
||||||
var second = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&page=2", Cancellation));
|
|
||||||
var filtered = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&status=RESOLVED", Cancellation));
|
|
||||||
Assert.Equal(2, first.TotalCount);
|
|
||||||
Assert.Equal(open.Id, Assert.Single(first.Items).Id);
|
|
||||||
Assert.Equal(resolved.Id, Assert.Single(second.Items).Id);
|
|
||||||
Assert.Equal(1, filtered.TotalCount);
|
|
||||||
Assert.Equal(resolved.Id, Assert.Single(filtered.Items).Id);
|
|
||||||
|
|
||||||
const string overview = "/api/v1/statistics/overview";
|
|
||||||
await ExpectAsync(reporter.GetAsync(overview, Cancellation), HttpStatusCode.Forbidden);
|
|
||||||
var from = Uri.EscapeDataString(resolved.CreatedAt.AddMinutes(-1).ToString("O"));
|
|
||||||
var to = Uri.EscapeDataString(open.CreatedAt.AddMinutes(1).ToString("O"));
|
|
||||||
var period = $"?from={from}&to={to}";
|
|
||||||
var statistics = await ReadAsync<StatisticsOverview>(manager.GetAsync(overview + period, Cancellation));
|
|
||||||
Assert.Equal(2, statistics.TotalIssues);
|
|
||||||
Assert.Equal(1, statistics.IssuesByStatus["RESOLVED"]);
|
|
||||||
Assert.Equal(1, statistics.IssuesByStatus["RECEIVED"]);
|
|
||||||
Assert.NotNull(statistics.AverageHoursToAssignment);
|
|
||||||
Assert.NotNull(statistics.AverageHoursToClosure);
|
|
||||||
var byCategory = Assert.Single(await ReadAsync<IssueCategoryStatistics[]>(
|
|
||||||
manager.GetAsync("/api/v1/statistics/issues/by-category" + period, Cancellation)));
|
|
||||||
Assert.Equal((resolved.CategoryId, 2), (byCategory.CategoryId, byCategory.IssueCount));
|
|
||||||
Assert.NotNull(byCategory.AverageHoursToResolution);
|
|
||||||
var byBuilding = Assert.Single(await ReadAsync<IssueBuildingStatistics[]>(
|
|
||||||
manager.GetAsync("/api/v1/statistics/issues/by-building" + period, Cancellation)));
|
|
||||||
Assert.Equal((resolved.BuildingId, 2), (byBuilding.BuildingId, byBuilding.IssueCount));
|
|
||||||
var byAssignee = Assert.Single(await ReadAsync<IssueAssigneeStatistics[]>(
|
|
||||||
manager.GetAsync("/api/v1/statistics/issues/by-assignee" + period, Cancellation)));
|
|
||||||
Assert.Equal((resolved.AssigneeId, 1, 0), ((int?)byAssignee.AssigneeId, byAssignee.ResolvedIssues, byAssignee.OpenIssues));
|
|
||||||
var available = await ReadAsync<AssignableUserDto[]>(manager.GetAsync("/api/v1/users/assignable", Cancellation));
|
|
||||||
Assert.Contains(available, user => user.Id == resolved.AssigneeId && user.OpenIssues == 0);
|
|
||||||
var trend = await ReadAsync<IssueTrendPoint[]>(manager.GetAsync("/api/v1/statistics/issues/trend" + period, Cancellation));
|
|
||||||
Assert.Equal(2, trend.Sum(point => point.CreatedIssues));
|
|
||||||
Assert.Equal(1, trend.Sum(point => point.ClosedIssues));
|
|
||||||
var after = await ReadAsync<StatisticsOverview>(manager.GetAsync(overview + $"?from={to}", Cancellation));
|
|
||||||
Assert.Equal(0, after.TotalIssues);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task<IssueDetail> PostIssueAsync<T>(
|
|
||||||
HttpClient client, string path, T request, HttpStatusCode expected = HttpStatusCode.OK) =>
|
|
||||||
ReadAsync<IssueDetail>(client.PostAsJsonAsync(path, request, Cancellation), expected);
|
|
||||||
|
|
||||||
private static async Task<NotificationDto[]> InboxAsync(HttpClient client, int issueId)
|
|
||||||
{
|
|
||||||
var notifications = await ReadAsync<PagedResult<NotificationDto>>(client.GetAsync("/api/v1/notifications", Cancellation));
|
|
||||||
return notifications.Items.Where(notification => notification.IssueId == issueId).ToArray();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Net.Http.Json;
|
|
||||||
using Helpdesk.Api.Controllers;
|
|
||||||
using Helpdesk.Application.Catalogs;
|
|
||||||
using Helpdesk.Application.Common;
|
|
||||||
using Helpdesk.Application.Issues;
|
|
||||||
using Helpdesk.Application.Notifications;
|
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
|
||||||
|
|
||||||
namespace Helpdesk.IntegrationTests;
|
|
||||||
|
|
||||||
public sealed class NotificationTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public async Task FailedEmailCanBeRetriedAndOnlyTheRecipientCanMarkNotificationsRead()
|
|
||||||
{
|
|
||||||
using var anonymous = fixture.CreateClient();
|
|
||||||
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
|
||||||
var user = await fixture.RegisterAsync(anonymous);
|
|
||||||
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
|
|
||||||
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
|
|
||||||
using var manager = fixture.CreateClient(managerSession.AccessToken);
|
|
||||||
var categories = await ReadAsync<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
|
|
||||||
var request = new CreateIssueRequest("Porucha v učebně", "Závadu je potřeba prověřit.", categories[0].Id, null, null);
|
|
||||||
const string inbox = "/api/v1/notifications";
|
|
||||||
const string deliveries = "/api/v1/admin/notification-deliveries";
|
|
||||||
|
|
||||||
fixture.FailNextEmail(managerSession.User.Email, "TEST_RECIPIENT_REJECTED", retryable: false);
|
|
||||||
var issue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created);
|
|
||||||
var notifications = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation));
|
|
||||||
var notification = Assert.Single(notifications.Items);
|
|
||||||
Assert.Equal((issue.Id, "ISSUE_CREATED"), (notification.IssueId, notification.Type));
|
|
||||||
await ExpectAsync(reporter.PostAsync($"{inbox}/{notification.Id}/read", null, Cancellation), HttpStatusCode.NotFound);
|
|
||||||
await ExpectAsync(reporter.GetAsync(deliveries, Cancellation), HttpStatusCode.Forbidden);
|
|
||||||
await ExpectAsync(admin.GetAsync(deliveries + "?status=invalid", Cancellation), HttpStatusCode.BadRequest);
|
|
||||||
|
|
||||||
var failed = await WaitForDeliveryAsync(admin, notification.Id, "FAILED");
|
|
||||||
Assert.Equal((1, "TEST_RECIPIENT_REJECTED"), (failed.AttemptCount, failed.LastError));
|
|
||||||
Assert.Null(failed.NextAttemptAt);
|
|
||||||
var retry = $"{deliveries}/{failed.Id}/retry";
|
|
||||||
await ExpectAsync(admin.PostAsync(retry, null, Cancellation), HttpStatusCode.NoContent);
|
|
||||||
var sent = await WaitForDeliveryAsync(admin, notification.Id, "SENT");
|
|
||||||
Assert.Equal(1, sent.AttemptCount);
|
|
||||||
Assert.NotNull(sent.SentAt);
|
|
||||||
Assert.Null(sent.LastError);
|
|
||||||
await ExpectAsync(admin.PostAsync(retry, null, Cancellation), HttpStatusCode.Conflict);
|
|
||||||
await ExpectAsync(admin.PostAsync($"{deliveries}/{int.MaxValue}/retry", null, Cancellation), HttpStatusCode.NotFound);
|
|
||||||
|
|
||||||
var read = $"{inbox}/{notification.Id}/read";
|
|
||||||
await ExpectAsync(manager.PostAsync(read, null, Cancellation), HttpStatusCode.NoContent);
|
|
||||||
await ExpectAsync(manager.PostAsync(read, null, Cancellation), HttpStatusCode.NoContent);
|
|
||||||
Assert.Equal(0, (await ReadAsync<UnreadCountDto>(manager.GetAsync(inbox + "/unread-count", Cancellation))).Count);
|
|
||||||
|
|
||||||
fixture.FailNextEmail(managerSession.User.Email, "TEST_TEMPORARY_FAILURE", retryable: true);
|
|
||||||
var secondIssue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created);
|
|
||||||
notifications = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation));
|
|
||||||
notification = Assert.Single(notifications.Items);
|
|
||||||
Assert.Equal(secondIssue.Id, notification.IssueId);
|
|
||||||
var pending = await WaitForDeliveryAsync(admin, notification.Id, "PENDING", attempts: 1);
|
|
||||||
Assert.Equal("TEST_TEMPORARY_FAILURE", pending.LastError);
|
|
||||||
Assert.True(pending.NextAttemptAt > DateTime.UtcNow);
|
|
||||||
await ExpectAsync(manager.PostAsync(inbox + "/read-all", null, Cancellation), HttpStatusCode.NoContent);
|
|
||||||
Assert.Empty((await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation))).Items);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task DeviceRegistrationPreservesCaseAndTransfersOwnership()
|
|
||||||
{
|
|
||||||
using var anonymous = fixture.CreateClient();
|
|
||||||
var firstUser = await fixture.RegisterAsync(anonymous);
|
|
||||||
var secondUser = await fixture.RegisterAsync(anonymous);
|
|
||||||
using var first = fixture.CreateClient((await LoginAsync(anonymous, firstUser.Email)).AccessToken);
|
|
||||||
using var second = fixture.CreateClient((await LoginAsync(anonymous, secondUser.Email)).AccessToken);
|
|
||||||
const string route = "/api/v1/devices";
|
|
||||||
var token = new RegisterDeviceRequest("CaseSensitiveDevice");
|
|
||||||
var otherCase = new RegisterDeviceRequest("casesensitivedevice");
|
|
||||||
await ExpectAsync(first.PostAsJsonAsync(route, new RegisterDeviceRequest("invalid token"), Cancellation), HttpStatusCode.BadRequest);
|
|
||||||
await ExpectAsync(first.PostAsJsonAsync(route, token, Cancellation), HttpStatusCode.NoContent);
|
|
||||||
await ExpectAsync(first.PostAsJsonAsync(route, otherCase, Cancellation), HttpStatusCode.NoContent);
|
|
||||||
await ExpectAsync(second.PostAsJsonAsync(route, token, Cancellation), HttpStatusCode.NoContent);
|
|
||||||
await ExpectAsync(first.DeleteAsync($"{route}/{token.Token}", Cancellation), HttpStatusCode.NoContent);
|
|
||||||
|
|
||||||
await using var scope = fixture.Services.CreateAsyncScope();
|
|
||||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
|
||||||
var devices = await db.PushDevices.AsNoTracking().ToListAsync(Cancellation);
|
|
||||||
Assert.Equal(secondUser.Id, Assert.Single(devices, item => item.FcmToken == token.Token).UserId);
|
|
||||||
Assert.Equal(firstUser.Id, Assert.Single(devices, item => item.FcmToken == otherCase.Token).UserId);
|
|
||||||
await ExpectAsync(second.DeleteAsync($"{route}/{token.Token}", Cancellation), HttpStatusCode.NoContent);
|
|
||||||
Assert.Equal(otherCase.Token, await db.PushDevices.Select(item => item.FcmToken).SingleAsync(Cancellation));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<NotificationDeliveryDto> WaitForDeliveryAsync(HttpClient client, int notificationId, string status, int attempts = 1)
|
|
||||||
{
|
|
||||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(Cancellation);
|
|
||||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
|
||||||
var path = $"/api/v1/admin/notification-deliveries?status={status}";
|
|
||||||
while (!timeout.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
var page = await ReadAsync<PagedResult<NotificationDeliveryDto>>(client.GetAsync(path, timeout.Token));
|
|
||||||
var delivery = page.Items.SingleOrDefault(item =>
|
|
||||||
item.NotificationId == notificationId && item.Channel == "EMAIL" && item.AttemptCount == attempts);
|
|
||||||
if (delivery is not null)
|
|
||||||
return delivery;
|
|
||||||
await Task.Delay(TimeSpan.FromMilliseconds(100), timeout.Token);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new TimeoutException($"Notification {notificationId} did not reach {status}.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Net.Http.Json;
|
|
||||||
using Helpdesk.Application.Catalogs;
|
|
||||||
using Helpdesk.Application.Common;
|
|
||||||
using Helpdesk.Application.Notifications;
|
|
||||||
using Helpdesk.Application.Proposals;
|
|
||||||
using Helpdesk.Application.Statistics;
|
|
||||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
|
||||||
|
|
||||||
namespace Helpdesk.IntegrationTests;
|
|
||||||
|
|
||||||
public sealed class ProposalWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
|
||||||
{
|
|
||||||
private const string Proposals = "/api/v1/proposals";
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task VotesAndDecisionsAreReflectedInTheProposalAndItsHistory()
|
|
||||||
{
|
|
||||||
using var anonymous = fixture.CreateClient();
|
|
||||||
var administrator = await LoginAsync(anonymous, AdminEmail);
|
|
||||||
using var admin = fixture.CreateClient(administrator.AccessToken);
|
|
||||||
var authorUser = await fixture.RegisterAsync(anonymous);
|
|
||||||
using var author = fixture.CreateClient((await LoginAsync(anonymous, authorUser.Email)).AccessToken);
|
|
||||||
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
|
|
||||||
using var manager = fixture.CreateClient(managerSession.AccessToken);
|
|
||||||
var categories = await ReadAsync<CategoryDto[]>(author.GetAsync("/api/v1/proposal-categories", Cancellation));
|
|
||||||
var request = new SaveProposalRequest("Prodloužení studovny", "Rozšířit večerní otevírací dobu.", categories[0].Id);
|
|
||||||
await ExpectAsync(author.PostAsJsonAsync(Proposals, request with { Title = " " }, Cancellation), HttpStatusCode.BadRequest);
|
|
||||||
await ExpectAsync(author.PostAsJsonAsync(Proposals, request with { CategoryId = int.MaxValue }, Cancellation), HttpStatusCode.BadRequest);
|
|
||||||
|
|
||||||
var proposal = await ReadAsync<ProposalDetail>(author.PostAsJsonAsync(Proposals, request, Cancellation), HttpStatusCode.Created);
|
|
||||||
Assert.Equal("SUBMITTED", proposal.Status);
|
|
||||||
var path = $"{Proposals}/{proposal.Id}";
|
|
||||||
var edit = request with { CategoryId = categories[1].Id, Description = "Otevřít do 22 hodin." };
|
|
||||||
await ExpectAsync(manager.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.Forbidden);
|
|
||||||
proposal = await ReadAsync<ProposalDetail>(author.PutAsJsonAsync(path, edit, Cancellation));
|
|
||||||
Assert.Equal((edit.CategoryId, edit.Description, "UPDATED"), (proposal.CategoryId, proposal.Description, proposal.Events[^1].EventType));
|
|
||||||
var adminEdit = edit with { Description = "Otevřít do 22 hodin ve všední dny." };
|
|
||||||
proposal = await ReadAsync<ProposalDetail>(admin.PutAsJsonAsync(path, adminEdit, Cancellation));
|
|
||||||
Assert.Equal((adminEdit.Description, authorUser.Id, administrator.User.Id),
|
|
||||||
(proposal.Description, proposal.AuthorId, proposal.Events[^1].ActorId));
|
|
||||||
var other = await ReadAsync<ProposalDetail>(author.PostAsJsonAsync(Proposals, edit with
|
|
||||||
{
|
|
||||||
Title = "Vybavení studovny",
|
|
||||||
}, Cancellation), HttpStatusCode.Created);
|
|
||||||
|
|
||||||
await VerifyVotesAsync(author, manager, path);
|
|
||||||
var from = Uri.EscapeDataString(proposal.CreatedAt.AddMinutes(-1).ToString("O"));
|
|
||||||
var to = Uri.EscapeDataString(other.CreatedAt.AddMinutes(1).ToString("O"));
|
|
||||||
var filter = $"{Proposals}?status=SUBMITTED&categoryId={edit.CategoryId}&authorId={authorUser.Id}&q=studovny&from={from}&to={to}";
|
|
||||||
var first = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter + "&sort=score&pageSize=1", Cancellation));
|
|
||||||
var second = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter + "&sort=score&pageSize=1&page=2", Cancellation));
|
|
||||||
Assert.Equal(2, first.TotalCount);
|
|
||||||
Assert.Equal(proposal.Id, Assert.Single(first.Items).Id);
|
|
||||||
Assert.Equal(other.Id, Assert.Single(second.Items).Id);
|
|
||||||
var newest = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter, Cancellation));
|
|
||||||
Assert.Equal(other.Id, newest.Items[0].Id);
|
|
||||||
var outside = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync($"{Proposals}?from={to}", Cancellation));
|
|
||||||
Assert.Empty(outside.Items);
|
|
||||||
|
|
||||||
await ExpectAsync(author.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("ACCEPTED", null), Cancellation),
|
|
||||||
HttpStatusCode.Forbidden);
|
|
||||||
await ExpectAsync(manager.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("REJECTED", " "), Cancellation),
|
|
||||||
HttpStatusCode.BadRequest);
|
|
||||||
await ExpectAsync(admin.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("IMPLEMENTED", null), Cancellation),
|
|
||||||
HttpStatusCode.Conflict);
|
|
||||||
var review = await ReadAsync<ProposalDetail>(admin.PostAsJsonAsync(path + "/status",
|
|
||||||
new ChangeProposalStatusRequest("UNDER_REVIEW", null), Cancellation));
|
|
||||||
Assert.Equal("UNDER_REVIEW", review.Status);
|
|
||||||
var accepted = await ReadAsync<ProposalDetail>(manager.PostAsJsonAsync(path + "/status",
|
|
||||||
new ChangeProposalStatusRequest("ACCEPTED", " Schváleno. "), Cancellation));
|
|
||||||
Assert.Equal(("ACCEPTED", "Schváleno."), (accepted.Status, accepted.Events[^1].Note));
|
|
||||||
await ExpectAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.Conflict);
|
|
||||||
await ExpectAsync(manager.DeleteAsync(path + "/vote", Cancellation), HttpStatusCode.Conflict);
|
|
||||||
|
|
||||||
var inbox = await ReadAsync<PagedResult<NotificationDto>>(author.GetAsync("/api/v1/notifications", Cancellation));
|
|
||||||
Assert.Equal(2, inbox.Items.Count(item => item.ProposalId == proposal.Id && item.Type == "PROPOSAL_STATUS_CHANGED"));
|
|
||||||
var top = Assert.Single(await ReadAsync<TopProposal[]>(
|
|
||||||
admin.GetAsync($"/api/v1/statistics/proposals/top?limit=1&from={from}&to={to}", Cancellation)));
|
|
||||||
Assert.Equal((proposal.Id, 1L), (top.Id, top.Score));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task VerifyVotesAsync(HttpClient author, HttpClient voter, string path)
|
|
||||||
{
|
|
||||||
var vote = path + "/vote";
|
|
||||||
await ExpectAsync(author.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.Forbidden);
|
|
||||||
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(0), Cancellation), HttpStatusCode.BadRequest);
|
|
||||||
|
|
||||||
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.NoContent);
|
|
||||||
var detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
|
|
||||||
Assert.Equal((1L, 0L, 1L, (int?)1), (detail.VotesFor, detail.VotesAgainst, detail.Score, detail.MyVote));
|
|
||||||
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(-1), Cancellation), HttpStatusCode.NoContent);
|
|
||||||
detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
|
|
||||||
Assert.Equal((0L, 1L, -1L, (int?)-1), (detail.VotesFor, detail.VotesAgainst, detail.Score, detail.MyVote));
|
|
||||||
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(-1), Cancellation), HttpStatusCode.NoContent);
|
|
||||||
await ExpectAsync(voter.DeleteAsync(vote, Cancellation), HttpStatusCode.NoContent);
|
|
||||||
detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
|
|
||||||
Assert.Equal(0L, detail.Score);
|
|
||||||
Assert.Null(detail.MyVote);
|
|
||||||
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.NoContent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using Microsoft.AspNetCore.TestHost;
|
|
||||||
using static Helpdesk.IntegrationTests.BackendFixture;
|
|
||||||
|
|
||||||
namespace Helpdesk.IntegrationTests;
|
|
||||||
|
|
||||||
public sealed class ProxyRateLimitTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public async Task TrustedProxiesShareTheLimitForEachClientAndSeparateDifferentClients()
|
|
||||||
{
|
|
||||||
const string externalProxy = "192.0.2.10";
|
|
||||||
const string web = "192.0.2.11";
|
|
||||||
const string firstClient = "198.51.100.10";
|
|
||||||
const string secondClient = "198.51.100.11";
|
|
||||||
await using var api = fixture.CreateApiBehindProxies(externalProxy, web);
|
|
||||||
|
|
||||||
for (var attempt = 0; attempt < 20; attempt++)
|
|
||||||
Assert.Equal(401, await LoginAsync(api.Server, web, firstClient));
|
|
||||||
|
|
||||||
Assert.Equal(429, await LoginAsync(api.Server, externalProxy, firstClient));
|
|
||||||
Assert.Equal(401, await LoginAsync(api.Server, web, secondClient));
|
|
||||||
Assert.Equal(429, await LoginAsync(api.Server, $"::ffff:{firstClient}", secondClient));
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<int> LoginAsync(TestServer server, string peer, string client)
|
|
||||||
{
|
|
||||||
using var body = new MemoryStream("""{"email":"absent@example.test","password":"test-password"}"""u8.ToArray());
|
|
||||||
var response = await server.SendAsync(context =>
|
|
||||||
{
|
|
||||||
context.Connection.RemoteIpAddress = IPAddress.Parse(peer);
|
|
||||||
context.Request.Method = "POST";
|
|
||||||
context.Request.Path = "/api/v1/auth/login";
|
|
||||||
context.Request.ContentType = "application/json";
|
|
||||||
context.Request.ContentLength = body.Length;
|
|
||||||
context.Request.Body = body;
|
|
||||||
context.Request.Headers["X-Forwarded-For"] = client;
|
|
||||||
}, Cancellation);
|
|
||||||
return response.Response.StatusCode;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
using Helpdesk.Domain.Auth;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
|
||||||
|
|
||||||
namespace Helpdesk.IntegrationTests;
|
|
||||||
|
|
||||||
internal sealed class TokenSaveGate : SaveChangesInterceptor
|
|
||||||
{
|
|
||||||
private Pause? next;
|
|
||||||
|
|
||||||
internal Pause PauseNextSave()
|
|
||||||
{
|
|
||||||
var pause = new Pause();
|
|
||||||
if (Interlocked.CompareExchange(ref next, pause, null) is not null)
|
|
||||||
throw new InvalidOperationException("A save is already scheduled to pause.");
|
|
||||||
return pause;
|
|
||||||
}
|
|
||||||
|
|
||||||
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(
|
|
||||||
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
if (Volatile.Read(ref next) is not null &&
|
|
||||||
eventData.Context!.ChangeTracker.Entries<AuthToken>()
|
|
||||||
.Any(entry => entry.State == EntityState.Added && entry.Entity.TokenType == TokenType.Refresh) &&
|
|
||||||
Interlocked.Exchange(ref next, null) is { } pause)
|
|
||||||
{
|
|
||||||
pause.Entered.TrySetResult();
|
|
||||||
await pause.Released.Task.WaitAsync(cancellationToken);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
internal sealed class Pause
|
|
||||||
{
|
|
||||||
internal TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
||||||
internal TaskCompletionSource Released { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
||||||
|
|
||||||
internal void Release() => Released.TrySetResult();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<Configuration>
|
|
||||||
<CodeCoverage>
|
|
||||||
<EnableStaticManagedInstrumentation>True</EnableStaticManagedInstrumentation>
|
|
||||||
<EnableDynamicManagedInstrumentation>False</EnableDynamicManagedInstrumentation>
|
|
||||||
<CollectFromChildProcesses>True</CollectFromChildProcesses>
|
|
||||||
<ModulePaths>
|
|
||||||
<Include>
|
|
||||||
<ModulePath>(^|[\\/])Helpdesk\.(Api|Application|Domain|Infrastructure|Migrator)\.dll$</ModulePath>
|
|
||||||
</Include>
|
|
||||||
</ModulePaths>
|
|
||||||
<Sources>
|
|
||||||
<Exclude>
|
|
||||||
<Source>[\\/]obj[\\/]</Source>
|
|
||||||
</Exclude>
|
|
||||||
</Sources>
|
|
||||||
</CodeCoverage>
|
|
||||||
</Configuration>
|
|
||||||
@@ -21,18 +21,15 @@ public sealed class IssueTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(IssueStatus.Received, UserRole.Management)]
|
[InlineData(IssueStatus.Received)]
|
||||||
[InlineData(IssueStatus.Assigned, UserRole.Management)]
|
[InlineData(IssueStatus.Assigned)]
|
||||||
[InlineData(IssueStatus.InProgress, UserRole.Management)]
|
[InlineData(IssueStatus.InProgress)]
|
||||||
[InlineData(IssueStatus.Received, UserRole.Admin)]
|
public void ManagementCanAssignOrReassign(IssueStatus from)
|
||||||
[InlineData(IssueStatus.Assigned, UserRole.Admin)]
|
|
||||||
[InlineData(IssueStatus.InProgress, UserRole.Admin)]
|
|
||||||
public void ManagementAndAdminCanAssignOrReassign(IssueStatus from, UserRole role)
|
|
||||||
{
|
{
|
||||||
var issue = At(from);
|
var issue = At(from);
|
||||||
var version = issue.RowVersion;
|
var version = issue.RowVersion;
|
||||||
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Assign, Manager, role));
|
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Assign, Manager, UserRole.Management));
|
||||||
issue.Assign(Manager, role, Replacement, UserRole.Management, IssuePriority.High);
|
issue.Assign(Manager, UserRole.Management, Replacement, UserRole.Management, IssuePriority.High);
|
||||||
Assert.Equal(IssueStatus.Assigned, issue.Status);
|
Assert.Equal(IssueStatus.Assigned, issue.Status);
|
||||||
Assert.Equal(Replacement, issue.AssigneeId);
|
Assert.Equal(Replacement, issue.AssigneeId);
|
||||||
Assert.Equal(IssuePriority.High, issue.Priority);
|
Assert.Equal(IssuePriority.High, issue.Priority);
|
||||||
@@ -41,17 +38,12 @@ public sealed class IssueTests
|
|||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueStatus.InProgress)]
|
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueStatus.InProgress)]
|
||||||
[InlineData(IssueStatus.Assigned, IssueAction.StartWork, Replacement, UserRole.Admin, IssueStatus.InProgress)]
|
|
||||||
[InlineData(IssueStatus.InProgress, IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, IssueStatus.PendingVerification)]
|
[InlineData(IssueStatus.InProgress, IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, IssueStatus.PendingVerification)]
|
||||||
[InlineData(IssueStatus.InProgress, IssueAction.SubmitForVerification, Replacement, UserRole.Admin, IssueStatus.PendingVerification)]
|
|
||||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Reporter, UserRole.Admin, IssueStatus.Resolved)]
|
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Reporter, UserRole.Admin, IssueStatus.Resolved)]
|
||||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Replacement, UserRole.Admin, IssueStatus.Resolved)]
|
[InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Reporter, UserRole.Admin, IssueStatus.InProgress)]
|
||||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Replacement, UserRole.Admin, IssueStatus.InProgress)]
|
|
||||||
[InlineData(IssueStatus.Assigned, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)]
|
[InlineData(IssueStatus.Assigned, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)]
|
||||||
[InlineData(IssueStatus.InProgress, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)]
|
[InlineData(IssueStatus.InProgress, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)]
|
||||||
[InlineData(IssueStatus.Received, IssueAction.Reject, Manager, UserRole.Management, IssueStatus.Rejected)]
|
[InlineData(IssueStatus.Received, IssueAction.Reject, Manager, UserRole.Management, IssueStatus.Rejected)]
|
||||||
[InlineData(IssueStatus.Received, IssueAction.Reject, Replacement, UserRole.Admin, IssueStatus.Rejected)]
|
|
||||||
[InlineData(IssueStatus.InProgress, IssueAction.Reject, Replacement, UserRole.Admin, IssueStatus.Rejected)]
|
|
||||||
public void AllowedTransitionsIncrementVersion(
|
public void AllowedTransitionsIncrementVersion(
|
||||||
IssueStatus from, IssueAction action, int actorId, UserRole role, IssueStatus target)
|
IssueStatus from, IssueAction action, int actorId, UserRole role, IssueStatus target)
|
||||||
{
|
{
|
||||||
@@ -71,7 +63,6 @@ public sealed class IssueTests
|
|||||||
[InlineData(IssueStatus.InProgress, IssueAction.StartWork, 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.Confirm, Assignee, UserRole.FacilityManager, IssueActionAvailability.Forbidden)]
|
||||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)]
|
[InlineData(IssueStatus.PendingVerification, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)]
|
||||||
[InlineData(IssueStatus.PendingVerification, IssueAction.Reject, Replacement, UserRole.Admin, IssueActionAvailability.InvalidState)]
|
|
||||||
[InlineData(IssueStatus.Resolved, IssueAction.Reopen, Reporter, UserRole.Admin, IssueActionAvailability.InvalidState)]
|
[InlineData(IssueStatus.Resolved, IssueAction.Reopen, Reporter, UserRole.Admin, IssueActionAvailability.InvalidState)]
|
||||||
[InlineData(IssueStatus.Rejected, IssueAction.Reject, Manager, UserRole.Management, IssueActionAvailability.InvalidState)]
|
[InlineData(IssueStatus.Rejected, IssueAction.Reject, Manager, UserRole.Management, IssueActionAvailability.InvalidState)]
|
||||||
public void DisallowedTransitionsMatchAvailability(
|
public void DisallowedTransitionsMatchAvailability(
|
||||||
@@ -111,12 +102,10 @@ public sealed class IssueTests
|
|||||||
{
|
{
|
||||||
var issue = At(IssueStatus.Assigned);
|
var issue = At(IssueStatus.Assigned);
|
||||||
Assert.True(issue.CanRead(Reporter, UserRole.Admin));
|
Assert.True(issue.CanRead(Reporter, UserRole.Admin));
|
||||||
Assert.True(issue.CanRead(Replacement, UserRole.Admin));
|
Assert.False(issue.CanRead(Replacement, UserRole.Admin));
|
||||||
Assert.False(issue.CanRead(Replacement, UserRole.Student));
|
|
||||||
Assert.True(issue.CanRead(Replacement, UserRole.FacilityManager));
|
Assert.True(issue.CanRead(Replacement, UserRole.FacilityManager));
|
||||||
Assert.Equal(IssueActionAvailability.Forbidden, issue.Availability(IssueAction.Comment, Manager, UserRole.Management));
|
Assert.Equal(IssueActionAvailability.Forbidden, issue.Availability(IssueAction.Comment, Manager, UserRole.Management));
|
||||||
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Comment, Reporter, UserRole.Admin));
|
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Comment, Reporter, UserRole.Admin));
|
||||||
Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.AddAttachments, Replacement, UserRole.Admin));
|
|
||||||
issue.RecordParticipation(IssueAction.Comment, Reporter, UserRole.Admin);
|
issue.RecordParticipation(IssueAction.Comment, Reporter, UserRole.Admin);
|
||||||
issue.Transition(IssueAction.Reject, Assignee, UserRole.FacilityManager, "Důvod");
|
issue.Transition(IssueAction.Reject, Assignee, UserRole.FacilityManager, "Důvod");
|
||||||
Assert.Equal(IssueActionAvailability.InvalidState, issue.Availability(IssueAction.AddAttachments, Reporter, UserRole.Admin));
|
Assert.Equal(IssueActionAvailability.InvalidState, issue.Availability(IssueAction.AddAttachments, Reporter, UserRole.Admin));
|
||||||
|
|||||||
@@ -35,14 +35,12 @@ public sealed class ProposalTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReviewRequiresManagementOrAdminAndRejectionRequiresNote()
|
public void ReviewRequiresManagementAndRejectionRequiresNote()
|
||||||
{
|
{
|
||||||
var proposal = At(ProposalStatus.Submitted);
|
var proposal = At(ProposalStatus.Submitted);
|
||||||
Assert.Throws<InvalidOperationException>(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Student, null));
|
Assert.Throws<InvalidOperationException>(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null));
|
||||||
Assert.Throws<ArgumentException>(() => proposal.ChangeStatus(ProposalStatus.Rejected, UserRole.Admin, " "));
|
Assert.Throws<ArgumentException>(() => proposal.ChangeStatus(ProposalStatus.Rejected, UserRole.Management, " "));
|
||||||
Assert.Equal(ProposalStatus.Submitted, proposal.Status);
|
Assert.Equal(ProposalStatus.Submitted, proposal.Status);
|
||||||
proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null);
|
|
||||||
Assert.Equal(ProposalStatus.Accepted, proposal.Status);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -51,25 +49,22 @@ public sealed class ProposalTests
|
|||||||
[InlineData(ProposalStatus.Accepted, false, false)]
|
[InlineData(ProposalStatus.Accepted, false, false)]
|
||||||
[InlineData(ProposalStatus.Rejected, false, false)]
|
[InlineData(ProposalStatus.Rejected, false, false)]
|
||||||
[InlineData(ProposalStatus.Implemented, false, false)]
|
[InlineData(ProposalStatus.Implemented, false, false)]
|
||||||
public void AuthorAndAdminEditAndOtherUsersVoteOnlyInEligibleStates(ProposalStatus state, bool mayEdit, bool mayVote)
|
public void AuthorEditsAndOtherUserVotesOnlyInEligibleStates(ProposalStatus state, bool mayEdit, bool mayVote)
|
||||||
{
|
{
|
||||||
var proposal = At(state);
|
var proposal = At(state);
|
||||||
Assert.Equal(mayEdit, proposal.IsEditable);
|
Assert.Equal(mayEdit, proposal.CanEdit(Author));
|
||||||
|
Assert.False(proposal.CanEdit(Voter));
|
||||||
Assert.False(proposal.CanVote(Author));
|
Assert.False(proposal.CanVote(Author));
|
||||||
Assert.Equal(mayVote, proposal.CanVote(Voter));
|
Assert.Equal(mayVote, proposal.CanVote(Voter));
|
||||||
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Voter, UserRole.Student, "Změna", "Popis", 1));
|
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Voter, "Změna", "Popis", 1));
|
||||||
if (mayEdit)
|
if (mayEdit)
|
||||||
{
|
{
|
||||||
proposal.Edit(Author, UserRole.Student, "Změna", "Popis", 1);
|
proposal.Edit(Author, "Změna", "Popis", 1);
|
||||||
Assert.Equal("Změna", proposal.Title);
|
Assert.Equal("Změna", proposal.Title);
|
||||||
proposal.Edit(Voter, UserRole.Admin, "Další změna", "Popis", 1);
|
|
||||||
Assert.Equal("Další změna", proposal.Title);
|
|
||||||
Assert.Equal(Author, proposal.AuthorId);
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Author, UserRole.Student, "Změna", "Popis", 1));
|
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Author, "Změna", "Popis", 1));
|
||||||
Assert.Throws<InvalidOperationException>(() => proposal.Edit(Voter, UserRole.Admin, "Změna", "Popis", 1));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-4
@@ -19,13 +19,10 @@ ADMIN_PASSWORD=change-me-admin
|
|||||||
# Loopback použijte pro reverse proxy běžící přímo na stejném hostiteli.
|
# Loopback použijte pro reverse proxy běžící přímo na stejném hostiteli.
|
||||||
PROXY_UPSTREAM_BIND_ADDRESS=127.0.0.1
|
PROXY_UPSTREAM_BIND_ADDRESS=127.0.0.1
|
||||||
API_HTTP_PORT=8080
|
API_HTTP_PORT=8080
|
||||||
# Port webové aplikace na hostiteli (stejná adresa jako API).
|
# Adresa reverse proxy tak, jak ji API vidí jako bezprostředního klienta.
|
||||||
WEB_HTTP_PORT=8081
|
|
||||||
# Adresa reverse proxy tak, jak ji API a web vidí jako bezprostředního klienta.
|
|
||||||
TRUSTED_REVERSE_PROXY_IP=
|
TRUSTED_REVERSE_PROXY_IP=
|
||||||
|
|
||||||
# Veřejná HTTPS adresa webu pro odkazy v e-mailech a povolené univerzitní domény.
|
# Veřejná HTTPS adresa webu pro odkazy v e-mailech a povolené univerzitní domény.
|
||||||
# Lokálně bez proxy: http://localhost:8081 (odkazy z e-mailů pak vedou na web v Dockeru).
|
|
||||||
PUBLIC_BASE_URL= #https://helpdesk.domain.local
|
PUBLIC_BASE_URL= #https://helpdesk.domain.local
|
||||||
STUDENT_EMAIL_DOMAIN= #student.domain.local
|
STUDENT_EMAIL_DOMAIN= #student.domain.local
|
||||||
TEACHER_EMAIL_DOMAIN= #domain.local
|
TEACHER_EMAIL_DOMAIN= #domain.local
|
||||||
@@ -43,3 +40,5 @@ FIREBASE_SERVICE_ACCOUNT_JSON=''
|
|||||||
# Development = bez proxy
|
# Development = bez proxy
|
||||||
# Production = s reverse proxy
|
# Production = s reverse proxy
|
||||||
ASPNETCORE_ENVIRONMENT=Development
|
ASPNETCORE_ENVIRONMENT=Development
|
||||||
|
|
||||||
|
API_PORT=8080
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
# Vývojové spuštění: 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
|
||||||
# Reverse proxy ukončuje HTTPS a připojuje se k webu a API přes HTTP
|
# Reverse proxy ukončuje HTTPS a připojuje se k API přes HTTP.
|
||||||
# (/ včetně /swagger → web, /api/* → api).
|
|
||||||
|
|
||||||
name: helpdesk
|
name: helpdesk
|
||||||
|
|
||||||
@@ -53,7 +52,6 @@ services:
|
|||||||
Smtp__Password: ${SMTP_PASSWORD:-}
|
Smtp__Password: ${SMTP_PASSWORD:-}
|
||||||
Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-}
|
Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-}
|
||||||
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
|
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
|
||||||
ReverseProxy__TrustedWebIp: ${WEB_API_WEB_IP:-172.30.242.6}
|
|
||||||
ADMIN_EMAIL: ${ADMIN_EMAIL:-}
|
ADMIN_EMAIL: ${ADMIN_EMAIL:-}
|
||||||
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
||||||
volumes:
|
volumes:
|
||||||
@@ -63,44 +61,13 @@ services:
|
|||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
ports:
|
ports:
|
||||||
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080"
|
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080"
|
||||||
networks:
|
networks: [frontend, backend]
|
||||||
frontend:
|
|
||||||
backend:
|
|
||||||
web-api:
|
|
||||||
aliases: [api-web]
|
|
||||||
|
|
||||||
web:
|
|
||||||
build:
|
|
||||||
context: ..
|
|
||||||
dockerfile: web/Dockerfile
|
|
||||||
environment:
|
|
||||||
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development}
|
|
||||||
Api__BaseUrl: http://api-web:8080/
|
|
||||||
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
|
|
||||||
volumes:
|
|
||||||
# Klíče pro šifrování cookie – bez nich by restart kontejneru odhlásil všechny uživatele.
|
|
||||||
- web-keys:/app/keys
|
|
||||||
depends_on:
|
|
||||||
- api
|
|
||||||
ports:
|
|
||||||
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${WEB_HTTP_PORT:-8081}:8080"
|
|
||||||
networks:
|
|
||||||
frontend:
|
|
||||||
web-api:
|
|
||||||
ipv4_address: ${WEB_API_WEB_IP:-172.30.242.6}
|
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
frontend:
|
frontend:
|
||||||
backend:
|
backend:
|
||||||
internal: true
|
internal: true
|
||||||
web-api:
|
|
||||||
# Při kolizi s existující sítí lze společně přepsat WEB_API_SUBNET a WEB_API_WEB_IP.
|
|
||||||
internal: true
|
|
||||||
ipam:
|
|
||||||
config:
|
|
||||||
- subnet: ${WEB_API_SUBNET:-172.30.242.0/29}
|
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
db-data:
|
db-data:
|
||||||
uploads:
|
uploads:
|
||||||
web-keys:
|
|
||||||
+79
-82
@@ -72,7 +72,7 @@ Webová i mobilní aplikace jsou **tenké klienty** – nepřistupují do datab
|
|||||||
| `TEACHER` | Vyučující | Samoregistrace | Stejná oprávnění jako student |
|
| `TEACHER` | Vyučující | Samoregistrace | Stejná oprávnění jako student |
|
||||||
| `FACILITY_MANAGER` | Správce budov | Přiděluje administrátor | Řeší přiřazené závady (odpovědná osoba) |
|
| `FACILITY_MANAGER` | Správce budov | Přiděluje administrátor | Řeší přiřazené závady (odpovědná osoba) |
|
||||||
| `MANAGEMENT` | Vedení školy | Přiděluje administrátor | Přiřazuje závady řešitelům, hodnotí návrhy, vidí statistiky |
|
| `MANAGEMENT` | Vedení školy | Přiděluje administrátor | Přiřazuje závady řešitelům, hodnotí návrhy, vidí statistiky |
|
||||||
| `ADMIN` | Administrátor | Přiděluje administrátor / vytvořen při instalaci | Správa systému, všechny akce nad závadami a návrhy, statistiky |
|
| `ADMIN` | Administrátor | Přiděluje administrátor / vytvořen při instalaci | Správa uživatelů a jejich rolí, správa číselníků |
|
||||||
|
|
||||||
- Každý uživatel má **právě jednu roli** (sloupec `app_user.role`). Základní funkce (hlásit závady, podávat návrhy, hlasovat) má každá role, takže kombinace rolí nejsou potřeba – např. vyučující, který je ve vedení, dostane roli `MANAGEMENT`.
|
- Každý uživatel má **právě jednu roli** (sloupec `app_user.role`). Základní funkce (hlásit závady, podávat návrhy, hlasovat) má každá role, takže kombinace rolí nejsou potřeba – např. vyučující, který je ve vedení, dostane roli `MANAGEMENT`.
|
||||||
- Při samoregistraci se role `STUDENT` / `TEACHER` určí automaticky **podle domény e-mailu** (např. `@student.univerzita.cz` → student, `@univerzita.cz` → vyučující). Domény jsou v konfiguraci backendu. Registrace z jiné domény není povolena. Tím se zabrání tomu, aby se student zaregistroval jako vyučující.
|
- Při samoregistraci se role `STUDENT` / `TEACHER` určí automaticky **podle domény e-mailu** (např. `@student.univerzita.cz` → student, `@univerzita.cz` → vyučující). Domény jsou v konfiguraci backendu. Registrace z jiné domény není povolena. Tím se zabrání tomu, aby se student zaregistroval jako vyučující.
|
||||||
@@ -86,26 +86,23 @@ Legenda: ✅ povoleno, 🔸 povoleno s podmínkou, — nepovoleno
|
|||||||
|---|:-:|:-:|:-:|:-:|
|
|---|:-:|:-:|:-:|:-:|
|
||||||
| Nahlásit závadu, přiložit soubory | ✅ | ✅ | ✅ | ✅ |
|
| Nahlásit závadu, přiložit soubory | ✅ | ✅ | ✅ | ✅ |
|
||||||
| Zobrazit vlastní hlášení | ✅ | ✅ | ✅ | ✅ |
|
| Zobrazit vlastní hlášení | ✅ | ✅ | ✅ | ✅ |
|
||||||
| Upravit hlášení | 🔸 vlastní ve stavu *Přijata* | 🔸 vlastní ve stavu *Přijata* | 🔸 vlastní ve stavu *Přijata* | 🔸 libovolné ve stavu *Přijata* |
|
| Upravit vlastní hlášení | 🔸 jen ve stavu *Přijata* | 🔸 | 🔸 | 🔸 |
|
||||||
| 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 | 🔸 ve stavu příslušného přechodu |
|
| 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 nebo nepřiřazené ve stavu *Přijata* | 🔸 ve stavu příslušného přechodu |
|
| Zamítnout závadu (s důvodem) | — | 🔸 jen přiřazené jemu | 🔸 přiřazené jemu nebo nepřiřazené ve stavu *Přijata* | — |
|
||||||
| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 ve stavu *Čeká na ověření* |
|
| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič |
|
||||||
| Komentovat závadu / přidat přílohu | 🔸 hlásič | 🔸 hlásič nebo řešitel | 🔸 hlásič nebo řešitel; ostatní jen čtení | 🔸 libovolná otevřená závada |
|
| 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í | 🔸 | 🔸 | 🔸 |
|
||||||
| Upravit návrh ve stavu *Podán* | 🔸 autor | 🔸 autor | 🔸 autor | ✅ |
|
| Hodnotit návrhy (změna stavu, vyjádření) | — | — | ✅ | — |
|
||||||
| Hodnotit návrhy (změna stavu, vyjádření) | — | — | ✅ | ✅ |
|
| Statistiky a výkazy | — | — | ✅ | — |
|
||||||
| Statistiky a výkazy | — | — | ✅ | ✅ |
|
|
||||||
| Správa uživatelů a rolí | — | — | — | ✅ |
|
| Správa uživatelů a rolí | — | — | — | ✅ |
|
||||||
| Správa číselníků (budovy, kategorie) | — | — | — | ✅ |
|
| Správa číselníků (budovy, kategorie) | — | — | — | ✅ |
|
||||||
|
|
||||||
Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkrétním záznamem** (resource-based authorization) a kontroluje je aplikační vrstva backendu (viz kap. 9.3).
|
Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkrétním záznamem** (resource-based authorization) a kontroluje je aplikační vrstva backendu (viz kap. 9.3).
|
||||||
|
|
||||||
`ADMIN` může spravovat závady a návrhy ostatních uživatelů. Požadavky na stav záznamu, povinné údaje a `rowVersion` platí pro všechny role. Profil, přihlášení, hlasování, zařízení a osobní notifikace se vztahují k aktuálně přihlášenému účtu.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Funkční požadavky
|
## 3. Funkční požadavky
|
||||||
@@ -125,7 +122,7 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
|||||||
| FR-10 | Uživatel nahlásí závadu: název, popis, kategorie (typ), budova a upřesnění místa. |
|
| FR-10 | Uživatel nahlásí závadu: název, popis, kategorie (typ), budova a upřesnění místa. |
|
||||||
| FR-11 | K hlášení lze při vytvoření i později v průběhu komunikace přiložit fotografii nebo jiný soubor (JPG, PNG, HEIC, PDF, DOCX; max. 10 MB/soubor, max. 5 souborů najednou). |
|
| FR-11 | K hlášení lze při vytvoření i později v průběhu komunikace přiložit fotografii nebo jiný soubor (JPG, PNG, HEIC, PDF, DOCX; max. 10 MB/soubor, max. 5 souborů najednou). |
|
||||||
| FR-12 | Závada prochází stavy *Přijata → Přiřazena → V řešení → Čeká na ověření → Vyřešena*, případně *Zamítnuta* (kap. 6). Nepovolené přechody server odmítne. |
|
| FR-12 | Závada prochází stavy *Přijata → Přiřazena → V řešení → Čeká na ověření → Vyřešena*, případně *Zamítnuta* (kap. 6). Nepovolené přechody server odmítne. |
|
||||||
| FR-13 | Vedení a administrátor přiřazují závadu odpovědné osobě; u každého řešitele vidí počet jeho otevřených závad. |
|
| FR-13 | Vedení přiřazuje závadu odpovědné osobě (správci budov); u každého správce vidí počet jeho otevřených závad. |
|
||||||
| FR-14 | Řešitel může závadu zamítnout s povinným uvedením důvodu. |
|
| FR-14 | Řešitel může závadu zamítnout s povinným uvedením důvodu. |
|
||||||
| FR-15 | Hlásič potvrdí vyřešení, nebo závadu znovu otevře (s povinným důvodem) → stav *V řešení*. |
|
| FR-15 | Hlásič potvrdí vyřešení, nebo závadu znovu otevře (s povinným důvodem) → stav *V řešení*. |
|
||||||
| FR-16 | Hlásič a řešitel si u závady vyměňují komentáře; protistrana je o novém komentáři informována. |
|
| FR-16 | Hlásič a řešitel si u závady vyměňují komentáře; protistrana je o novém komentáři informována. |
|
||||||
@@ -137,13 +134,13 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
|||||||
| FR-20 | Každý uživatel podá návrh: název, popis, oblast (studium, služby, prostředí, ostatní). |
|
| FR-20 | Každý uživatel podá návrh: název, popis, oblast (studium, služby, prostředí, ostatní). |
|
||||||
| FR-21 | Uživatel hlasuje pro/proti návrhu jiného uživatele; jeden hlas na návrh, hlas lze změnit či zrušit; autor pro vlastní návrh hlasovat nemůže. |
|
| FR-21 | Uživatel hlasuje pro/proti návrhu jiného uživatele; jeden hlas na návrh, hlas lze změnit či zrušit; autor pro vlastní návrh hlasovat nemůže. |
|
||||||
| FR-22 | Seznam návrhů lze řadit podle podpory (skóre) a data a filtrovat podle stavu a oblasti. |
|
| FR-22 | Seznam návrhů lze řadit podle podpory (skóre) a data a filtrovat podle stavu a oblasti. |
|
||||||
| FR-23 | Vedení a administrátor hodnotí návrhy, mění jejich stav (*V posouzení, Přijat, Zamítnut, Realizován*) a připojují vyjádření. |
|
| FR-23 | Vedení hodnotí návrhy – mění stav (*V posouzení, Přijat, Zamítnut, Realizován*) a připojuje vyjádření. |
|
||||||
|
|
||||||
### Správa, přehledy, notifikace
|
### Správa, přehledy, notifikace
|
||||||
| ID | Požadavek |
|
| ID | Požadavek |
|
||||||
|---|---|
|
|---|---|
|
||||||
| FR-30 | Centrální přehled závad a návrhů s filtrováním podle typu (kategorie), stavu, lokality (budovy), řešitele a data; stránkování a řazení. |
|
| FR-30 | Centrální přehled závad a návrhů s filtrováním podle typu (kategorie), stavu, lokality (budovy), řešitele a data; stránkování a řazení. |
|
||||||
| FR-31 | Statistiky pro vedení a administrátory zahrnují počty závad podle stavu, kategorie či budovy, průměrnou dobu do přiřazení a uzavření, vytížení řešitelů a nejpodporovanější návrhy za zvolené období. |
|
| FR-31 | Statistiky pro vedení: počet závad podle stavu / kategorie / budovy, průměrná doba do přiřazení a do uzavření, vytížení řešitelů, nejpodporovanější návrhy, vše za zvolené období. |
|
||||||
| FR-32 | Notifikace v aplikaci (seznam, počet nepřečtených), e-mailem a push notifikací v mobilní aplikaci (kap. 8). |
|
| FR-32 | Notifikace v aplikaci (seznam, počet nepřečtených), e-mailem a push notifikací v mobilní aplikaci (kap. 8). |
|
||||||
| FR-33 | Nedoručené e-maily a push notifikace se automaticky opakují; trvale nedoručené vidí administrátor a může je odeslat znovu. |
|
| FR-33 | Nedoručené e-maily a push notifikace se automaticky opakují; trvale nedoručené vidí administrátor a může je odeslat znovu. |
|
||||||
|
|
||||||
@@ -156,7 +153,7 @@ Pravidla „🔸“ nelze vyjádřit jen rolí – jsou to **pravidla nad konkr
|
|||||||
| NFR-01 | Bezpečnost | Komunikace výhradně přes HTTPS; hesla hashovaná; JWT s krátkou platností; citlivé údaje šifrované (kap. 10). |
|
| NFR-01 | Bezpečnost | Komunikace výhradně přes HTTPS; hesla hashovaná; JWT s krátkou platností; citlivé údaje šifrované (kap. 10). |
|
||||||
| NFR-02 | Konzistence | Pravidla životního cyklu a oprávnění jsou pouze na serveru; klienti je jen zobrazují. |
|
| NFR-02 | Konzistence | Pravidla životního cyklu a oprávnění jsou pouze na serveru; klienti je jen zobrazují. |
|
||||||
| NFR-03 | Souběžnost | Změny stavu závady chráněny optimistickým zamykáním (`row_version`) – dvě souběžné změny nevedou k nekonzistentnímu stavu. |
|
| NFR-03 | Souběžnost | Změny stavu závady chráněny optimistickým zamykáním (`row_version`) – dvě souběžné změny nevedou k nekonzistentnímu stavu. |
|
||||||
| NFR-04 | Dokumentace API | Swagger UI na `/swagger` pro administrátory přihlášené na webu. Volání API ze Swaggeru se autorizují access tokenem. |
|
| NFR-04 | Dokumentace API | Swagger UI (OpenAPI) dostupné na `/swagger`, včetně autorizace tokenem. |
|
||||||
| NFR-05 | Výkon | Seznamy stránkované (výchozí 20 záznamů), indexy pro všechny filtry v přehledu. |
|
| NFR-05 | Výkon | Seznamy stránkované (výchozí 20 záznamů), indexy pro všechny filtry v přehledu. |
|
||||||
| NFR-06 | Použitelnost | Responzivní web (desktop i mobil), mobilní aplikace Android 8.0+ (API 26). Rozhraní v češtině. |
|
| NFR-06 | Použitelnost | Responzivní web (desktop i mobil), mobilní aplikace Android 8.0+ (API 26). Rozhraní v češtině. |
|
||||||
| NFR-07 | Nasaditelnost | Celý systém spustitelný příkazem `docker compose up`. |
|
| NFR-07 | Nasaditelnost | Celý systém spustitelný příkazem `docker compose up`. |
|
||||||
@@ -201,7 +198,7 @@ flowchart LR
|
|||||||
S --- UC1 & UC2 & UC3 & UC4 & UC10 & UC11
|
S --- UC1 & UC2 & UC3 & UC4 & UC10 & UC11
|
||||||
F --- UC3 & UC6 & UC7 & UC20
|
F --- UC3 & UC6 & UC7 & UC20
|
||||||
M --- UC5 & UC7 & UC12 & UC20 & UC21
|
M --- UC5 & UC7 & UC12 & UC20 & UC21
|
||||||
A --- UC5 & UC6 & UC7 & UC12 & UC20 & UC21 & UC22 & UC23
|
A --- UC22 & UC23
|
||||||
```
|
```
|
||||||
|
|
||||||
*Správce budov, vedení i administrátor mají navíc všechny případy užití studenta (hlášení závad, návrhy, hlasování).*
|
*Správce budov, vedení i administrátor mají navíc všechny případy užití studenta (hlášení závad, návrhy, hlasování).*
|
||||||
@@ -232,16 +229,16 @@ stateDiagram-v2
|
|||||||
state "Zamítnuta" as REJECTED
|
state "Zamítnuta" as REJECTED
|
||||||
|
|
||||||
[*] --> RECEIVED : hlásič vytvoří
|
[*] --> RECEIVED : hlásič vytvoří
|
||||||
RECEIVED --> ASSIGNED : vedení nebo admin přiřadí řešitele
|
RECEIVED --> ASSIGNED : vedení přiřadí řešitele
|
||||||
ASSIGNED --> ASSIGNED : vedení nebo admin přeřadí
|
ASSIGNED --> ASSIGNED : vedení přeřadí
|
||||||
ASSIGNED --> IN_PROGRESS : řešitel nebo admin zahájí
|
ASSIGNED --> IN_PROGRESS : řešitel zahájí
|
||||||
IN_PROGRESS --> ASSIGNED : vedení nebo admin přeřadí
|
IN_PROGRESS --> ASSIGNED : vedení přeřadí
|
||||||
IN_PROGRESS --> PENDING_VERIFICATION : řešitel nebo admin předá k ověření
|
IN_PROGRESS --> PENDING_VERIFICATION : řešitel předá k ověření
|
||||||
PENDING_VERIFICATION --> RESOLVED : hlásič nebo admin potvrdí
|
PENDING_VERIFICATION --> RESOLVED : hlásič potvrdí
|
||||||
PENDING_VERIFICATION --> IN_PROGRESS : hlásič nebo admin znovu otevře
|
PENDING_VERIFICATION --> IN_PROGRESS : hlásič znovu otevře
|
||||||
RECEIVED --> REJECTED : vedení nebo admin zamítne
|
RECEIVED --> REJECTED : vedení zamítne
|
||||||
ASSIGNED --> REJECTED : řešitel nebo admin zamítne
|
ASSIGNED --> REJECTED : řešitel zamítne
|
||||||
IN_PROGRESS --> REJECTED : řešitel nebo admin zamítne
|
IN_PROGRESS --> REJECTED : řešitel zamítne
|
||||||
RESOLVED --> [*]
|
RESOLVED --> [*]
|
||||||
REJECTED --> [*]
|
REJECTED --> [*]
|
||||||
```
|
```
|
||||||
@@ -251,14 +248,14 @@ stateDiagram-v2
|
|||||||
| # | Z → Do | Kdo smí | Povinné údaje | Vedlejší efekty | Notifikace |
|
| # | Z → Do | Kdo smí | Povinné údaje | Vedlejší efekty | Notifikace |
|
||||||
|---|---|---|---|---|---|
|
|---|---|---|---|---|---|
|
||||||
| T1 | — → **Přijata** | každý přihlášený (stává se hlásičem) | název, popis, kategorie | událost `CREATED` | vedení: `ISSUE_CREATED` |
|
| T1 | — → **Přijata** | každý přihlášený (stává se hlásičem) | název, popis, kategorie | událost `CREATED` | vedení: `ISSUE_CREATED` |
|
||||||
| T2 | Přijata → **Přiřazena** | vedení / admin | řešitel (správce budov / vedení / admin) | `assignee_id`, událost `ASSIGNED` | řešitel: `ISSUE_ASSIGNED`; hlásič: změna stavu |
|
| T2 | Přijata → **Přiřazena** | vedení | řešitel (role správce budov / vedení) | `assignee_id`, událost `ASSIGNED` | řešitel: `ISSUE_ASSIGNED`; hlásič: změna stavu |
|
||||||
| T3 | Přiřazena / V řešení → **Přiřazena** (přeřazení) | vedení / admin | nový řešitel | změna `assignee_id`, událost `ASSIGNED` | `ISSUE_ASSIGNED` novému řešiteli, `ISSUE_STATUS_CHANGED` hlásiči při změně stavu, pokud hlásič není novým řešitelem |
|
| T3 | Přiřazena / V řešení → **Přiřazena** (přeřazení) | vedení | nový řešitel | změna `assignee_id`, událost `ASSIGNED` | nový řešitel: `ISSUE_ASSIGNED` |
|
||||||
| T4 | Přiřazena → **V řešení** | přiřazený řešitel / admin | — | událost `STATUS_CHANGED` | hlásič |
|
| T4 | Přiřazena → **V řešení** | přiřazený řešitel | — | událost `STATUS_CHANGED` | hlásič |
|
||||||
| T5 | V řešení → **Čeká na ověření** | přiřazený řešitel / admin | volitelná poznámka | událost `STATUS_CHANGED` | hlásič |
|
| T5 | V řešení → **Čeká na ověření** | přiřazený řešitel | volitelná poznámka | událost `STATUS_CHANGED` | hlásič |
|
||||||
| T6 | Čeká na ověření → **Vyřešena** | hlásič / admin | — | událost `STATUS_CHANGED` (= čas uzavření) | řešitel |
|
| T6 | Čeká na ověření → **Vyřešena** | hlásič | — | událost `STATUS_CHANGED` (= čas uzavření) | řešitel |
|
||||||
| T7 | Čeká na ověření → **V řešení** | hlásič / admin | důvod znovuotevření | událost s důvodem v `note` | řešitel: `ISSUE_REOPENED` |
|
| T7 | Čeká na ověření → **V řešení** | hlásič | důvod znovuotevření | událost s důvodem v `note` | řešitel: `ISSUE_REOPENED` |
|
||||||
| T8 | Přiřazena / V řešení → **Zamítnuta** | přiřazený řešitel / admin | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič |
|
| T8 | Přiřazena / V řešení → **Zamítnuta** | přiřazený řešitel | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič |
|
||||||
| T9 | Přijata → **Zamítnuta** | vedení / admin | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič |
|
| T9 | Přijata → **Zamítnuta** | vedení | důvod zamítnutí | událost s důvodem v `note` (= čas uzavření) | hlásič |
|
||||||
|
|
||||||
**Obecná pravidla**
|
**Obecná pravidla**
|
||||||
|
|
||||||
@@ -303,19 +300,19 @@ stateDiagram-v2
|
|||||||
state "Realizován" as IMPLEMENTED
|
state "Realizován" as IMPLEMENTED
|
||||||
|
|
||||||
[*] --> SUBMITTED : uživatel podá
|
[*] --> SUBMITTED : uživatel podá
|
||||||
SUBMITTED --> UNDER_REVIEW : vedení nebo admin
|
SUBMITTED --> UNDER_REVIEW : vedení
|
||||||
SUBMITTED --> ACCEPTED : vedení nebo admin
|
SUBMITTED --> ACCEPTED : vedení
|
||||||
SUBMITTED --> REJECTED : vedení nebo admin (s vyjádřením)
|
SUBMITTED --> REJECTED : vedení (s vyjádřením)
|
||||||
UNDER_REVIEW --> ACCEPTED : vedení nebo admin
|
UNDER_REVIEW --> ACCEPTED : vedení
|
||||||
UNDER_REVIEW --> REJECTED : vedení nebo admin (s vyjádřením)
|
UNDER_REVIEW --> REJECTED : vedení (s vyjádřením)
|
||||||
ACCEPTED --> IMPLEMENTED : vedení nebo admin
|
ACCEPTED --> IMPLEMENTED : vedení
|
||||||
REJECTED --> [*]
|
REJECTED --> [*]
|
||||||
IMPLEMENTED --> [*]
|
IMPLEMENTED --> [*]
|
||||||
```
|
```
|
||||||
|
|
||||||
- Stavy může měnit vedení školy nebo administrátor. Zamítnutí vyžaduje vyjádření, u ostatních přechodů je volitelné. Vyjádření se ukládá do `note` příslušné události.
|
- Stavy mění pouze **vedení školy**; zamítnutí vyžaduje vyjádření, u ostatních je volitelné. Vyjádření se ukládá do `note` příslušné události.
|
||||||
- Autor nebo administrátor může návrh upravit, dokud je ve stavu *Podán* (událost `UPDATED`).
|
- Autor může návrh upravit, dokud je ve stavu *Podán* (událost `UPDATED`).
|
||||||
- Každá změna se zapisuje do `proposal_event`. Při změně stavu dostane autor notifikaci, pokud stav nezměnil sám.
|
- Každá změna se zapisuje do `proposal_event`, autor dostane notifikaci.
|
||||||
|
|
||||||
### 7.2 Pravidla hlasování
|
### 7.2 Pravidla hlasování
|
||||||
|
|
||||||
@@ -410,8 +407,8 @@ flowchart TB
|
|||||||
|
|
||||||
subgraph Docker["Docker Compose"]
|
subgraph Docker["Docker Compose"]
|
||||||
PROXY[Reverzní proxy nginx<br/>HTTPS / TLS]
|
PROXY[Reverzní proxy nginx<br/>HTTPS / TLS]
|
||||||
WEB[Webová aplikace<br/>ASP.NET Core MVC<br/>+ Swagger UI]
|
WEB[Webová aplikace<br/>ASP.NET Core MVC]
|
||||||
API[Backend REST API<br/>ASP.NET Core Web API<br/>+ OpenAPI]
|
API[Backend REST API<br/>ASP.NET Core Web API<br/>+ Swagger]
|
||||||
DB[(MariaDB 11)]
|
DB[(MariaDB 11)]
|
||||||
FILES[[Volume: přílohy]]
|
FILES[[Volume: přílohy]]
|
||||||
end
|
end
|
||||||
@@ -422,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/*" --> API
|
PROXY -- "/api/*, /swagger" --> API
|
||||||
WEB -- "REST, JWT" --> API
|
WEB -- "REST, JWT" --> API
|
||||||
API --> DB
|
API --> DB
|
||||||
API --> FILES
|
API --> FILES
|
||||||
@@ -447,8 +444,8 @@ Fyzické nasazení (sítě, porty, úložiště, tajné klíče) popisuje kapito
|
|||||||
|
|
||||||
### 9.3 Autorizace
|
### 9.3 Autorizace
|
||||||
|
|
||||||
1. **Podle role** – atributy jako `[Authorize(Roles = Roles.ManagementOrAdmin)]` a autorizační politiky. Role je v JWT jako claim `role`.
|
1. **Podle role** – atribut `[Authorize(Roles = "MANAGEMENT")]` / politiky (např. `CanAssignIssues`, `CanEvaluateProposals`, `IsAdmin`). Role je v JWT jako claim `role`.
|
||||||
2. **Nad konkrétním záznamem** – aplikační a doménová vrstva ověřují oprávnění k akci. U závad a úprav návrhů může administrátor jednat i u cizích záznamů. Porušení → 403.
|
2. **Nad konkrétním záznamem** – v aplikační vrstvě (`IssueAuthorizationService`): „je aktuální uživatel hlásičem / přiřazeným řešitelem této závady?“, „je autorem návrhu?“. Porušení → 403.
|
||||||
3. **Podle stavu** – stavový automat v doméně. Porušení → 409.
|
3. **Podle stavu** – stavový automat v doméně. Porušení → 409.
|
||||||
|
|
||||||
Detail závady vrací pole `allowedActions` (např. `["START_WORK", "REJECT", "COMMENT"]`), podle kterého klienti zobrazují ovládací prvky – logika tak není duplikována v klientech.
|
Detail závady vrací pole `allowedActions` (např. `["START_WORK", "REJECT", "COMMENT"]`), podle kterého klienti zobrazují ovládací prvky – logika tak není duplikována v klientech.
|
||||||
@@ -618,7 +615,7 @@ SET revoked_at = UTC_TIMESTAMP(6), revoke_reason = 'USED'
|
|||||||
WHERE jti = ? AND token_type = 'REFRESH' AND revoked_at IS NULL;
|
WHERE jti = ? AND token_type = 'REFRESH' AND revoked_at IS NULL;
|
||||||
```
|
```
|
||||||
|
|
||||||
- **Změněn 1 řádek** → token se používá poprvé, server uloží nový pár tokenů ve stejné databázové transakci.
|
- **Změněn 1 řádek** → token se používá poprvé, server vydá nový pár tokenů.
|
||||||
- **Změněno 0 řádků** → token už byl použitý nebo zneplatněný. U refresh tokenu to znamená, že ho zneužil někdo jiný. Server zneplatní všechny tokeny uživatele (`REUSE_DETECTED`) a vrátí 401.
|
- **Změněno 0 řádků** → token už byl použitý nebo zneplatněný. U refresh tokenu to znamená, že ho zneužil někdo jiný. Server zneplatní všechny tokeny uživatele (`REUSE_DETECTED`) a vrátí 401.
|
||||||
|
|
||||||
Ze dvou současných požadavků se stejným tokenem vždy uspěje jen jeden. Klienti (mobil i web) proto musí obnovu tokenů provádět vždy jen jednou současně. Jinak by souběžné obnovy vyhodnotil server jako krádež.
|
Ze dvou současných požadavků se stejným tokenem vždy uspěje jen jeden. Klienti (mobil i web) proto musí obnovu tokenů provádět vždy jen jednou současně. Jinak by souběžné obnovy vyhodnotil server jako krádež.
|
||||||
@@ -650,7 +647,7 @@ Aplikační API má základní cestu **`/api/v1`**. Připojte tento prefix před
|
|||||||
|
|
||||||
Čí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.
|
Číslo v URL je hlavní verze API. Zpětně kompatibilní rozšíření patří do stávající verze. Při nekompatibilní změně vznikne nová cesta (např. `/api/v2`) a samostatný OpenAPI dokument. Během přechodu klientů poběží obě verze souběžně. Před ukončením podpory starší verze se oznámí termín a zdokumentuje přechod.
|
||||||
|
|
||||||
Swagger UI je na webu na `/swagger`. UI i jeho OpenAPI dokument na `/swagger/v1/swagger.json` vyžadují administrátorskou relaci. Web načítá dokument z `GET /api/v1/admin/openapi/v1.json` s access tokenem administrátora. Provozní kontrola API je na `GET /health`.
|
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 |
|
||||||
@@ -668,21 +665,21 @@ Swagger UI je na webu na `/swagger`. UI i jeho OpenAPI dokument na `/swagger/v1/
|
|||||||
### 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=newest\|oldest`. Student a vyučující vidí 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), JSON do 1 MiB nebo multipart s poli hlášení a soubory v poli `files` |
|
| POST | `/issues` | přihlášený | Vytvoření hlášení (T1), JSON do 1 MiB nebo multipart s poli hlášení a soubory v poli `files` |
|
||||||
| GET | `/issues/{id}` | účastník / správce / vedení / admin | Detail vč. `allowedActions` a `rowVersion` |
|
| GET | `/issues/{id}` | účastník / správce / vedení | Detail vč. `allowedActions` a `rowVersion` |
|
||||||
| PUT | `/issues/{id}` | hlásič / admin | Úprava ve stavu Přijata s `rowVersion` |
|
| PUT | `/issues/{id}` | hlásič | Úprava ve stavu Přijata s `rowVersion` |
|
||||||
| POST | `/issues/{id}/assign` | vedení / admin | `{ assigneeId, priority?, rowVersion }` (T2, T3) |
|
| POST | `/issues/{id}/assign` | vedení | `{ assigneeId, priority?, rowVersion }` (T2, T3) |
|
||||||
| POST | `/issues/{id}/start` | řešitel / admin | `{ rowVersion }` (T4) |
|
| POST | `/issues/{id}/start` | řešitel | `{ rowVersion }` (T4) |
|
||||||
| POST | `/issues/{id}/submit-for-verification` | řešitel / admin | `{ rowVersion, note? }` (T5) |
|
| POST | `/issues/{id}/submit-for-verification` | řešitel | `{ rowVersion, note? }` (T5) |
|
||||||
| POST | `/issues/{id}/confirm` | hlásič / admin | `{ rowVersion }` (T6) |
|
| POST | `/issues/{id}/confirm` | hlásič | `{ rowVersion }` (T6) |
|
||||||
| POST | `/issues/{id}/reopen` | hlásič / admin | `{ rowVersion, reason }` (T7) |
|
| POST | `/issues/{id}/reopen` | hlásič | `{ rowVersion, reason }` (T7) |
|
||||||
| POST | `/issues/{id}/reject` | řešitel / vedení / admin | `{ rowVersion, 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 / admin | `{ 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 / admin | `multipart/form-data`, 1–5 souborů v poli `files` |
|
| 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í / admin | 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`.
|
Po přidání komentáře nebo příloh klient znovu načte detail, aby získal aktuální `rowVersion`.
|
||||||
@@ -693,10 +690,10 @@ Po přidání komentáře nebo příloh klient znovu načte detail, aby získal
|
|||||||
| GET | `/proposals` | přihlášený | Filtry `status`, `categoryId`, `authorId`, `q`; `sort=score\|newest`; obsahuje skóre a můj hlas |
|
| GET | `/proposals` | přihlášený | Filtry `status`, `categoryId`, `authorId`, `q`; `sort=score\|newest`; obsahuje skóre a můj hlas |
|
||||||
| POST | `/proposals` | přihlášený | Podání návrhu |
|
| POST | `/proposals` | přihlášený | Podání návrhu |
|
||||||
| GET | `/proposals/{id}` | přihlášený | Detail vč. událostí a vyjádření vedení |
|
| GET | `/proposals/{id}` | přihlášený | Detail vč. událostí a vyjádření vedení |
|
||||||
| PUT | `/proposals/{id}` | autor / admin | Úprava ve stavu Podán |
|
| PUT | `/proposals/{id}` | autor | Úprava ve stavu Podán |
|
||||||
| PUT | `/proposals/{id}/vote` | přihlášený (ne autor) | `{ value: 1 \| -1 }` – vytvoření nebo změna hlasu |
|
| PUT | `/proposals/{id}/vote` | přihlášený (ne autor) | `{ value: 1 \| -1 }` – vytvoření nebo změna hlasu |
|
||||||
| DELETE | `/proposals/{id}/vote` | přihlášený | Zrušení hlasu |
|
| DELETE | `/proposals/{id}/vote` | přihlášený | Zrušení hlasu |
|
||||||
| POST | `/proposals/{id}/status` | vedení / admin | `{ status, note? }` |
|
| POST | `/proposals/{id}/status` | vedení | `{ status, note? }` |
|
||||||
|
|
||||||
### Notifikace a zařízení
|
### Notifikace a zařízení
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
@@ -711,12 +708,12 @@ Po přidání komentáře nebo příloh klient znovu načte detail, aby získal
|
|||||||
### Statistiky
|
### Statistiky
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| GET | `/statistics/overview?from=&to=` | vedení / admin | Souhrnné KPI: počty podle stavu, průměrná doba do přiřazení a do uzavření |
|
| GET | `/statistics/overview?from=&to=` | vedení | Souhrnné KPI: počty podle stavu, průměrná doba do přiřazení a do uzavření |
|
||||||
| GET | `/statistics/issues/by-category` | vedení / admin | Počty a průměrná doba řešení podle kategorie |
|
| GET | `/statistics/issues/by-category` | vedení | Počty a průměrná doba řešení podle kategorie |
|
||||||
| GET | `/statistics/issues/by-building` | vedení / admin | Podle budovy |
|
| GET | `/statistics/issues/by-building` | vedení | Podle budovy |
|
||||||
| GET | `/statistics/issues/by-assignee` | vedení / admin | Vytížení řešitelů (otevřené / uzavřené) |
|
| GET | `/statistics/issues/by-assignee` | vedení | Vytížení řešitelů (otevřené / uzavřené) |
|
||||||
| GET | `/statistics/issues/trend?granularity=month` | vedení / admin | Nové vs. uzavřené závady v čase |
|
| GET | `/statistics/issues/trend?granularity=month` | vedení | Nové vs. uzavřené závady v čase |
|
||||||
| GET | `/statistics/proposals/top?limit=10` | vedení / admin | Nejpodporovanější návrhy |
|
| GET | `/statistics/proposals/top?limit=10` | vedení | Nejpodporovanější návrhy |
|
||||||
|
|
||||||
### Číselníky a administrace
|
### Číselníky a administrace
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
@@ -979,7 +976,7 @@ V první verzi byla tabulka uživatelů „chobotnice“: vedlo na ni 17 cizích
|
|||||||
- **Normalizace (3NF)**: číselníky jsou v samostatných tabulkách. Časy životního cyklu se neukládají redundantně, ale odvozují se z událostí.
|
- **Normalizace (3NF)**: číselníky jsou v samostatných tabulkách. Časy životního cyklu se neukládají redundantně, ale odvozují se z událostí.
|
||||||
- **Stavy jako text + CHECK** místo nativního `ENUM`: hodnoty jsou v DB čitelné, rozšíření je snadné a v EF Core se mapují na C# `enum` přes `HasConversion<string>()`.
|
- **Stavy jako text + CHECK** místo nativního `ENUM`: hodnoty jsou v DB čitelné, rozšíření je snadné a v EF Core se mapují na C# `enum` přes `HasConversion<string>()`.
|
||||||
- **Integritní omezení v DB** jako druhá linie obrany za aplikační logikou. Zamítnutí i znovuotevření musí mít důvod. Závada ve stavu *Přiřazena / V řešení / Čeká na ověření* musí mít řešitele. Událost `CREATED` musí začínat výchozím stavem, komentář (`COMMENTED`) musí mít text a nesmí měnit stav. Hlas je jen `+1`/`-1`, příloha má max. 10 MB a odeslané doručení musí mít `sent_at`. Notifikace typu `ISSUE_*` musí odkazovat na závadu, typu `PROPOSAL_*` na návrh.
|
- **Integritní omezení v DB** jako druhá linie obrany za aplikační logikou. Zamítnutí i znovuotevření musí mít důvod. Závada ve stavu *Přiřazena / V řešení / Čeká na ověření* musí mít řešitele. Událost `CREATED` musí začínat výchozím stavem, komentář (`COMMENTED`) musí mít text a nesmí měnit stav. Hlas je jen `+1`/`-1`, příloha má max. 10 MB a odeslané doručení musí mít `sent_at`. Notifikace typu `ISSUE_*` musí odkazovat na závadu, typu `PROPOSAL_*` na návrh.
|
||||||
- **Pravidla vyžadující více tabulek** (autor nehlasuje pro svůj návrh, řešitel musí mít roli správce budov, vedení nebo administrátora) hlídá aplikační vrstva. V DB by vyžadovala triggery a logika by se rozdělila na dvě místa.
|
- **Pravidla vyžadující více tabulek** (autor nehlasuje pro svůj návrh, řešitel musí mít roli správce budov / vedení) hlídá aplikační vrstva. V DB by vyžadovala triggery a logika by se rozdělila na dvě místa.
|
||||||
- **Optimistické zamykání**: `issue.row_version` (EF Core concurrency token).
|
- **Optimistické zamykání**: `issue.row_version` (EF Core concurrency token).
|
||||||
- **Mazání**: uživatelé, závady, návrhy a číselníky se nemažou. Uživatelé a číselníky se deaktivují (`is_active`). `ON DELETE CASCADE` je jen u čistě závislých dat.
|
- **Mazání**: uživatelé, závady, návrhy a číselníky se nemažou. Uživatelé a číselníky se deaktivují (`is_active`). `ON DELETE CASCADE` je jen u čistě závislých dat.
|
||||||
- **Časy v UTC**, `DATETIME(6)`; převod do místního času dělá klient.
|
- **Časy v UTC**, `DATETIME(6)`; převod do místního času dělá klient.
|
||||||
@@ -1038,13 +1035,13 @@ ORDER BY n.created_at DESC;
|
|||||||
| Nástěnka (moje otevřená hlášení, poslední notifikace, top návrhy) | ✅ | ✅ | všichni |
|
| Nástěnka (moje otevřená hlášení, poslední notifikace, top návrhy) | ✅ | ✅ | všichni |
|
||||||
| Nové hlášení závady (formulář + přílohy / fotoaparát) | ✅ | ✅ | všichni |
|
| Nové hlášení závady (formulář + přílohy / fotoaparát) | ✅ | ✅ | všichni |
|
||||||
| Moje hlášení (seznam se stavem) | ✅ | ✅ | všichni |
|
| Moje hlášení (seznam se stavem) | ✅ | ✅ | všichni |
|
||||||
| Detail závady (stav, časová osa, akce podle `allowedActions`, komentáře, přílohy) | ✅ | ✅ | účastníci, správce, vedení, admin |
|
| Detail závady (stav, časová osa, akce podle `allowedActions`, komentáře, přílohy) | ✅ | ✅ | účastníci, správce, vedení |
|
||||||
| Přiřazené závady (pracovní fronta řešitele) | ✅ | ✅ | správce budov |
|
| Přiřazené závady (pracovní fronta řešitele) | ✅ | ✅ | správce budov |
|
||||||
| Centrální přehled závad (tabulka, filtry, hromadný přehled) | ✅ | — | správce budov, vedení, admin |
|
| Centrální přehled závad (tabulka, filtry, hromadný přehled) | ✅ | — | správce budov, vedení |
|
||||||
| Návrhy – seznam (řazení podle skóre, hlasování přímo v seznamu) | ✅ | ✅ | všichni |
|
| Návrhy – seznam (řazení podle skóre, hlasování přímo v seznamu) | ✅ | ✅ | všichni |
|
||||||
| Detail návrhu / nový návrh | ✅ | ✅ | všichni |
|
| Detail návrhu / nový návrh | ✅ | ✅ | všichni |
|
||||||
| Hodnocení návrhů (fronta podaných návrhů) | ✅ | — | vedení, admin |
|
| Hodnocení návrhů (fronta podaných návrhů) | ✅ | — | vedení |
|
||||||
| Statistiky (KPI dlaždice, grafy, filtr období) | ✅ | — | vedení, admin |
|
| Statistiky (KPI dlaždice, grafy, filtr období) | ✅ | — | vedení |
|
||||||
| Notifikace | ✅ | ✅ | všichni |
|
| Notifikace | ✅ | ✅ | všichni |
|
||||||
| Profil a nastavení notifikací | ✅ | ✅ | všichni |
|
| Profil a nastavení notifikací | ✅ | ✅ | všichni |
|
||||||
| Správa uživatelů a rolí | ✅ | — | admin |
|
| Správa uživatelů a rolí | ✅ | — | admin |
|
||||||
@@ -1132,7 +1129,7 @@ flowchart LR
|
|||||||
BROWSER -- "HTTPS 443" --> PROXY
|
BROWSER -- "HTTPS 443" --> PROXY
|
||||||
MOBILE -- "HTTPS 443 /api/v1/*" --> PROXY
|
MOBILE -- "HTTPS 443 /api/v1/*" --> PROXY
|
||||||
PROXY -- "HTTP 8080 /" --> WEB
|
PROXY -- "HTTP 8080 /" --> WEB
|
||||||
PROXY -- "HTTP 8080 /api/*" --> 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
|
||||||
@@ -1160,8 +1157,8 @@ flowchart LR
|
|||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| prohlížeč | proxy | HTTPS 443 (HTTP 80 → přesměrování) | internet | webová aplikace |
|
| prohlížeč | proxy | HTTPS 443 (HTTP 80 → přesměrování) | internet | webová aplikace |
|
||||||
| mobil | proxy | HTTPS 443 | internet | REST API |
|
| mobil | proxy | HTTPS 443 | internet | REST API |
|
||||||
| proxy | web | HTTP 8080 | frontend | stránky (`/`), administrátorské Swagger UI (`/swagger`) |
|
| proxy | web | HTTP 8080 | frontend | stránky (`/`) |
|
||||||
| proxy | api | HTTP 8080 | frontend | `/api/*` |
|
| proxy | api | HTTP 8080 | frontend | `/api/*`, `/swagger` |
|
||||||
| web | api | HTTP 8080 (`http://api:8080/api/v1/`) | 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` |
|
||||||
@@ -1174,8 +1171,8 @@ 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 51 MiB (5 příloh × 10 MiB a režie multipart) |
|
| `proxy` | `nginx` | frontend | **80, 443 publikované** | certifikáty | TLS (vývoj: `mkcert`, produkce: Let's Encrypt), HSTS, limit velikosti požadavku 51 MiB (5 příloh × 10 MiB a režie multipart) |
|
||||||
| `web` | vlastní (`dotnet/aspnet`) | frontend | interně 8080 | `web-keys` | administrátorské Swagger UI na `/swagger`, klíče Data Protection pro šifrované cookie |
|
| `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` | OpenAPI pro administrátory, `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čí |
|
||||||
| `db` | `mariadb:11.4` | backend | interně 3306 | `db-data` | při prvním startu vytvoří DB účty skriptem z `deploy/db-init/` |
|
| `db` | `mariadb:11.4` | backend | interně 3306 | `db-data` | při prvním startu vytvoří DB účty skriptem z `deploy/db-init/` |
|
||||||
| `mailpit` | `axllent/mailpit` | frontend | 8025 (jen vývoj) | — | zachytává e-maily, v produkci se nespouští |
|
| `mailpit` | `axllent/mailpit` | frontend | 8025 (jen vývoj) | — | zachytává e-maily, v produkci se nespouští |
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# NTBug pro Android
|
||||||
|
|
||||||
|
Nativní český klient univerzitního helpdesku pro Android 8.0+ (API 26), napsaný v Kotlinu a Jetpack Compose / Material 3. Aplikace podporuje světlý i tmavý motiv, systémové okraje, posouvání formulářů a klávesnici.
|
||||||
|
|
||||||
|
## Spuštění
|
||||||
|
|
||||||
|
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.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`.
|
||||||
|
4. Spusťte modul `app` na emulátoru nebo připojeném telefonu.
|
||||||
|
|
||||||
|
Příkazová řádka ve Windows, ze složky `mobile`:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\gradlew.bat :app:assembleDebug
|
||||||
|
.\gradlew.bat :app:testDebugUnitTest :app:lintDebug
|
||||||
|
# Pro spuštěný emulátor nebo připojené testovací zařízení:
|
||||||
|
.\gradlew.bat :app:connectedDebugAndroidTest
|
||||||
|
```
|
||||||
|
|
||||||
|
Na Linuxu/macOS použijte `sh ./gradlew`. Debug APK se vytvoří v `app/build/outputs/apk/debug/app-debug.apk`. Release sestavení vyžaduje vlastní podpisový klíč; klíče ani hesla do repozitáře nepatří.
|
||||||
|
|
||||||
|
### 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.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).
|
||||||
|
|
||||||
|
## Skutečný server a ukázka
|
||||||
|
|
||||||
|
**Přihlásit se** používá REST API. Nejprve spusťte backend podle hlavního README. Přes **Nastavení serveru** zadejte adresu:
|
||||||
|
|
||||||
|
| Prostředí | Příklad |
|
||||||
|
|---|---|
|
||||||
|
| Android emulátor, backend na stejném počítači | `http://10.0.2.2:8080/` |
|
||||||
|
| 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) |
|
||||||
|
| Nasazený server | `https://helpdesk.example.cz/` |
|
||||||
|
|
||||||
|
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é.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Rozsah a stav API
|
||||||
|
|
||||||
|
| Funkce | Mobilní klient | Backend v tomto repozitáři |
|
||||||
|
|---|---|---|
|
||||||
|
| Přihlášení, registrace, ověření e-mailu, obnova hesla | Hotovo | Implementován |
|
||||||
|
| Obnova relace, odhlášení / všechna zařízení | 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 včetně správy a deaktivace kategorií |
|
||||||
|
| Správa kategorií a statistiky vedení | Mimo rozsah mobilních obrazovek | Implementovány příslušné administrační a statistické endpointy |
|
||||||
|
| Nástěnka, seznam a detail vlastních závad, filtry, stránkování | Napojeno na skutečné API | Implementován |
|
||||||
|
| Nová závada, úprava přijaté závady, fotografie a soubory | Napojeno na skutečné API | Implementován |
|
||||||
|
| Komentáře, časová osa, stažení příloh | Napojeno na skutečné API | Implementován |
|
||||||
|
| Pracovní fronta řešitele a serverem povolené změny stavu | Napojeno podle `allowedActions` a `rowVersion` | Implementován |
|
||||||
|
| Seznam, detail, nový návrh, hlas pro/proti/zrušení | Napojeno včetně uzavřeného hlasování | Implementován |
|
||||||
|
| Seznam 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` |
|
||||||
|
|
||||||
|
Funkce fungují proti backendu z větve `main`; ukázka zůstává samostatnou volbou. Chyba serveru aplikaci nepřepne na ukázková data. Chyba 404 označuje nenalezený záznam, 409 obnoví konfliktující detail. Administrační a analytické obrazovky, přiřazování závad a hodnocení návrhů patří podle návrhu webové části.
|
||||||
|
|
||||||
|
Přesné síťové kontrakty jsou oddělené v `data/WireDtos.kt` a vycházejí z `backend/src/Helpdesk.Application/Issues/IssueDtos.cs`, `Proposals/ProposalDtos.cs` a `Notifications/NotificationService.cs`. `data/Models.kt` obsahuje modely pro obrazovky, ne předpokládaný formát serverových odpovědí:
|
||||||
|
|
||||||
|
- JSON v camelCase; seznamy `{ items, totalCount, page, pageSize }`, stránka po 20 položkách.
|
||||||
|
- Nové závady a návrhy nabízejí jen aktivní kategorie a budovy. Při úpravě starší závady lze ponechat původní deaktivovanou kategorii nebo budovu; formulář ji označí jako „již není v nabídce“ a zachová její ID i při obnovení číselníků. Obnovení číselníků nemaže rozepsaný název ani popis.
|
||||||
|
- Seznamy závad a návrhů vracejí souhrny bez popisu a názvů osob. Klient kvůli nim nestahuje každý detail; názvy budov/kategorií doplňuje ze sdílené cache číselníků. Jméno přihlášeného uživatele zná z profilu; další skutečná jména získá z autorů událostí v detailu, jinak zobrazí identifikátor uživatele.
|
||||||
|
- Detail závady obsahuje `locationDetail`, `priority`, `assigneeId`, `rowVersion` (nové hlášení začíná na nule), `allowedActions` a přílohy `{ id, fileName, contentType, sizeBytes, createdAt }`. Události se čtou přes `GET /issues/{id}/events`: `{ id, eventType, fromStatus, toStatus, actorId, actorName, note, occurredAt }`.
|
||||||
|
- `allowedActions` používá skutečné kódy `EDIT`, `START_WORK`, `SUBMIT_FOR_VERIFICATION`, `CONFIRM`, `REOPEN`, `REJECT`, `COMMENT`, `ADD_ATTACHMENTS`. Mobil zobrazuje pouze serverem povolené akce; `ASSIGN` je určený webovému rozhraní vedení.
|
||||||
|
- 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.
|
||||||
|
- 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`.
|
||||||
|
|
||||||
|
## Struktura a bezpečnost
|
||||||
|
|
||||||
|
- `ui/`: ViewModel, neměnný StateFlow, navigace, účet a profil, téma.
|
||||||
|
- `ui/features/`: funkční Compose obrazovky bez závislosti na síťové vrstvě; fotoaparát přes systémovou aplikaci, přílohy přes systémový výběr souborů.
|
||||||
|
- `data/`: kontrakty, Retrofit/OkHttp adaptér, ukázkový repozitář, šifrované úložiště relace.
|
||||||
|
- `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ářů.
|
||||||
|
|
||||||
|
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í.
|
||||||
|
|
||||||
|
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,66 @@
|
|||||||
|
plugins {
|
||||||
|
id("com.android.application")
|
||||||
|
id("org.jetbrains.kotlin.android")
|
||||||
|
id("org.jetbrains.kotlin.plugin.compose")
|
||||||
|
id("org.jetbrains.kotlin.plugin.serialization")
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "cz.ntbug.mobile"
|
||||||
|
compileSdk = 35
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "cz.ntbug.mobile"
|
||||||
|
minSdk = 26
|
||||||
|
targetSdk = 35
|
||||||
|
versionCode = 1
|
||||||
|
versionName = "0.1.0"
|
||||||
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
vectorDrawables.useSupportLibrary = true
|
||||||
|
}
|
||||||
|
buildTypes {
|
||||||
|
debug { applicationIdSuffix = ".debug" }
|
||||||
|
release {
|
||||||
|
isMinifyEnabled = true
|
||||||
|
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
kotlinOptions { jvmTarget = "17" }
|
||||||
|
buildFeatures { compose = true; buildConfig = true }
|
||||||
|
packaging { resources.excludes += "/META-INF/{AL2.0,LGPL2.1}" }
|
||||||
|
testOptions { unitTests.isReturnDefaultValues = true }
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
val composeBom = platform("androidx.compose:compose-bom:2025.04.01")
|
||||||
|
implementation(composeBom)
|
||||||
|
androidTestImplementation(composeBom)
|
||||||
|
implementation("androidx.core:core-ktx:1.16.0")
|
||||||
|
implementation("androidx.activity:activity-compose:1.10.1")
|
||||||
|
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.9.0")
|
||||||
|
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.9.0")
|
||||||
|
implementation("androidx.navigation:navigation-compose:2.9.0")
|
||||||
|
implementation("androidx.compose.ui:ui")
|
||||||
|
implementation("androidx.compose.ui:ui-tooling-preview")
|
||||||
|
implementation("androidx.compose.material3:material3")
|
||||||
|
implementation("androidx.compose.material:material-icons-extended")
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0")
|
||||||
|
implementation("com.squareup.retrofit2:retrofit:2.11.0")
|
||||||
|
implementation("com.squareup.retrofit2:converter-kotlinx-serialization:2.11.0")
|
||||||
|
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||||
|
implementation("io.coil-kt:coil-compose:2.7.0")
|
||||||
|
debugImplementation("androidx.compose.ui:ui-tooling")
|
||||||
|
testImplementation("junit:junit:4.13.2")
|
||||||
|
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2")
|
||||||
|
testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")
|
||||||
|
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
|
||||||
|
androidTestImplementation("androidx.test.ext:junit:1.2.1")
|
||||||
|
androidTestImplementation("androidx.test:runner:1.6.2")
|
||||||
|
androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1")
|
||||||
|
debugImplementation("androidx.compose.ui:ui-test-manifest")
|
||||||
|
}
|
||||||
Vendored
+2
@@ -0,0 +1,2 @@
|
|||||||
|
# Retrofit reads generic service signatures and annotations at runtime.
|
||||||
|
-keepattributes Signature,InnerClasses,EnclosingMethod,RuntimeVisibleAnnotations,RuntimeVisibleParameterAnnotations
|
||||||
@@ -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) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,303 @@
|
|||||||
|
package cz.ntbug.mobile
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
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.junit4.createAndroidComposeRule
|
||||||
|
import androidx.compose.ui.test.junit4.createComposeRule
|
||||||
|
import androidx.core.view.WindowCompat
|
||||||
|
import androidx.core.view.WindowInsetsCompat
|
||||||
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
|
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||||
|
import androidx.test.filters.LargeTest
|
||||||
|
import androidx.test.platform.app.InstrumentationRegistry
|
||||||
|
import org.junit.Rule
|
||||||
|
import org.junit.Test
|
||||||
|
import org.junit.rules.ExternalResource
|
||||||
|
import org.junit.rules.RuleChain
|
||||||
|
import org.junit.runner.RunWith
|
||||||
|
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. */
|
||||||
|
@RunWith(AndroidJUnit4::class)
|
||||||
|
@LargeTest
|
||||||
|
class MobileSmokeTest {
|
||||||
|
private val compose = createAndroidComposeRule<MainActivity>()
|
||||||
|
|
||||||
|
private val cleanSession = object : ExternalResource() {
|
||||||
|
override fun before() {
|
||||||
|
// Run before Activity creation, so a previous real session cannot start network work.
|
||||||
|
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 demoShowsDashboardAndLoadedIssues() {
|
||||||
|
enterDemo()
|
||||||
|
|
||||||
|
compose.onNodeWithText("UKÁZKOVÝ REŽIM").assertIsDisplayed()
|
||||||
|
compose.onNodeWithText("Nahlásit závadu").assertIsDisplayed()
|
||||||
|
compose.waitForIdle()
|
||||||
|
val context = InstrumentationRegistry.getInstrumentation().targetContext
|
||||||
|
val screenshot = File(requireNotNull(context.getExternalFilesDir(null)), "dashboard.png")
|
||||||
|
screenshot.outputStream().use { output ->
|
||||||
|
check(compose.onRoot().captureToImage().asAndroidBitmap().compress(Bitmap.CompressFormat.PNG, 100, output))
|
||||||
|
}
|
||||||
|
scrollTo("Nefunkční projektor v B-205")
|
||||||
|
compose.onNodeWithText("Nefunkční projektor v B-205").assertIsDisplayed()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun proposalVoteCanBeCastAndRemoved() {
|
||||||
|
enterDemo()
|
||||||
|
compose.onNodeWithText("Nápady").performClick()
|
||||||
|
awaitText("Návrhy na zlepšení")
|
||||||
|
scrollTo("Více zásuvek ve studovně")
|
||||||
|
compose.onNodeWithText("Více zásuvek ve studovně").performClick()
|
||||||
|
awaitText("Detail nápadu")
|
||||||
|
scrollTo("Co si o návrhu myslíte?")
|
||||||
|
|
||||||
|
compose.onNodeWithText("42").assertIsDisplayed()
|
||||||
|
compose.onNode(hasText("Pro") and hasClickAction()).performClick()
|
||||||
|
awaitText("43")
|
||||||
|
compose.onNode(hasText("Pro") and hasClickAction()).assertIsSelected()
|
||||||
|
|
||||||
|
compose.onNode(hasText("Pro") and hasClickAction()).performClick()
|
||||||
|
awaitText("42")
|
||||||
|
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
|
||||||
|
fun issueRequiresCategoryAndPersistsCreationAndComment() {
|
||||||
|
val title = "Testovací závada ve studovně"
|
||||||
|
val comment = "Upřesnění: zásuvka je u okna."
|
||||||
|
enterDemo()
|
||||||
|
compose.onNodeWithText("Nahlásit závadu").performClick()
|
||||||
|
awaitText("Nové hlášení")
|
||||||
|
|
||||||
|
scrollTo("Název závady *")
|
||||||
|
field("Název závady *").performTextInput(title)
|
||||||
|
hideKeyboard()
|
||||||
|
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.")
|
||||||
|
hideKeyboard()
|
||||||
|
scrollTo("Odeslat hlášení")
|
||||||
|
compose.onNodeWithText("Odeslat hlášení").performClick()
|
||||||
|
|
||||||
|
// Title and description are valid; the missing category must still block creation.
|
||||||
|
compose.onNodeWithText("Vyplňte název, popis a vyberte kategorii závady.").assertExists()
|
||||||
|
compose.onNodeWithText("Nové hlášení").assertIsDisplayed()
|
||||||
|
|
||||||
|
scrollTo("Kategorie *")
|
||||||
|
compose.onNodeWithText("Kategorie *").performClick()
|
||||||
|
compose.onNodeWithText("Elektroinstalace").performClick()
|
||||||
|
scrollTo("Odeslat hlášení")
|
||||||
|
compose.onNodeWithText("Odeslat hlášení").performClick()
|
||||||
|
awaitText("Detail hlášení")
|
||||||
|
awaitText(title)
|
||||||
|
compose.onAllNodesWithText("Přijata").onFirst().assertExists()
|
||||||
|
|
||||||
|
scrollTo("Napsat komentář")
|
||||||
|
field("Napsat komentář").performTextInput(comment)
|
||||||
|
hideKeyboard()
|
||||||
|
scrollTo("Odeslat komentář")
|
||||||
|
compose.onNodeWithText("Odeslat komentář").performClick()
|
||||||
|
awaitText("Komentář byl přidán.")
|
||||||
|
|
||||||
|
// Reload removes the editor's local state; the comment must come from repository data.
|
||||||
|
compose.onNodeWithContentDescription("Obnovit").performClick()
|
||||||
|
compose.waitForIdle()
|
||||||
|
scrollTo(comment)
|
||||||
|
compose.onNodeWithText(comment).assertIsDisplayed()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun profileCanEndDemoAndNewDemoStartsFresh() {
|
||||||
|
enterDemo()
|
||||||
|
compose.onNodeWithText("Profil").performClick()
|
||||||
|
awaitText("[email protected]")
|
||||||
|
compose.onNodeWithText("Ukončit ukázku").performScrollTo().performClick()
|
||||||
|
|
||||||
|
awaitText("Vítejte v NTBug")
|
||||||
|
compose.onNodeWithText("Prohlédnout ukázku").performScrollTo().assertIsDisplayed()
|
||||||
|
enterDemo()
|
||||||
|
compose.onNodeWithText("Ahoj, Jana.").assertIsDisplayed()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun enterDemo() {
|
||||||
|
awaitText("Prohlédnout ukázku")
|
||||||
|
compose.onNodeWithText("Prohlédnout ukázku").performScrollTo().performClick()
|
||||||
|
awaitText("Ahoj, Jana.")
|
||||||
|
compose.waitForIdle()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun awaitText(text: String) {
|
||||||
|
compose.waitUntil(timeoutMillis = 15_000) {
|
||||||
|
compose.onAllNodesWithText(text).fetchSemanticsNodes().isNotEmpty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun scrollTo(text: String) {
|
||||||
|
compose.onNode(hasScrollToIndexAction()).performScrollToNode(hasText(text))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun field(label: String): SemanticsNodeInteraction =
|
||||||
|
compose.onNode(hasSetTextAction() and hasText(label))
|
||||||
|
|
||||||
|
private fun hideKeyboard() {
|
||||||
|
compose.runOnUiThread {
|
||||||
|
WindowCompat.getInsetsController(compose.activity.window, compose.activity.window.decorView)
|
||||||
|
.hide(WindowInsetsCompat.Type.ime())
|
||||||
|
}
|
||||||
|
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"),
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
<application android:usesCleartextTraffic="true" tools:replace="android:usesCleartextTraffic" />
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-feature android:name="android.hardware.camera" android:required="false" />
|
||||||
|
<application
|
||||||
|
android:allowBackup="false"
|
||||||
|
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||||
|
android:icon="@drawable/ic_ntbug"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:supportsRtl="true"
|
||||||
|
android:theme="@style/Theme.NTBug"
|
||||||
|
android:usesCleartextTraffic="false">
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:windowSoftInputMode="adjustResize">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
<provider
|
||||||
|
android:name="androidx.core.content.FileProvider"
|
||||||
|
android:authorities="${applicationId}.files"
|
||||||
|
android:exported="false"
|
||||||
|
android:grantUriPermissions="true">
|
||||||
|
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
|
||||||
|
</provider>
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package cz.ntbug.mobile
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.compose.setContent
|
||||||
|
import androidx.activity.enableEdgeToEdge
|
||||||
|
import cz.ntbug.mobile.ui.NTBugApp
|
||||||
|
import cz.ntbug.mobile.ui.NTBugTheme
|
||||||
|
|
||||||
|
class MainActivity : ComponentActivity() {
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
enableEdgeToEdge()
|
||||||
|
setContent { NTBugTheme { NTBugApp() } }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import java.time.Instant
|
||||||
|
|
||||||
|
/** Explicit, ephemeral demonstration. This repository never sends data to a server. */
|
||||||
|
class DemoRepository : HelpdeskRepository {
|
||||||
|
private var user = User(1, "[email protected]", "Jana", "Nováková", role = "STUDENT")
|
||||||
|
private val catalog = Catalogs(
|
||||||
|
listOf(Building(1, "A", "Budova A", "Univerzitní kampus"), Building(2, "B", "Budova B", "Univerzitní kampus"), Building(3, "K", "Knihovna")),
|
||||||
|
listOf(Category(1, "Technické vybavení"), Category(2, "Elektroinstalace"), Category(3, "Voda a topení"), Category(4, "Úklid a prostředí"), Category(5, "Ostatní")),
|
||||||
|
listOf(Category(1, "Studium"), Category(2, "Služby"), Category(3, "Prostředí"), Category(4, "Ostatní")),
|
||||||
|
)
|
||||||
|
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", "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"))),
|
||||||
|
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"))),
|
||||||
|
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"))),
|
||||||
|
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"))),
|
||||||
|
).apply {
|
||||||
|
replaceAll { issue -> if (issue.assigneeName != null) issue.copy(assigneeId = 2) else issue }
|
||||||
|
}
|
||||||
|
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.", votesFor = 45, votesAgainst = 3,
|
||||||
|
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(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(
|
||||||
|
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(2, "Nový komentář u projektoru", "Petr Svoboda přidal zprávu k vašemu hlášení.", "2026-11-04T08:30:00Z", false, issueId = 104),
|
||||||
|
Notice(3, "Váš návrh byl přijat", "Stojany na kola u budovy B získaly podporu vedení.", "2026-11-03T09:00:00Z", true, proposalId = 23),
|
||||||
|
)
|
||||||
|
private val uploadedFiles = mutableMapOf<Int, Upload>()
|
||||||
|
private var nextAttachmentId = 1
|
||||||
|
|
||||||
|
override suspend fun login(email: String, password: String): User = user
|
||||||
|
override suspend fun register(email: String, password: String, firstName: String, lastName: String) = Unit
|
||||||
|
override suspend fun confirmEmail(token: String) = Unit
|
||||||
|
override suspend fun forgotPassword(email: String) = Unit
|
||||||
|
override suspend fun resetPassword(token: String, newPassword: String) = Unit
|
||||||
|
override suspend fun restoreUser(): User = user
|
||||||
|
override suspend fun logout(allDevices: Boolean) = Unit
|
||||||
|
override suspend fun updateProfile(update: ProfileUpdate): User {
|
||||||
|
require(update.firstName.isNotBlank() && update.lastName.isNotBlank()) { "Vyplňte jméno a příjmení." }
|
||||||
|
user = user.copy(firstName = update.firstName.trim(), lastName = update.lastName.trim(), phone = update.phone?.trim()?.takeIf(String::isNotBlank), emailNotificationsEnabled = update.emailNotificationsEnabled)
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
override suspend fun catalogs(refresh: Boolean): Catalogs = catalog
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
override suspend fun issue(id: Int): Issue = issueItems.firstOrNull { it.id == id } ?: throw ApiException(404, "Hlášení nebylo nalezeno.")
|
||||||
|
override suspend fun createIssue(issue: NewIssue): Issue {
|
||||||
|
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 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(), 0, listOf("EDIT", "COMMENT", "ADD_ATTACHMENTS"),
|
||||||
|
listOf(IssueEvent(nextEventId(), name(), "CREATED", "Závada byla přijata.", now(), user.id, null, "RECEIVED")))
|
||||||
|
issueItems.add(0, created)
|
||||||
|
addNotice("Hlášení bylo přijato", created.title, issueId = created.id)
|
||||||
|
return created
|
||||||
|
}
|
||||||
|
override suspend fun updateIssue(id: Int, issue: NewIssue, rowVersion: Int): Issue {
|
||||||
|
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 building = issue.buildingId?.let { buildingId -> catalog.buildings.first { it.id == buildingId } }
|
||||||
|
changeIssue(id) { old ->
|
||||||
|
if (old.rowVersion != rowVersion) throw ApiException(409, "Záznam se mezitím změnil. Obnovte jej.")
|
||||||
|
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,
|
||||||
|
buildingId = building?.id, buildingName = building?.name, location = issue.location.trim(),
|
||||||
|
events = old.events + IssueEvent(nextEventId(), name(), "UPDATED", "Hlášení bylo upraveno.", now(), user.id, null, old.status))
|
||||||
|
}
|
||||||
|
return this.issue(id)
|
||||||
|
}
|
||||||
|
override suspend fun addAttachments(id: Int, files: List<Upload>) {
|
||||||
|
validateUploads(files)
|
||||||
|
changeIssue(id) { old ->
|
||||||
|
ensureAllowed(old, "ADD_ATTACHMENTS")
|
||||||
|
old.copy(attachments = old.attachments + files.map { upload ->
|
||||||
|
val attachmentId = nextAttachmentId++
|
||||||
|
val name = uploadBaseName(upload.name)
|
||||||
|
uploadedFiles[attachmentId] = upload.copy(name = name, bytes = upload.bytes.copyOf())
|
||||||
|
Attachment(attachmentId, name, upload.mimeType)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override suspend fun downloadAttachment(id: Int): Upload = uploadedFiles[id]?.let { it.copy(bytes = it.bytes.copyOf()) }
|
||||||
|
?: throw ApiException(404, "Příloha není v této ukázkové relaci dostupná.")
|
||||||
|
override suspend fun comment(id: Int, text: String) {
|
||||||
|
require(text.isNotBlank()) { "Napište komentář." }
|
||||||
|
changeIssue(id) { old ->
|
||||||
|
ensureAllowed(old, "COMMENT")
|
||||||
|
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) {
|
||||||
|
changeIssue(id) { old ->
|
||||||
|
if (old.rowVersion != rowVersion) throw ApiException(409, "Záznam se mezitím změnil. Obnovte jej.")
|
||||||
|
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." }
|
||||||
|
val status = when (action) {
|
||||||
|
"start", "reopen" -> "IN_PROGRESS"
|
||||||
|
"submit-for-verification" -> "PENDING_VERIFICATION"
|
||||||
|
"confirm" -> "RESOLVED"
|
||||||
|
"reject" -> "REJECTED"
|
||||||
|
else -> throw IllegalArgumentException("Neznámá akce.")
|
||||||
|
}
|
||||||
|
val actions = when (status) {
|
||||||
|
"RESOLVED", "REJECTED" -> emptyList()
|
||||||
|
"PENDING_VERIFICATION" -> listOf("CONFIRM", "REOPEN", "COMMENT", "ADD_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(), user.id, old.status, status))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override suspend fun proposals(page: Int, query: String, sort: String): Page<Proposal> {
|
||||||
|
val filtered = proposalItems.filter { it.title.contains(query, true) || it.description.contains(query, true) }
|
||||||
|
return paginate(if (sort == "newest") filtered.sortedByDescending { it.createdAt } else filtered.sortedByDescending { it.score }, page)
|
||||||
|
}
|
||||||
|
override suspend fun proposal(id: Int): Proposal = proposalItems.firstOrNull { it.id == id } ?: throw ApiException(404, "Návrh nebyl nalezen.")
|
||||||
|
override suspend fun createProposal(proposal: NewProposal): Proposal {
|
||||||
|
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 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)
|
||||||
|
return created
|
||||||
|
}
|
||||||
|
override suspend fun vote(id: Int, value: Int?) {
|
||||||
|
require(value == null || value == 1 || value == -1) { "Neplatná hodnota hlasu." }
|
||||||
|
val proposal = proposal(id)
|
||||||
|
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 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 unreadCount(): Int = noticeItems.count { !it.isRead }
|
||||||
|
override suspend fun readNotice(id: Int) {
|
||||||
|
val index = noticeItems.indexOfFirst { it.id == id }
|
||||||
|
if (index >= 0) noticeItems[index] = noticeItems[index].copy(isRead = true)
|
||||||
|
}
|
||||||
|
override suspend fun readAllNotices() { noticeItems.replaceAll { it.copy(isRead = true) } }
|
||||||
|
|
||||||
|
private fun changeIssue(id: Int, change: (Issue) -> Issue) {
|
||||||
|
val index = issueItems.indexOfFirst { it.id == id }
|
||||||
|
if (index < 0) throw ApiException(404, "Hlášení nebylo nalezeno.")
|
||||||
|
val old = issueItems[index]
|
||||||
|
issueItems[index] = change(old).copy(rowVersion = old.rowVersion + 1)
|
||||||
|
}
|
||||||
|
private fun ensureAllowed(issue: Issue, action: String) {
|
||||||
|
if (action !in issue.allowedActions) throw ApiException(403, "Tato akce není u hlášení povolena.")
|
||||||
|
}
|
||||||
|
private fun addNotice(title: String, text: String, issueId: Int? = null, proposalId: Int? = null) {
|
||||||
|
noticeItems.add(0, Notice((noticeItems.maxOfOrNull { it.id } ?: 0) + 1, title, text, now(), false, issueId, proposalId))
|
||||||
|
}
|
||||||
|
private fun nextEventId() = (issueItems.flatMap { it.events }.maxOfOrNull { it.id } ?: 0) + 1
|
||||||
|
private fun name() = "${user.firstName} ${user.lastName}"
|
||||||
|
private fun now() = Instant.now().toString()
|
||||||
|
private fun <T> paginate(items: List<T>, page: Int): Page<T> {
|
||||||
|
require(page > 0) { "Neplatné číslo stránky." }
|
||||||
|
return Page(items.drop((page - 1) * 20).take(20), items.size, page, 20)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class User(
|
||||||
|
val id: Int, val email: String, val firstName: String, val lastName: String,
|
||||||
|
val phone: String? = null, val role: String, val emailNotificationsEnabled: Boolean = true,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class AuthSession(
|
||||||
|
val accessToken: String, val accessTokenExpiresAt: String,
|
||||||
|
val refreshToken: String, val refreshTokenExpiresAt: String, val user: User,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Building(val id: Int, val code: String, val name: String, val address: String? = null, val isActive: Boolean = true)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Category(val id: Int, val name: String, val description: String? = null, val isActive: Boolean = true)
|
||||||
|
|
||||||
|
data class Catalogs(val buildings: List<Building>, val issueCategories: List<Category>, val proposalCategories: List<Category>)
|
||||||
|
|
||||||
|
/** Screen model; REST summaries/details are mapped separately in WireDtos.kt. */
|
||||||
|
@Serializable
|
||||||
|
data class Issue(
|
||||||
|
val id: Int, val title: String, val description: String, val status: String,
|
||||||
|
val categoryId: Int, val categoryName: String, val buildingId: Int? = null,
|
||||||
|
val buildingName: String? = null, val location: String = "", val reporterId: Int,
|
||||||
|
val reporterName: String, val assigneeName: String? = null, val createdAt: String,
|
||||||
|
val rowVersion: Int = 0, val allowedActions: List<String> = emptyList(),
|
||||||
|
val events: List<IssueEvent> = emptyList(), val attachments: List<Attachment> = emptyList(),
|
||||||
|
val assigneeId: Int? = null, val priority: String = "NORMAL",
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
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
|
||||||
|
data class Attachment(val id: Int, val fileName: String, val contentType: String)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Proposal(
|
||||||
|
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 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
|
||||||
|
data class Notice(
|
||||||
|
val id: Int, val title: String, val text: String, val createdAt: String, val isRead: Boolean,
|
||||||
|
val issueId: Int? = null, val proposalId: Int? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Page<T>(val items: List<T>, val totalCount: Int, val page: Int = 1, val pageSize: Int = 20)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class NewIssue(val title: String, val description: String, val categoryId: Int, val buildingId: Int?, val location: String)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class NewProposal(val title: String, val description: String, val categoryId: Int)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ProfileUpdate(val firstName: String, val lastName: String, val phone: String?, val emailNotificationsEnabled: Boolean)
|
||||||
|
|
||||||
|
data class Upload(val name: String, val mimeType: String, val bytes: ByteArray)
|
||||||
|
|
||||||
|
class ApiException(val status: Int, message: String) : Exception(message)
|
||||||
|
|
||||||
|
interface HelpdeskRepository {
|
||||||
|
suspend fun login(email: String, password: String): User
|
||||||
|
suspend fun register(email: String, password: String, firstName: String, lastName: String)
|
||||||
|
suspend fun confirmEmail(token: String)
|
||||||
|
suspend fun forgotPassword(email: String)
|
||||||
|
suspend fun resetPassword(token: String, newPassword: String)
|
||||||
|
suspend fun restoreUser(): User?
|
||||||
|
suspend fun logout(allDevices: Boolean = false)
|
||||||
|
suspend fun updateProfile(update: ProfileUpdate): User
|
||||||
|
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 issue(id: Int): Issue
|
||||||
|
suspend fun createIssue(issue: NewIssue): Issue
|
||||||
|
suspend fun updateIssue(id: Int, issue: NewIssue, rowVersion: Int): Issue
|
||||||
|
suspend fun addAttachments(id: Int, files: List<Upload>)
|
||||||
|
suspend fun downloadAttachment(id: Int): Upload
|
||||||
|
suspend fun comment(id: Int, text: String)
|
||||||
|
suspend fun issueAction(id: Int, action: String, rowVersion: Int, reason: String = "")
|
||||||
|
suspend fun proposals(page: Int = 1, query: String = "", sort: String = "score"): Page<Proposal>
|
||||||
|
suspend fun proposal(id: Int): Proposal
|
||||||
|
suspend fun createProposal(proposal: NewProposal): Proposal
|
||||||
|
suspend fun vote(id: Int, value: Int?)
|
||||||
|
suspend fun notices(page: Int = 1): Page<Notice>
|
||||||
|
suspend fun unreadCount(): Int
|
||||||
|
suspend fun readNotice(id: Int)
|
||||||
|
suspend fun readAllNotices()
|
||||||
|
}
|
||||||
@@ -0,0 +1,386 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.currentCoroutineContext
|
||||||
|
import kotlinx.coroutines.ensureActive
|
||||||
|
import kotlinx.coroutines.NonCancellable
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlinx.serialization.SerializationException
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import kotlinx.serialization.json.jsonArray
|
||||||
|
import kotlinx.serialization.json.jsonObject
|
||||||
|
import kotlinx.serialization.json.jsonPrimitive
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
|
import okhttp3.ResponseBody
|
||||||
|
import retrofit2.HttpException
|
||||||
|
import retrofit2.Retrofit
|
||||||
|
import retrofit2.converter.kotlinx.serialization.asConverterFactory
|
||||||
|
import retrofit2.http.Body
|
||||||
|
import retrofit2.http.DELETE
|
||||||
|
import retrofit2.http.GET
|
||||||
|
import retrofit2.http.Header
|
||||||
|
import retrofit2.http.Multipart
|
||||||
|
import retrofit2.http.POST
|
||||||
|
import retrofit2.http.PUT
|
||||||
|
import retrofit2.http.Part
|
||||||
|
import retrofit2.http.Path
|
||||||
|
import retrofit2.http.Query
|
||||||
|
import retrofit2.http.Streaming
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.IOException
|
||||||
|
import java.net.URI
|
||||||
|
import java.net.URLDecoder
|
||||||
|
import java.time.Instant
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/** Accept an origin or an existing /api base URL; Retrofit needs the trailing slash. */
|
||||||
|
fun normalizeBaseUrl(value: String): String {
|
||||||
|
val uri = try { URI(value.trim()) } catch (_: Exception) { throw IllegalArgumentException("Zadejte platnou adresu serveru.") }
|
||||||
|
require(uri.scheme in listOf("https", "http") && !uri.host.isNullOrBlank() && uri.rawUserInfo == null && uri.rawQuery == null && uri.rawFragment == null) {
|
||||||
|
"Adresa musí začínat https:// (pro místní vývoj http://) a nesmí obsahovat přihlašovací údaje, dotaz ani fragment."
|
||||||
|
}
|
||||||
|
val base = value.trim().trimEnd('/')
|
||||||
|
return if (uri.path.trimEnd('/').endsWith("/api")) "$base/" else "$base/api/"
|
||||||
|
}
|
||||||
|
|
||||||
|
class RemoteRepository(baseUrl: String, private val store: SessionPersistence) : HelpdeskRepository {
|
||||||
|
private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
|
||||||
|
private val client = OkHttpClient.Builder()
|
||||||
|
.connectTimeout(15, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(30, TimeUnit.SECONDS)
|
||||||
|
.writeTimeout(45, TimeUnit.SECONDS)
|
||||||
|
// Token rotation and mutations must never be replayed automatically.
|
||||||
|
.retryOnConnectionFailure(false)
|
||||||
|
.followRedirects(false)
|
||||||
|
.followSslRedirects(false)
|
||||||
|
.build()
|
||||||
|
private val api = Retrofit.Builder().baseUrl(normalizeBaseUrl(baseUrl)).client(client)
|
||||||
|
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
|
||||||
|
.build().create(HelpdeskApi::class.java)
|
||||||
|
private val refreshLock = Mutex()
|
||||||
|
private val catalogLock = Mutex()
|
||||||
|
@Volatile private var catalogCache: Catalogs? = null
|
||||||
|
@Volatile private var session: AuthSession? = store.read()
|
||||||
|
|
||||||
|
override suspend fun login(email: String, password: String): User = mapped {
|
||||||
|
val response = api.login(LoginRequest(email.trim(), password))
|
||||||
|
store.write(response)
|
||||||
|
catalogCache = null
|
||||||
|
session = response
|
||||||
|
response.user
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun register(email: String, password: String, firstName: String, lastName: String) = mapped {
|
||||||
|
api.register(RegisterRequest(email.trim(), password, firstName.trim(), lastName.trim()))
|
||||||
|
Unit
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun confirmEmail(token: String) = mapped { api.confirmEmail(TokenRequest(token.trim())) }
|
||||||
|
override suspend fun forgotPassword(email: String) = mapped { api.forgotPassword(EmailRequest(email.trim())) }
|
||||||
|
override suspend fun resetPassword(token: String, newPassword: String) = mapped {
|
||||||
|
api.resetPassword(ResetRequest(token.trim(), newPassword))
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun restoreUser(): User? {
|
||||||
|
if (session == null) return null
|
||||||
|
return try {
|
||||||
|
val user = authorized { api.me(it) }
|
||||||
|
refreshLock.withLock {
|
||||||
|
session?.copy(user = user)?.also { store.write(it); session = it }
|
||||||
|
}
|
||||||
|
user
|
||||||
|
} catch (error: ApiException) {
|
||||||
|
if (error.status == 401) { clearSession(); null } else throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun logout(allDevices: Boolean) {
|
||||||
|
try {
|
||||||
|
if (session != null) authorized { bearer ->
|
||||||
|
if (allDevices) api.logoutAll(bearer)
|
||||||
|
else api.logout(bearer, RefreshRequest(requireSession().refreshToken))
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
refreshLock.withLock { clearSession() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun updateProfile(update: ProfileUpdate): User {
|
||||||
|
val user = authorized { api.updateMe(it, update) }
|
||||||
|
refreshLock.withLock {
|
||||||
|
session?.copy(user = user)?.also { store.write(it); session = it }
|
||||||
|
}
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun catalogs(refresh: Boolean): Catalogs = catalogLock.withLock {
|
||||||
|
// Administrators can rename/deactivate catalog entries while this session is open.
|
||||||
|
// Publish a replacement only when all three requests have completed successfully.
|
||||||
|
catalogCache?.takeUnless { refresh } ?: Catalogs(
|
||||||
|
authorized { api.buildings(it) }, authorized { api.issueCategories(it) }, authorized { api.proposalCategories(it) },
|
||||||
|
).also { catalogCache = it }
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun issues(page: Int, query: String, status: String?, assigned: Boolean): Page<Issue> {
|
||||||
|
val result = authorized {
|
||||||
|
api.issues(it, page, query.takeIf(String::isNotBlank), status, !assigned, if (assigned) requireSession().user.id else null)
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
val detail = authorized { api.issue(it, id) }
|
||||||
|
val events = authorized { api.events(it, id) }
|
||||||
|
return detail.toModel(catalogs(), requireSession().user, events)
|
||||||
|
}
|
||||||
|
override suspend fun createIssue(issue: NewIssue): Issue {
|
||||||
|
val catalog = catalogs()
|
||||||
|
val current = requireSession().user
|
||||||
|
return authorized { api.createIssue(it, issue.toCreateRequest()) }.toModel(catalog, current)
|
||||||
|
}
|
||||||
|
override suspend fun updateIssue(id: Int, issue: NewIssue, rowVersion: Int): Issue {
|
||||||
|
val catalog = catalogs()
|
||||||
|
val current = requireSession().user
|
||||||
|
return authorized { api.updateIssue(it, id, issue.toEditRequest(rowVersion)) }.toModel(catalog, current)
|
||||||
|
}
|
||||||
|
override suspend fun addAttachments(id: Int, files: List<Upload>) {
|
||||||
|
validateUploads(files)
|
||||||
|
if (files.isEmpty()) return
|
||||||
|
authorized { bearer ->
|
||||||
|
api.attachments(bearer, id, files.map { file ->
|
||||||
|
MultipartBody.Part.createFormData("files", uploadBaseName(file.name), file.bytes.toRequestBody(file.mimeType.toMediaType()))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
override suspend fun downloadAttachment(id: Int): Upload = authorized { bearer ->
|
||||||
|
val response = api.downloadAttachment(bearer, id)
|
||||||
|
if (!response.isSuccessful) throw HttpException(response)
|
||||||
|
val responseBody = response.body() ?: throw ApiException(0, "Server nevrátil obsah přílohy.")
|
||||||
|
val fileName = attachmentFileName(response.headers()["Content-Disposition"], id)
|
||||||
|
responseBody.use { body ->
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
if (body.contentLength() > MAX_ATTACHMENT_BYTES) throw ApiException(413, "Příloha je větší než povolených 10 MB.")
|
||||||
|
val bytes = body.byteStream().use { stream ->
|
||||||
|
val output = ByteArrayOutputStream()
|
||||||
|
val buffer = ByteArray(8192)
|
||||||
|
var total = 0
|
||||||
|
while (true) {
|
||||||
|
currentCoroutineContext().ensureActive()
|
||||||
|
val count = stream.read(buffer)
|
||||||
|
if (count < 0) break
|
||||||
|
total += count
|
||||||
|
if (total > MAX_ATTACHMENT_BYTES) throw ApiException(413, "Příloha je větší než povolených 10 MB.")
|
||||||
|
output.write(buffer, 0, count)
|
||||||
|
}
|
||||||
|
output.toByteArray()
|
||||||
|
}
|
||||||
|
Upload(fileName, body.contentType()?.toString()?.substringBefore(';') ?: "application/octet-stream", bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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) {
|
||||||
|
require(action in listOf("start", "submit-for-verification", "confirm", "reopen", "reject")) { "Neznámá akce závady." }
|
||||||
|
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> {
|
||||||
|
val result = authorized { api.proposals(it, page, query.takeIf(String::isNotBlank), sort) }
|
||||||
|
if (result.items.isEmpty()) return Page(emptyList(), result.totalCount, result.page, result.pageSize)
|
||||||
|
val catalog = catalogs()
|
||||||
|
val current = requireSession().user
|
||||||
|
return Page(result.items.map { it.toModel(catalog, current) }, result.totalCount, result.page, result.pageSize)
|
||||||
|
}
|
||||||
|
override suspend fun proposal(id: Int): Proposal {
|
||||||
|
val result = authorized { api.proposal(it, id) }
|
||||||
|
return result.toModel(catalogs(), requireSession().user)
|
||||||
|
}
|
||||||
|
override suspend fun createProposal(proposal: NewProposal): Proposal {
|
||||||
|
val catalog = catalogs()
|
||||||
|
val current = requireSession().user
|
||||||
|
return authorized { api.createProposal(it, proposal) }.toModel(catalog, current)
|
||||||
|
}
|
||||||
|
override suspend fun vote(id: Int, value: Int?) {
|
||||||
|
require(value == null || value == 1 || value == -1) { "Hlas musí být pro, proti nebo zrušen." }
|
||||||
|
authorized { if (value == null) api.removeVote(it, id) else api.vote(it, id, VoteRequest(value)) }
|
||||||
|
}
|
||||||
|
override suspend fun notices(page: Int): Page<Notice> {
|
||||||
|
val result = authorized { api.notices(it, page) }
|
||||||
|
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 clearSession() { session = null; catalogCache = null; store.clear() }
|
||||||
|
|
||||||
|
private suspend fun token(): String {
|
||||||
|
val current = requireSession()
|
||||||
|
val expiresSoon = runCatching { Instant.parse(current.accessTokenExpiresAt).isBefore(Instant.now().plusSeconds(30)) }.getOrDefault(false)
|
||||||
|
return if (expiresSoon) refresh(current.accessToken) else current.accessToken
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One refresh per old access token, even when several screens receive 401 together. */
|
||||||
|
private suspend fun refresh(oldAccessToken: String): String = refreshLock.withLock {
|
||||||
|
val current = requireSession()
|
||||||
|
if (current.accessToken != oldAccessToken) return@withLock current.accessToken
|
||||||
|
// Changing a screen/search must not cancel token rotation halfway through.
|
||||||
|
// Finish and persist the single-use response before releasing the mutex.
|
||||||
|
withContext(NonCancellable) {
|
||||||
|
try {
|
||||||
|
val renewed = api.refresh(RefreshRequest(current.refreshToken))
|
||||||
|
store.write(renewed)
|
||||||
|
session = renewed
|
||||||
|
renewed.accessToken
|
||||||
|
} catch (error: Exception) {
|
||||||
|
// Even an IO/storage failure may happen after server-side rotation.
|
||||||
|
// Require a fresh login instead of replaying an uncertain refresh token.
|
||||||
|
clearSession()
|
||||||
|
throw ApiException(401, "Přihlášení se nepodařilo bezpečně obnovit. Přihlaste se znovu.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun <T> authorized(block: suspend (String) -> T): T = mapped {
|
||||||
|
val access = token()
|
||||||
|
try { block("Bearer $access") }
|
||||||
|
catch (error: HttpException) {
|
||||||
|
if (error.code() != 401) throw error
|
||||||
|
val renewed = refresh(access)
|
||||||
|
try { block("Bearer $renewed") }
|
||||||
|
catch (second: HttpException) {
|
||||||
|
if (second.code() == 401) refreshLock.withLock {
|
||||||
|
if (session?.accessToken == renewed) clearSession()
|
||||||
|
}
|
||||||
|
throw second
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun <T> mapped(block: suspend () -> T): T = try { block() }
|
||||||
|
catch (error: CancellationException) { throw error }
|
||||||
|
catch (error: HttpException) {
|
||||||
|
val fallback = when (error.code()) {
|
||||||
|
400 -> "Zkontrolujte vyplněné údaje."
|
||||||
|
401 -> "Přihlášení vypršelo nebo jsou přihlašovací údaje nesprávné."
|
||||||
|
403 -> "K této akci nemáte oprávnění."
|
||||||
|
404 -> "Požadovaný záznam nebyl nalezen."
|
||||||
|
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."
|
||||||
|
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."
|
||||||
|
}
|
||||||
|
val body = runCatching { error.response()?.errorBody()?.string() }.getOrNull()
|
||||||
|
val message = problemMessage(body) ?: fallback
|
||||||
|
throw ApiException(error.code(), message)
|
||||||
|
}
|
||||||
|
catch (error: SerializationException) { throw ApiException(0, "Server vrátil odpověď v neočekávaném formátu.") }
|
||||||
|
catch (error: IOException) { throw ApiException(0, "K serveru se nelze připojit. Zkontrolujte internet a adresu serveru.") }
|
||||||
|
|
||||||
|
private fun problemMessage(body: String?): String? = runCatching {
|
||||||
|
val problem = json.parseToJsonElement(body ?: return null).jsonObject
|
||||||
|
val validation = problem["errors"]?.jsonObject?.values?.flatMap { it.jsonArray.map { item -> item.jsonPrimitive.content } }?.distinct()
|
||||||
|
validation?.takeIf(List<String>::isNotEmpty)?.joinToString("\n")
|
||||||
|
?: problem["detail"]?.jsonPrimitive?.content?.takeIf(String::isNotBlank)
|
||||||
|
?: problem["title"]?.jsonPrimitive?.content?.takeIf(String::isNotBlank)
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun validateUploads(files: List<Upload>) {
|
||||||
|
require(files.size <= 5) { "Najednou můžete přiložit nejvýše 5 souborů." }
|
||||||
|
files.forEach {
|
||||||
|
require(it.bytes.isNotEmpty() && it.bytes.size <= 10 * 1024 * 1024) { "Každý soubor musí mít velikost 1 B až 10 MB." }
|
||||||
|
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 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 TokenRequest(val token: String)
|
||||||
|
@Serializable private data class EmailRequest(val email: String)
|
||||||
|
@Serializable private data class ResetRequest(val token: String, val newPassword: String)
|
||||||
|
@Serializable private data class CommentRequest(val text: String)
|
||||||
|
@Serializable private data class VoteRequest(val value: Int)
|
||||||
|
|
||||||
|
private const val MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024
|
||||||
|
|
||||||
|
private fun attachmentFileName(disposition: String?, id: Int): String {
|
||||||
|
val utf8 = disposition?.let { Regex("filename\\*=UTF-8''([^;]+)", RegexOption.IGNORE_CASE).find(it)?.groupValues?.get(1) }
|
||||||
|
val encodedName = utf8?.let { runCatching { URLDecoder.decode(it.replace("+", "%2B"), "UTF-8") }.getOrNull() }
|
||||||
|
val plainName = disposition?.let { Regex("filename=\\\"([^\\\"]+)\\\"|filename=([^;]+)", RegexOption.IGNORE_CASE).find(it)?.groupValues?.drop(1)?.firstOrNull(String::isNotEmpty) }
|
||||||
|
return (encodedName ?: plainName)?.trim()?.substringAfterLast('/')?.substringAfterLast('\\')
|
||||||
|
?.filter { it.code >= 32 && it.code != 127 }?.take(150)?.takeIf { it.isNotBlank() && it != "." && it != ".." }
|
||||||
|
?: "attachment-$id"
|
||||||
|
}
|
||||||
|
|
||||||
|
private interface HelpdeskApi {
|
||||||
|
@POST("auth/login") suspend fun login(@Body request: LoginRequest): AuthSession
|
||||||
|
@POST("auth/register") suspend fun register(@Body request: RegisterRequest): User
|
||||||
|
@POST("auth/refresh") suspend fun refresh(@Body request: RefreshRequest): AuthSession
|
||||||
|
@POST("auth/confirm-email") suspend fun confirmEmail(@Body request: TokenRequest)
|
||||||
|
@POST("auth/forgot-password") suspend fun forgotPassword(@Body request: EmailRequest)
|
||||||
|
@POST("auth/reset-password") suspend fun resetPassword(@Body request: ResetRequest)
|
||||||
|
@POST("auth/logout") suspend fun logout(@Header("Authorization") bearer: String, @Body request: RefreshRequest)
|
||||||
|
@POST("auth/logout-all") suspend fun logoutAll(@Header("Authorization") bearer: String)
|
||||||
|
@GET("users/me") suspend fun me(@Header("Authorization") bearer: String): User
|
||||||
|
@PUT("users/me") suspend fun updateMe(@Header("Authorization") bearer: String, @Body request: ProfileUpdate): User
|
||||||
|
@GET("buildings") suspend fun buildings(@Header("Authorization") bearer: String): List<Building>
|
||||||
|
@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("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): WireIssueDetail
|
||||||
|
@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: CreateIssueRequest): WireIssueDetail
|
||||||
|
@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>): List<WireAttachment>
|
||||||
|
@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): WireIssueEvent
|
||||||
|
@POST("issues/{id}/start") suspend fun startIssue(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: IssueVersionRequest): WireIssueDetail
|
||||||
|
@POST("issues/{id}/submit-for-verification") suspend fun submitIssue(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: VerifyIssueRequest): WireIssueDetail
|
||||||
|
@POST("issues/{id}/confirm") suspend fun confirmIssue(@Header("Authorization") bearer: String, @Path("id") id: Int, @Body request: IssueVersionRequest): WireIssueDetail
|
||||||
|
@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)
|
||||||
|
@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<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/read-all") suspend fun readAllNotices(@Header("Authorization") bearer: String)
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.security.keystore.KeyGenParameterSpec
|
||||||
|
import android.security.keystore.KeyProperties
|
||||||
|
import android.util.Base64
|
||||||
|
import kotlinx.serialization.encodeToString
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import java.security.KeyStore
|
||||||
|
import javax.crypto.Cipher
|
||||||
|
import javax.crypto.KeyGenerator
|
||||||
|
import javax.crypto.SecretKey
|
||||||
|
import javax.crypto.spec.GCMParameterSpec
|
||||||
|
|
||||||
|
interface SessionPersistence {
|
||||||
|
fun read(): AuthSession?
|
||||||
|
fun write(session: AuthSession)
|
||||||
|
fun clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Only ciphertext is written to disk. The AES key never leaves Android Keystore. */
|
||||||
|
class SessionStore(context: Context) : SessionPersistence {
|
||||||
|
private val preferences = context.applicationContext.getSharedPreferences("ntbug_session", Context.MODE_PRIVATE)
|
||||||
|
private val json = Json { ignoreUnknownKeys = true }
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
override fun read(): AuthSession? {
|
||||||
|
val encoded = preferences.getString("session", null) ?: return null
|
||||||
|
return try {
|
||||||
|
val blob = Base64.decode(encoded, Base64.NO_WRAP)
|
||||||
|
require(blob.size > 12)
|
||||||
|
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||||
|
cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, blob.copyOfRange(0, 12)))
|
||||||
|
json.decodeFromString<AuthSession>(cipher.doFinal(blob.copyOfRange(12, blob.size)).decodeToString())
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// Reinstallation, invalidated keys or corrupt storage require a fresh sign-in.
|
||||||
|
clear()
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
override fun write(session: AuthSession) {
|
||||||
|
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||||
|
cipher.init(Cipher.ENCRYPT_MODE, key())
|
||||||
|
val encrypted = cipher.doFinal(json.encodeToString(session).encodeToByteArray())
|
||||||
|
check(preferences.edit().putString("session", Base64.encodeToString(cipher.iv + encrypted, Base64.NO_WRAP)).commit()) {
|
||||||
|
"Přihlášení se nepodařilo bezpečně uložit."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
override fun clear() {
|
||||||
|
preferences.edit().remove("session").commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun key(): SecretKey {
|
||||||
|
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||||
|
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
|
||||||
|
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
|
||||||
|
init(KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||||
|
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||||
|
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||||
|
.setKeySize(256)
|
||||||
|
.build())
|
||||||
|
}.generateKey()
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object { const val KEY_ALIAS = "ntbug.session.v1" }
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
package cz.ntbug.mobile.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.outlined.*
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
|
import androidx.compose.ui.text.input.VisualTransformation
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import cz.ntbug.mobile.data.ProfileUpdate
|
||||||
|
import cz.ntbug.mobile.data.User
|
||||||
|
|
||||||
|
private enum class AuthMode(val title: String, val action: String) {
|
||||||
|
LOGIN("Vítejte v NTBug", "Přihlásit se"),
|
||||||
|
REGISTER("Vytvořit účet", "Zaregistrovat se"),
|
||||||
|
FORGOT("Zapomenuté heslo", "Odeslat odkaz"),
|
||||||
|
CONFIRM("Ověřit e-mail", "Ověřit e-mail"),
|
||||||
|
RESET("Nové heslo", "Změnit heslo"),
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun AccountScreen(s: AppState, vm: AppViewModel) {
|
||||||
|
var mode by rememberSaveable { mutableStateOf(AuthMode.LOGIN) }
|
||||||
|
var email by rememberSaveable { mutableStateOf("") }
|
||||||
|
var first by rememberSaveable { mutableStateOf("") }
|
||||||
|
var last by rememberSaveable { mutableStateOf("") }
|
||||||
|
// Credentials and email tokens intentionally stay out of saved instance state.
|
||||||
|
var password by remember { mutableStateOf("") }
|
||||||
|
var repeat by remember { mutableStateOf("") }
|
||||||
|
var token by remember { mutableStateOf("") }
|
||||||
|
var validation by remember { mutableStateOf<String?>(null) }
|
||||||
|
var serverDialog by remember { mutableStateOf(false) }
|
||||||
|
fun complete(value: AuthMode) {
|
||||||
|
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(
|
||||||
|
Modifier.fillMaxSize().safeDrawingPadding().imePadding().verticalScroll(rememberScrollState()).padding(horizontal = 24.dp, vertical = 28.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||||
|
) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
Box(Modifier.size(48.dp).background(Color(0xFF102C36), RoundedCornerShape(16.dp)), contentAlignment = Alignment.Center) {
|
||||||
|
Icon(Icons.Outlined.BugReport, null, tint = Color(0xFF67DCC3))
|
||||||
|
}
|
||||||
|
Column {
|
||||||
|
Text("NTBug", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
|
||||||
|
Text("Není to bug. Je to podnět ke změně.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
Text(mode.title, style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold)
|
||||||
|
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.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 -> "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.RESET -> "Vložte odkaz z e-mailu a zvolte nové heslo o délce 8 až 64 znaků."
|
||||||
|
}, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
|
||||||
|
if (mode == AuthMode.REGISTER) {
|
||||||
|
AccountField(first, { first = it }, "Jméno", enabled = !s.busy)
|
||||||
|
AccountField(last, { last = it }, "Příjmení", enabled = !s.busy)
|
||||||
|
}
|
||||||
|
if (mode in listOf(AuthMode.LOGIN, AuthMode.REGISTER, AuthMode.FORGOT)) {
|
||||||
|
AccountField(email, { email = it }, "Univerzitní e-mail", KeyboardType.Email, !s.busy)
|
||||||
|
}
|
||||||
|
if (mode in listOf(AuthMode.CONFIRM, AuthMode.RESET)) {
|
||||||
|
AccountField(token, { token = it }, "Odkaz nebo token z e-mailu", enabled = !s.busy, singleLine = false)
|
||||||
|
}
|
||||||
|
if (mode in listOf(AuthMode.LOGIN, AuthMode.REGISTER, AuthMode.RESET)) {
|
||||||
|
PasswordField(password, { password = it }, if (mode == AuthMode.RESET) "Nové heslo" else "Heslo", !s.busy)
|
||||||
|
}
|
||||||
|
if (mode in listOf(AuthMode.REGISTER, AuthMode.RESET)) PasswordField(repeat, { repeat = it }, "Heslo znovu", !s.busy)
|
||||||
|
val error = validation ?: s.error
|
||||||
|
if (error != null) Feedback(error, true)
|
||||||
|
s.authMessage?.let { Feedback(it, false) }
|
||||||
|
Button(
|
||||||
|
enabled = !s.busy,
|
||||||
|
modifier = Modifier.fillMaxWidth().heightIn(min = 52.dp),
|
||||||
|
onClick = {
|
||||||
|
validation = when {
|
||||||
|
mode in listOf(AuthMode.LOGIN, AuthMode.REGISTER, AuthMode.FORGOT) && !validEmail(email) -> "Vyplňte platný e-mail."
|
||||||
|
mode == AuthMode.LOGIN && password.isBlank() -> "Vyplňte heslo."
|
||||||
|
mode in listOf(AuthMode.REGISTER, AuthMode.RESET) && password.length !in 8..64 -> "Heslo musí mít 8 až 64 znaků."
|
||||||
|
mode in listOf(AuthMode.REGISTER, AuthMode.RESET) && repeat != password -> "Hesla se neshodují."
|
||||||
|
mode == AuthMode.REGISTER && (first.isBlank() || last.isBlank() || first.trim().length > 100 || last.trim().length > 100) -> "Vyplňte jméno a příjmení, každé do 100 znaků."
|
||||||
|
mode in listOf(AuthMode.CONFIRM, AuthMode.RESET) && token.isBlank() -> "Vložte token nebo odkaz z e-mailu."
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
if (validation == null) when (mode) {
|
||||||
|
AuthMode.LOGIN -> vm.login(email, password)
|
||||||
|
AuthMode.REGISTER -> vm.register(email, password, first, last)
|
||||||
|
AuthMode.FORGOT -> vm.forgotPassword(email)
|
||||||
|
AuthMode.CONFIRM -> vm.confirmEmail(token)
|
||||||
|
AuthMode.RESET -> vm.resetPassword(token, password)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
) { if (s.busy) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) else Text(mode.action) }
|
||||||
|
|
||||||
|
if (mode == AuthMode.LOGIN) {
|
||||||
|
TextButton(onClick = { change(AuthMode.FORGOT) }, enabled = !s.busy, modifier = Modifier.align(Alignment.CenterHorizontally)) { Text("Zapomněli jste heslo?") }
|
||||||
|
OutlinedButton(onClick = { change(AuthMode.REGISTER) }, enabled = !s.busy, modifier = Modifier.fillMaxWidth()) { Text("Ještě nemám účet") }
|
||||||
|
HorizontalDivider()
|
||||||
|
OutlinedButton(onClick = vm::demo, enabled = !s.busy, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) {
|
||||||
|
Icon(Icons.Outlined.Explore, null); Spacer(Modifier.width(8.dp)); Text("Prohlédnout ukázku")
|
||||||
|
}
|
||||||
|
Text("Ukázková data jsou oddělená od vašeho účtu a po odhlášení se smažou.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) {
|
||||||
|
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") }
|
||||||
|
}
|
||||||
|
} 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)) {
|
||||||
|
Icon(Icons.Outlined.Dns, null, modifier = Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text("Nastavení serveru")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (serverDialog) ServerDialog(s.baseUrl, { serverDialog = false }) { vm.server(it); serverDialog = false }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ProfileScreen(user: User, s: AppState, vm: AppViewModel) {
|
||||||
|
var first by rememberSaveable(user) { mutableStateOf(user.firstName) }
|
||||||
|
var last by rememberSaveable(user) { mutableStateOf(user.lastName) }
|
||||||
|
var phone by rememberSaveable(user) { mutableStateOf(user.phone.orEmpty()) }
|
||||||
|
var emailNotifications by rememberSaveable(user) { mutableStateOf(user.emailNotificationsEnabled) }
|
||||||
|
var validation by remember { mutableStateOf<String?>(null) }
|
||||||
|
Column(Modifier.fillMaxSize().imePadding().verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||||
|
Card(Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)) {
|
||||||
|
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||||
|
Text("${user.firstName} ${user.lastName}", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
|
||||||
|
Text(user.email)
|
||||||
|
Text(roleLabel(user.role), style = MaterialTheme.typography.labelLarge)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text("Osobní údaje", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||||
|
AccountField(first, { first = it }, "Jméno", enabled = !s.busy)
|
||||||
|
AccountField(last, { last = it }, "Příjmení", enabled = !s.busy)
|
||||||
|
AccountField(phone, { phone = it }, "Telefon (nepovinný)", KeyboardType.Phone, !s.busy)
|
||||||
|
ListItem(
|
||||||
|
headlineContent = { Text("E-mailová oznámení") },
|
||||||
|
supportingContent = { Text("Změny stavu a nové komentáře") },
|
||||||
|
trailingContent = { Switch(emailNotifications, { emailNotifications = it }, enabled = !s.busy) },
|
||||||
|
)
|
||||||
|
validation?.let { Feedback(it, true) }
|
||||||
|
Button(onClick = {
|
||||||
|
validation = when {
|
||||||
|
first.isBlank() || last.isBlank() || first.trim().length > 100 || last.trim().length > 100 -> "Jméno i příjmení musí mít 1 až 100 znaků."
|
||||||
|
phone.length > 30 || phone.isNotBlank() && !Regex("^\\+?[0-9 ]+$").matches(phone.trim()) -> "Telefon smí obsahovat číslice, mezery a úvodní +, nejvýše 30 znaků."
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
if (validation == null) vm.profile(ProfileUpdate(first.trim(), last.trim(), phone.trim().ifBlank { null }, emailNotifications))
|
||||||
|
}, enabled = !s.busy, modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp)) { Text("Uložit změny") }
|
||||||
|
HorizontalDivider()
|
||||||
|
Text("O aplikaci", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||||
|
Text(if (s.demo) "Ukázkový režim · data jsou pouze v paměti aplikace." else "Server: ${s.baseUrl}", style = MaterialTheme.typography.bodySmall)
|
||||||
|
Text("NTBug 0.1.0 · Univerzitní helpdesk", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
Text("Oznámení jsou dostupná v aplikaci. Push oznámení zatím nejsou zapojená.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
OutlinedButton(onClick = { vm.logout(false) }, enabled = !s.busy, modifier = Modifier.fillMaxWidth()) { Text(if (s.demo) "Ukončit ukázku" else "Odhlásit se") }
|
||||||
|
if (!s.demo) TextButton(onClick = { vm.logout(true) }, enabled = !s.busy, modifier = Modifier.fillMaxWidth()) { Text("Odhlásit ze všech zařízení") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun AccountField(value: String, onChange: (String) -> Unit, label: String, keyboardType: KeyboardType = KeyboardType.Text, enabled: Boolean = true, singleLine: Boolean = true) {
|
||||||
|
OutlinedTextField(value, onChange, label = { Text(label) }, modifier = Modifier.fillMaxWidth(), singleLine = singleLine, enabled = enabled, keyboardOptions = KeyboardOptions(keyboardType = keyboardType), shape = RoundedCornerShape(14.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun PasswordField(value: String, onChange: (String) -> Unit, label: String, enabled: Boolean) {
|
||||||
|
var visible by remember { mutableStateOf(false) }
|
||||||
|
OutlinedTextField(value, onChange, label = { Text(label) }, modifier = Modifier.fillMaxWidth(), singleLine = true, enabled = enabled,
|
||||||
|
visualTransformation = if (visible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), shape = RoundedCornerShape(14.dp),
|
||||||
|
trailingIcon = { IconButton(onClick = { visible = !visible }) { Icon(if (visible) Icons.Outlined.VisibilityOff else Icons.Outlined.Visibility, if (visible) "Skrýt heslo" else "Zobrazit heslo") } },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun Feedback(message: String, error: Boolean) {
|
||||||
|
Surface(color = if (error) MaterialTheme.colorScheme.errorContainer else MaterialTheme.colorScheme.primaryContainer, shape = RoundedCornerShape(12.dp), modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Text(message, Modifier.padding(14.dp), color = if (error) MaterialTheme.colorScheme.onErrorContainer else MaterialTheme.colorScheme.onPrimaryContainer, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun ServerDialog(current: String, onDismiss: () -> Unit, onSave: (String) -> Unit) {
|
||||||
|
var value by remember { mutableStateOf(current) }
|
||||||
|
AlertDialog(onDismissRequest = onDismiss, title = { Text("Server NTBug") },
|
||||||
|
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. 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)
|
||||||
|
} }, confirmButton = { TextButton(onClick = { onSave(value) }) { Text("Uložit") } }, dismissButton = { TextButton(onClick = onDismiss) { Text("Zrušit") } })
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun validEmail(value: String): Boolean = value.trim().length <= 254 && Regex("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$").matches(value.trim())
|
||||||
|
private fun roleLabel(role: String) = when (role) {
|
||||||
|
"STUDENT" -> "Student"; "TEACHER" -> "Vyučující"; "FACILITY_MANAGER" -> "Správce budov"; "MANAGEMENT" -> "Vedení školy"; "ADMIN" -> "Administrátor"; else -> role
|
||||||
|
}
|
||||||
@@ -0,0 +1,409 @@
|
|||||||
|
package cz.ntbug.mobile.ui
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import androidx.lifecycle.AndroidViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import cz.ntbug.mobile.data.*
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.coroutineScope
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
enum class AuthOutcome { REGISTERED, EMAIL_CONFIRMED, PASSWORD_RESET }
|
||||||
|
|
||||||
|
data class AppState(
|
||||||
|
val booting: Boolean = true,
|
||||||
|
val user: User? = null,
|
||||||
|
val demo: Boolean = false,
|
||||||
|
val baseUrl: String = "http://10.0.2.2:8080/",
|
||||||
|
val busy: Boolean = false,
|
||||||
|
val loading: Boolean = false,
|
||||||
|
val error: String? = null,
|
||||||
|
val message: String? = null,
|
||||||
|
val authMessage: String? = null,
|
||||||
|
val authOutcome: AuthOutcome? = null,
|
||||||
|
val catalogs: Catalogs = Catalogs(emptyList(), emptyList(), emptyList()),
|
||||||
|
val issues: List<Issue> = emptyList(),
|
||||||
|
val proposals: List<Proposal> = emptyList(),
|
||||||
|
val notices: List<Notice> = emptyList(),
|
||||||
|
val unreadCount: Int = 0,
|
||||||
|
val issue: Issue? = null,
|
||||||
|
val proposal: Proposal? = null,
|
||||||
|
val issueQuery: String = "",
|
||||||
|
val issueStatus: String? = null,
|
||||||
|
val assigned: Boolean = false,
|
||||||
|
val proposalQuery: String = "",
|
||||||
|
val proposalSort: String = "score",
|
||||||
|
val issuePage: Int = 0,
|
||||||
|
val proposalPage: Int = 0,
|
||||||
|
val noticePage: Int = 0,
|
||||||
|
val moreIssues: Boolean = false,
|
||||||
|
val moreProposals: Boolean = false,
|
||||||
|
val moreNotices: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
class AppViewModel(application: Application) : AndroidViewModel(application) {
|
||||||
|
private val preferences = application.getSharedPreferences("connection", 0)
|
||||||
|
private val sessionStore = SessionStore(application)
|
||||||
|
private val state = MutableStateFlow(AppState(baseUrl = preferences.getString("baseUrl", null) ?: "http://10.0.2.2:8080/"))
|
||||||
|
val ui = state.asStateFlow()
|
||||||
|
private var repository: HelpdeskRepository = RemoteRepository(state.value.baseUrl, sessionStore)
|
||||||
|
private var loadJob: Job? = null
|
||||||
|
private var currentRoute = "home"
|
||||||
|
private var generation = 0
|
||||||
|
private var loadSequence = 0
|
||||||
|
|
||||||
|
init {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
state.update { it.copy(user = repository.restoreUser()) }
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (e is CancellationException) throw e
|
||||||
|
state.update { it.copy(error = e.message ?: "Přihlášení se nepodařilo obnovit.") }
|
||||||
|
} finally {
|
||||||
|
state.update { it.copy(booting = false) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun server(value: String) {
|
||||||
|
if (state.value.busy || state.value.booting || state.value.user != null) return
|
||||||
|
try {
|
||||||
|
val url = normalizeBaseUrl(value)
|
||||||
|
if (!cz.ntbug.mobile.BuildConfig.DEBUG && !url.startsWith("https://")) {
|
||||||
|
throw IllegalArgumentException("Pro vydanou aplikaci použijte adresu HTTPS.")
|
||||||
|
}
|
||||||
|
sessionStore.clear()
|
||||||
|
repository = RemoteRepository(url, sessionStore)
|
||||||
|
preferences.edit().putString("baseUrl", url).apply()
|
||||||
|
state.update { it.copy(baseUrl = url, demo = false, error = null, authMessage = "Adresa serveru byla uložena.") }
|
||||||
|
} catch (e: IllegalArgumentException) {
|
||||||
|
state.update { it.copy(error = e.message ?: "Adresa serveru není platná.") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun login(email: String, password: String) = operation {
|
||||||
|
val user = repository.login(email.trim(), password)
|
||||||
|
state.update { it.copy(user = user, demo = false, authMessage = null) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun demo() {
|
||||||
|
if (state.value.busy) return
|
||||||
|
repository = DemoRepository()
|
||||||
|
operation {
|
||||||
|
val user = repository.login("[email protected]", "demo")
|
||||||
|
state.update { AppState(booting = false, user = user, demo = true, baseUrl = it.baseUrl) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun register(email: String, password: String, firstName: String, lastName: String) = operation {
|
||||||
|
try {
|
||||||
|
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 {
|
||||||
|
repository.forgotPassword(email.trim())
|
||||||
|
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 {
|
||||||
|
repository.confirmEmail(extractEmailActionToken(token, EmailAction.CONFIRM))
|
||||||
|
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 {
|
||||||
|
repository.resetPassword(extractEmailActionToken(token, EmailAction.RESET), password)
|
||||||
|
state.update { it.copy(authMessage = "Heslo bylo změněno. Přihlaste se novým heslem.", authOutcome = AuthOutcome.PASSWORD_RESET) }
|
||||||
|
}
|
||||||
|
|
||||||
|
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 logout(allDevices: Boolean) {
|
||||||
|
if (state.value.busy) return
|
||||||
|
loadJob?.cancel()
|
||||||
|
generation++
|
||||||
|
operation {
|
||||||
|
var warning: String? = null
|
||||||
|
try { repository.logout(allDevices) }
|
||||||
|
catch (e: Exception) {
|
||||||
|
if (e is CancellationException) throw e
|
||||||
|
warning = "Místní přihlášení bylo smazáno. Server odhlášení nepotvrdil; přihlášení na serveru může ještě platit."
|
||||||
|
} finally {
|
||||||
|
sessionStore.clear()
|
||||||
|
repository = RemoteRepository(state.value.baseUrl, sessionStore)
|
||||||
|
state.update { AppState(booting = false, baseUrl = it.baseUrl, authMessage = warning) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun profile(update: ProfileUpdate) = operation {
|
||||||
|
val user = repository.updateProfile(update)
|
||||||
|
state.update { it.copy(user = user, message = "Profil byl uložen.") }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun load(route: String, refreshCatalogs: Boolean = false) {
|
||||||
|
currentRoute = route
|
||||||
|
loadJob?.cancel()
|
||||||
|
val sequence = ++loadSequence
|
||||||
|
loadJob = viewModelScope.launch {
|
||||||
|
val stamp = generation
|
||||||
|
state.update { it.copy(loading = true, error = null) }
|
||||||
|
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 {
|
||||||
|
route == "home" -> loadHome()
|
||||||
|
route == "issues" -> loadIssues(false)
|
||||||
|
route == "proposals" -> loadProposals(false)
|
||||||
|
route == "notices" -> loadNotices(false)
|
||||||
|
route == "new-issue" || route == "new-proposal" -> {
|
||||||
|
val catalogs = repository.catalogs()
|
||||||
|
state.update { it.copy(catalogs = catalogs) }
|
||||||
|
}
|
||||||
|
route.startsWith("edit-issue/") -> {
|
||||||
|
val catalogs = repository.catalogs()
|
||||||
|
val detail = repository.issue(route.substringAfter('/').toInt())
|
||||||
|
state.update { it.copy(catalogs = catalogs, issue = detail) }
|
||||||
|
}
|
||||||
|
route.startsWith("issue/") -> {
|
||||||
|
state.update { it.copy(issue = null) }
|
||||||
|
val detail = repository.issue(route.substringAfter('/').toInt())
|
||||||
|
state.update { it.copy(issue = detail) }
|
||||||
|
}
|
||||||
|
route.startsWith("proposal/") -> {
|
||||||
|
state.update { it.copy(proposal = null) }
|
||||||
|
val detail = repository.proposal(route.substringAfter('/').toInt())
|
||||||
|
state.update { it.copy(proposal = detail) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (e is CancellationException) throw e
|
||||||
|
if (stamp == generation && sequence == loadSequence) failure(e)
|
||||||
|
} finally {
|
||||||
|
if (stamp == generation && sequence == loadSequence) state.update { it.copy(loading = false) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun retry() = load(currentRoute, refreshCatalogs = true)
|
||||||
|
|
||||||
|
private suspend fun loadHome() = coroutineScope {
|
||||||
|
// Keep usable sections visible when another request temporarily fails.
|
||||||
|
val issues = async { runCatching { repository.issues() }.getOrThrowCancellation() }
|
||||||
|
val proposals = async { runCatching { repository.proposals() }.getOrThrowCancellation() }
|
||||||
|
val notices = async { runCatching { repository.notices() }.getOrThrowCancellation() }
|
||||||
|
val unread = async { runCatching { repository.unreadCount() }.getOrThrowCancellation() }
|
||||||
|
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 }
|
||||||
|
state.update { it.copy(
|
||||||
|
issues = i.getOrNull()?.items.orEmpty(), proposals = p.getOrNull()?.items.orEmpty(),
|
||||||
|
notices = n.getOrNull()?.items.orEmpty(),
|
||||||
|
unreadCount = u.getOrNull() ?: it.unreadCount,
|
||||||
|
error = listOfNotNull(i.exceptionOrNull(), p.exceptionOrNull(), n.exceptionOrNull(), u.exceptionOrNull()).firstOrNull()?.message,
|
||||||
|
) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun issueFilters(query: String = state.value.issueQuery, status: String? = state.value.issueStatus, assigned: Boolean = state.value.assigned) {
|
||||||
|
state.update { it.copy(issueQuery = query, issueStatus = status, assigned = assigned) }
|
||||||
|
load("issues")
|
||||||
|
}
|
||||||
|
fun proposalFilters(query: String = state.value.proposalQuery, sort: String = state.value.proposalSort) {
|
||||||
|
state.update { it.copy(proposalQuery = query, proposalSort = sort) }
|
||||||
|
load("proposals")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun more(kind: String) {
|
||||||
|
if (state.value.loading || state.value.busy) return
|
||||||
|
operation {
|
||||||
|
when (kind) { "issues" -> loadIssues(true); "proposals" -> loadProposals(true); "notices" -> loadNotices(true) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun loadIssues(append: Boolean) {
|
||||||
|
val s = state.value
|
||||||
|
val page = repository.issues(if (append) s.issuePage + 1 else 1, s.issueQuery, s.issueStatus, s.assigned)
|
||||||
|
state.update { it.copy(issues = (if (append) it.issues + page.items else page.items).distinctBy(Issue::id), issuePage = page.page, moreIssues = page.page * page.pageSize < page.totalCount) }
|
||||||
|
}
|
||||||
|
private suspend fun loadProposals(append: Boolean) {
|
||||||
|
val s = state.value
|
||||||
|
val page = repository.proposals(if (append) s.proposalPage + 1 else 1, s.proposalQuery, s.proposalSort)
|
||||||
|
state.update { it.copy(proposals = (if (append) it.proposals + page.items else page.items).distinctBy(Proposal::id), proposalPage = page.page, moreProposals = page.page * page.pageSize < page.totalCount) }
|
||||||
|
}
|
||||||
|
private suspend fun loadNotices(append: Boolean) {
|
||||||
|
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) }
|
||||||
|
val unread = repository.unreadCount()
|
||||||
|
state.update { it.copy(unreadCount = unread) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun createIssue(request: NewIssue, attachments: List<Upload>, onCreated: (Int) -> Unit) = operation {
|
||||||
|
val issue = repository.createIssue(request)
|
||||||
|
// Creation is committed before upload: never retry creation after a partial upload failure.
|
||||||
|
var uploadError: String? = null
|
||||||
|
if (attachments.isNotEmpty()) {
|
||||||
|
try { repository.addAttachments(issue.id, attachments) }
|
||||||
|
catch (e: Exception) { if (e is CancellationException) throw e; uploadError = e.message }
|
||||||
|
}
|
||||||
|
state.update { it.copy(message = if (uploadError == null) "Hlášení bylo odesláno." else "Hlášení #${issue.id} je uložené, přílohy se nepodařilo přidat: $uploadError. Přidejte je znovu v detailu.") }
|
||||||
|
onCreated(issue.id)
|
||||||
|
}
|
||||||
|
fun createProposal(request: NewProposal, onCreated: (Int) -> Unit) = operation {
|
||||||
|
val proposal = repository.createProposal(request)
|
||||||
|
state.update { it.copy(message = "Návrh byl odeslán.") }
|
||||||
|
onCreated(proposal.id)
|
||||||
|
}
|
||||||
|
fun updateIssue(id: Int, request: NewIssue, onSaved: () -> Unit) = operation {
|
||||||
|
val version = state.value.issue?.rowVersion ?: return@operation
|
||||||
|
try {
|
||||||
|
val latest = repository.updateIssue(id, request, version)
|
||||||
|
state.update { it.copy(issue = latest, message = "Hlášení bylo upraveno.") }
|
||||||
|
onSaved()
|
||||||
|
} catch (e: ApiException) {
|
||||||
|
if (e.status == 409) {
|
||||||
|
val latest = repository.issue(id)
|
||||||
|
state.update { it.copy(issue = latest) }
|
||||||
|
throw ApiException(409, "Hlášení mezitím upravil někdo jiný. Formulář byl obnoven aktuální verzí. Zkontrolujte jej a upravte znovu.")
|
||||||
|
}
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fun openAttachment(id: Int) = operation {
|
||||||
|
val upload = repository.downloadAttachment(id)
|
||||||
|
val context = getApplication<Application>()
|
||||||
|
val file = withContext(Dispatchers.IO) {
|
||||||
|
val directory = java.io.File(context.cacheDir, "shared").apply { mkdirs() }
|
||||||
|
// Discard all server-supplied path components before writing within the provider root.
|
||||||
|
val name = upload.name.substringAfterLast('/').substringAfterLast('\\')
|
||||||
|
.replace(Regex("[^\\p{L}\\p{N}._ -]"), "_").take(140).ifBlank { "priloha-$id" }
|
||||||
|
java.io.File(directory, "${id}_$name").also { it.writeBytes(upload.bytes) }
|
||||||
|
}
|
||||||
|
val uri = androidx.core.content.FileProvider.getUriForFile(context, "${context.packageName}.files", file)
|
||||||
|
val intent = android.content.Intent(android.content.Intent.ACTION_VIEW).apply {
|
||||||
|
setDataAndType(uri, upload.mimeType)
|
||||||
|
addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION or android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
}
|
||||||
|
try { context.startActivity(intent) }
|
||||||
|
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, onSaved: () -> Unit = {}) = operation {
|
||||||
|
repository.comment(id, text.trim())
|
||||||
|
onSaved()
|
||||||
|
refreshIssueAfterSave(id, "Komentář byl přidán.", "Komentář je uložený")
|
||||||
|
}
|
||||||
|
fun attachments(id: Int, uploads: List<Upload>, onSaved: () -> Unit = {}) = operation {
|
||||||
|
repository.addAttachments(id, uploads)
|
||||||
|
onSaved()
|
||||||
|
refreshIssueAfterSave(id, "Přílohy byly přidány.", "Přílohy jsou uložené")
|
||||||
|
}
|
||||||
|
private suspend fun refreshIssueAfterSave(id: Int, success: String, saved: String) {
|
||||||
|
state.update { it.copy(message = success) }
|
||||||
|
try {
|
||||||
|
val detail = repository.issue(id)
|
||||||
|
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 {
|
||||||
|
val detail = state.value.issue ?: return@operation
|
||||||
|
try { repository.issueAction(id, action, detail.rowVersion, reason.trim()) }
|
||||||
|
catch (e: ApiException) {
|
||||||
|
if (e.status == 409) {
|
||||||
|
val latest = repository.issue(id)
|
||||||
|
state.update { it.copy(issue = latest) }
|
||||||
|
}
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
val latest = repository.issue(id)
|
||||||
|
state.update { it.copy(issue = latest, message = "Stav hlášení byl aktualizován.") }
|
||||||
|
}
|
||||||
|
fun vote(id: Int, value: Int?) = operation {
|
||||||
|
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)
|
||||||
|
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 {
|
||||||
|
repository.readNotice(notice.id)
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
fun readAll() = operation {
|
||||||
|
repository.readAllNotices()
|
||||||
|
state.update { it.copy(notices = it.notices.map { n -> n.copy(isRead = true) }, unreadCount = 0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun failure(e: Exception) {
|
||||||
|
state.update { it.copy(error = e.message ?: "Operace se nezdařila. Zkuste to znovu.") }
|
||||||
|
if (e is ApiException && e.status == 401 && state.value.user != null) {
|
||||||
|
loadJob?.cancel()
|
||||||
|
generation++
|
||||||
|
sessionStore.clear()
|
||||||
|
state.update { AppState(booting = false, baseUrl = it.baseUrl, error = "Přihlášení vypršelo. Přihlaste se znovu.") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun operation(block: suspend () -> Unit) {
|
||||||
|
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 {
|
||||||
|
state.update { it.copy(busy = true, error = null, message = null, authMessage = null, authOutcome = null) }
|
||||||
|
try { block() }
|
||||||
|
catch (e: Exception) { if (e is CancellationException) throw e; failure(e) }
|
||||||
|
finally { state.update { it.copy(busy = false) } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <T> Result<T>.getOrThrowCancellation(): Result<T> {
|
||||||
|
(exceptionOrNull() as? CancellationException)?.let { throw it }
|
||||||
|
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()
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
package cz.ntbug.mobile.ui
|
||||||
|
|
||||||
|
import androidx.activity.compose.BackHandler
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.gestures.detectTapGestures
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||||
|
import androidx.compose.material.icons.outlined.*
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
|
import androidx.navigation.NavGraph.Companion.findStartDestination
|
||||||
|
import androidx.navigation.compose.*
|
||||||
|
import cz.ntbug.mobile.ui.features.*
|
||||||
|
|
||||||
|
private data class Tab(val route: String, val title: String, val icon: ImageVector)
|
||||||
|
private val tabs = listOf(
|
||||||
|
Tab("home", "Přehled", Icons.Outlined.Home), Tab("issues", "Hlášení", Icons.Outlined.Build),
|
||||||
|
Tab("proposals", "Nápady", Icons.Outlined.Lightbulb), Tab("notices", "Oznámení", Icons.Outlined.Notifications), Tab("profile", "Profil", Icons.Outlined.Person),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun NTBugApp(vm: AppViewModel = viewModel()) {
|
||||||
|
val s by vm.ui.collectAsStateWithLifecycle()
|
||||||
|
Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
|
||||||
|
if (s.booting) Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
|
||||||
|
else if (s.user == null) AccountScreen(s, vm)
|
||||||
|
else key(s.user!!.id, s.demo) { SignedInApp(s, vm) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
private fun SignedInApp(s: AppState, vm: AppViewModel) {
|
||||||
|
val user = s.user ?: return
|
||||||
|
val nav = rememberNavController()
|
||||||
|
val entry by nav.currentBackStackEntryAsState()
|
||||||
|
val routePattern = entry?.destination?.route ?: "home"
|
||||||
|
val id = entry?.arguments?.getString("id")
|
||||||
|
val route = routePattern.replace("{id}", id.orEmpty())
|
||||||
|
val mainTab = routePattern in tabs.map(Tab::route)
|
||||||
|
val snackbar = remember { SnackbarHostState() }
|
||||||
|
BackHandler(enabled = s.busy) { /* Finish the submitted operation before changing screens. */ }
|
||||||
|
LaunchedEffect(route) { vm.load(route) }
|
||||||
|
LaunchedEffect(s.message) { s.message?.let { snackbar.showSnackbar(it, duration = SnackbarDuration.Long); vm.dismissMessage() } }
|
||||||
|
fun open(route: String) { if (!s.busy) nav.navigate(route) { launchSingleTop = true } }
|
||||||
|
val title = when (routePattern) {
|
||||||
|
"home" -> "NTBug"; "new-issue" -> "Nové hlášení"; "issue/{id}" -> "Detail hlášení"; "edit-issue/{id}" -> "Upravit hlášení"
|
||||||
|
"new-proposal" -> "Nový nápad"; "proposal/{id}" -> "Detail nápadu"
|
||||||
|
else -> tabs.firstOrNull { it.route == routePattern }?.title ?: "NTBug"
|
||||||
|
}
|
||||||
|
Box(Modifier.fillMaxSize()) {
|
||||||
|
Scaffold(
|
||||||
|
containerColor = MaterialTheme.colorScheme.background,
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(title = { Column {
|
||||||
|
Text(title, fontWeight = FontWeight.Bold)
|
||||||
|
if (s.demo) Text("UKÁZKOVÝ REŽIM", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary)
|
||||||
|
} }, navigationIcon = {
|
||||||
|
if (!mainTab) IconButton(onClick = { nav.popBackStack() }, enabled = !s.busy) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, "Zpět") }
|
||||||
|
else if (routePattern == "home") Icon(Icons.Outlined.BugReport, null, Modifier.padding(start = 20.dp, end = 8.dp), tint = MaterialTheme.colorScheme.primary)
|
||||||
|
}, actions = {
|
||||||
|
if (routePattern != "profile") IconButton(onClick = vm::retry, enabled = !s.loading && !s.busy) { Icon(Icons.Outlined.Refresh, "Obnovit") }
|
||||||
|
}, colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.background))
|
||||||
|
},
|
||||||
|
bottomBar = {
|
||||||
|
if (mainTab) NavigationBar {
|
||||||
|
tabs.forEach { tab ->
|
||||||
|
NavigationBarItem(selected = routePattern == tab.route, enabled = !s.busy, onClick = {
|
||||||
|
nav.navigate(tab.route) {
|
||||||
|
popUpTo(nav.graph.findStartDestination().id) { saveState = true }
|
||||||
|
launchSingleTop = true; restoreState = true
|
||||||
|
}
|
||||||
|
}, icon = {
|
||||||
|
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)
|
||||||
|
}, label = { Text(tab.title, maxLines = 1) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
snackbarHost = { SnackbarHost(snackbar) },
|
||||||
|
) { padding ->
|
||||||
|
Column(Modifier.fillMaxSize().padding(padding)) {
|
||||||
|
if (s.loading) LinearProgressIndicator(Modifier.fillMaxWidth()) else Spacer(Modifier.height(4.dp))
|
||||||
|
if (s.error != null) {
|
||||||
|
Surface(color = MaterialTheme.colorScheme.errorContainer) {
|
||||||
|
Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp)) {
|
||||||
|
Text(s.error, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onErrorContainer)
|
||||||
|
Row {
|
||||||
|
TextButton(onClick = vm::retry, enabled = !s.loading) { Text("Zkusit znovu") }
|
||||||
|
TextButton(onClick = vm::clearFeedback) { Text("Zavřít") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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") }, unreadCount = s.unreadCount) }
|
||||||
|
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) }
|
||||||
|
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 || 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("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("proposal/{id}") { s.proposal?.let { proposal -> ProposalDetailScreen(proposal, user.id, s.busy || s.loading) { vm.vote(proposal.id, it) } } }
|
||||||
|
composable("notices") { NoticesScreen(s.notices, { notice -> vm.readNotice(notice) { when { notice.issueId != null -> nav.navigate("issue/${notice.issueId}"); notice.proposalId != null -> nav.navigate("proposal/${notice.proposalId}") } } }, vm::readAll, { vm.more("notices") }, s.moreNotices, unreadCount = s.unreadCount) }
|
||||||
|
composable("profile") { ProfileScreen(user, s, vm) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (s.busy) Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.12f)).pointerInput(Unit) { detectTapGestures { } }, contentAlignment = Alignment.Center) {
|
||||||
|
Surface(shape = MaterialTheme.shapes.large, tonalElevation = 8.dp) { Row(Modifier.padding(24.dp), horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically) { CircularProgressIndicator(Modifier.size(24.dp)); Text("Chvilku prosím…") } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package cz.ntbug.mobile.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.darkColorScheme
|
||||||
|
import androidx.compose.material3.lightColorScheme
|
||||||
|
import androidx.compose.material3.Typography
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
|
||||||
|
private val LightColors = lightColorScheme(
|
||||||
|
primary = Color(0xFF006B5C), onPrimary = Color.White,
|
||||||
|
primaryContainer = Color(0xFFD4F5E9), onPrimaryContainer = Color(0xFF00382E),
|
||||||
|
secondary = Color(0xFF49646E), secondaryContainer = Color(0xFFE0EDF2),
|
||||||
|
background = Color(0xFFF5F7F9), onBackground = Color(0xFF142E38),
|
||||||
|
surface = Color.White, onSurface = Color(0xFF142E38),
|
||||||
|
surfaceVariant = Color(0xFFE9EFF1), onSurfaceVariant = Color(0xFF53666F),
|
||||||
|
outline = Color(0xFF74868D), outlineVariant = Color(0xFFD9E3E7),
|
||||||
|
)
|
||||||
|
|
||||||
|
private val DarkColors = darkColorScheme(
|
||||||
|
primary = Color(0xFF67DCC3), onPrimary = Color(0xFF00382E),
|
||||||
|
primaryContainer = Color(0xFF005044), onPrimaryContainer = Color(0xFFADF2DE),
|
||||||
|
background = Color(0xFF0F2027), surface = Color(0xFF172D36),
|
||||||
|
surfaceVariant = Color(0xFF223E48), onSurfaceVariant = Color(0xFFBACCD2),
|
||||||
|
onBackground = Color(0xFFE2EDF1), onSurface = Color(0xFFE2EDF1),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun NTBugTheme(content: @Composable () -> Unit) {
|
||||||
|
MaterialTheme(
|
||||||
|
colorScheme = if (isSystemInDarkTheme()) DarkColors else LightColors,
|
||||||
|
typography = Typography(), content = content,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package cz.ntbug.mobile.ui.features
|
||||||
|
|
||||||
|
import android.net.Uri
|
||||||
|
import android.provider.OpenableColumns
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.rounded.*
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.core.content.FileProvider
|
||||||
|
import coil.compose.AsyncImage
|
||||||
|
import cz.ntbug.mobile.data.Upload
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
private const val MAX_FILE_SIZE = 10 * 1024 * 1024
|
||||||
|
private const val MAX_FILES = 5
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun AttachmentPicker(files: List<Upload>, onFilesChanged: (List<Upload>) -> Unit, enabled: Boolean = true, onReading: (Boolean) -> Unit = {}) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
var error by remember { mutableStateOf<String?>(null) }
|
||||||
|
var reading by remember { mutableStateOf(false) }
|
||||||
|
var cameraUri by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
|
var cameraPath by rememberSaveable { mutableStateOf<String?>(null) }
|
||||||
|
val onChange by rememberUpdatedState(onFilesChanged)
|
||||||
|
val currentFiles by rememberUpdatedState(files)
|
||||||
|
fun load(uris: List<Uri>, camera: Boolean = false) {
|
||||||
|
if (uris.isEmpty()) return
|
||||||
|
reading = true
|
||||||
|
onReading(true)
|
||||||
|
error = null
|
||||||
|
scope.launch {
|
||||||
|
val result = withContext(Dispatchers.IO) {
|
||||||
|
val available = (MAX_FILES - currentFiles.size).coerceAtLeast(0)
|
||||||
|
val accepted = mutableListOf<Upload>()
|
||||||
|
val problems = mutableListOf<String>()
|
||||||
|
if (uris.size > available) problems += "Najednou lze přiložit nejvýše $MAX_FILES souborů."
|
||||||
|
uris.take(available).forEach { uri ->
|
||||||
|
try {
|
||||||
|
accepted += readUpload(context, uri)
|
||||||
|
} catch (cancelled: CancellationException) {
|
||||||
|
throw cancelled
|
||||||
|
} catch (exception: Exception) {
|
||||||
|
problems += exception.message ?: "Soubor se nepodařilo načíst."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
accepted to problems
|
||||||
|
}
|
||||||
|
onChange((currentFiles + result.first).take(MAX_FILES))
|
||||||
|
error = result.second.distinct().joinToString("\n").takeIf { it.isNotEmpty() }
|
||||||
|
reading = false
|
||||||
|
onReading(false)
|
||||||
|
if (camera) {
|
||||||
|
cameraPath?.let { path -> runCatching { File(path).delete() } }
|
||||||
|
cameraPath = null
|
||||||
|
cameraUri = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val documents = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> load(uris) }
|
||||||
|
val camera = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { saved ->
|
||||||
|
val uri = cameraUri
|
||||||
|
if (saved && uri != null) load(listOf(Uri.parse(uri)), camera = true)
|
||||||
|
else {
|
||||||
|
cameraPath?.let { path -> runCatching { File(path).delete() } }
|
||||||
|
cameraPath = null
|
||||||
|
cameraUri = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
OutlinedButton(onClick = {
|
||||||
|
try {
|
||||||
|
error = null
|
||||||
|
val directory = File(context.cacheDir, "shared").apply { mkdirs() }
|
||||||
|
val photo = File.createTempFile("ntbug_foto_", ".jpg", directory)
|
||||||
|
val uri = FileProvider.getUriForFile(context, "${context.packageName}.files", photo)
|
||||||
|
cameraPath = photo.absolutePath
|
||||||
|
cameraUri = uri.toString()
|
||||||
|
camera.launch(uri)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
error = "Fotoaparát se nepodařilo otevřít. Zkuste vybrat fotografii ze souborů."
|
||||||
|
}
|
||||||
|
}, enabled = enabled && !reading && files.size < MAX_FILES, modifier = Modifier.weight(1f)) {
|
||||||
|
Icon(Icons.Rounded.PhotoCamera, null, Modifier.size(18.dp)); Spacer(Modifier.width(6.dp)); Text("Vyfotit")
|
||||||
|
}
|
||||||
|
OutlinedButton(onClick = {
|
||||||
|
try {
|
||||||
|
documents.launch(arrayOf("image/jpeg", "image/png", "image/heic", "application/pdf", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
|
||||||
|
} catch (_: Exception) {
|
||||||
|
error = "Výběr souborů se nepodařilo otevřít."
|
||||||
|
}
|
||||||
|
}, enabled = enabled && !reading && files.size < MAX_FILES, modifier = Modifier.weight(1f)) {
|
||||||
|
Icon(Icons.Rounded.AttachFile, null, Modifier.size(18.dp)); Spacer(Modifier.width(6.dp)); Text("Přiložit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Text("JPG, PNG, HEIC, PDF nebo DOCX · nejvýše 5 souborů po 10 MB", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
if (reading) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
||||||
|
files.forEachIndexed { index, upload ->
|
||||||
|
OutlinedCard(Modifier.fillMaxWidth(), shape = RoundedCornerShape(14.dp)) {
|
||||||
|
Row(Modifier.fillMaxWidth().padding(10.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
if (upload.mimeType.startsWith("image/")) AsyncImage(model = upload.bytes, contentDescription = upload.name, modifier = Modifier.size(48.dp))
|
||||||
|
else Icon(Icons.Rounded.Description, null, Modifier.size(36.dp), tint = MaterialTheme.colorScheme.primary)
|
||||||
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(upload.name, style = MaterialTheme.typography.bodyMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
Text(if (upload.bytes.size < 1024 * 1024) "${upload.bytes.size / 1024} kB" else String.format(Locale.forLanguageTag("cs-CZ"), "%.1f MB", upload.bytes.size / (1024f * 1024f)), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
IconButton(onClick = { onFilesChanged(files.filterIndexed { i, _ -> i != index }) }, enabled = enabled && !reading) { Icon(Icons.Rounded.Close, "Odebrat ${upload.name}") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun readUpload(context: android.content.Context, uri: Uri): Upload {
|
||||||
|
var name = uri.lastPathSegment?.substringAfterLast('/') ?: "priloha"
|
||||||
|
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { cursor ->
|
||||||
|
if (cursor.moveToFirst()) {
|
||||||
|
val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
|
||||||
|
if (nameIndex >= 0 && !cursor.isNull(nameIndex)) name = cursor.getString(nameIndex)
|
||||||
|
val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
|
||||||
|
if (sizeIndex >= 0 && !cursor.isNull(sizeIndex) && cursor.getLong(sizeIndex) > MAX_FILE_SIZE) throw IllegalArgumentException("$name: soubor je větší než 10 MB.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val extension = name.substringAfterLast('.', "").lowercase()
|
||||||
|
val extensionType = when (extension) {
|
||||||
|
"jpg", "jpeg" -> "image/jpeg"
|
||||||
|
"png" -> "image/png"
|
||||||
|
"heic" -> "image/heic"
|
||||||
|
"pdf" -> "application/pdf"
|
||||||
|
"docx" -> "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
// The server determines the format from the extension and verifies the file signature.
|
||||||
|
val type = extensionType ?: throw IllegalArgumentException("$name: tento typ souboru není podporován.")
|
||||||
|
val bytes = context.contentResolver.openInputStream(uri)?.use { input ->
|
||||||
|
val output = ByteArrayOutputStream()
|
||||||
|
val buffer = ByteArray(8192)
|
||||||
|
while (true) {
|
||||||
|
val count = input.read(buffer)
|
||||||
|
if (count < 0) break
|
||||||
|
if (output.size() + count > MAX_FILE_SIZE) throw IllegalArgumentException("$name: soubor je větší než 10 MB.")
|
||||||
|
output.write(buffer, 0, count)
|
||||||
|
}
|
||||||
|
output.toByteArray()
|
||||||
|
} ?: throw IllegalArgumentException("$name: soubor nelze otevřít.")
|
||||||
|
require(bytes.isNotEmpty()) { "$name: soubor je prázdný." }
|
||||||
|
return Upload(name, type, bytes)
|
||||||
|
}
|
||||||
@@ -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)"
|
||||||
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
package cz.ntbug.mobile.ui.features
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.rounded.ArrowForward
|
||||||
|
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.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import cz.ntbug.mobile.data.Issue
|
||||||
|
import cz.ntbug.mobile.data.Proposal
|
||||||
|
import java.time.Instant
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
internal val screenPadding = PaddingValues(start = 20.dp, end = 20.dp, top = 20.dp, bottom = 32.dp)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun SectionHeading(title: String, action: String? = null, onAction: () -> Unit = {}) {
|
||||||
|
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text(title, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f))
|
||||||
|
if (action != null) TextButton(onClick = onAction) {
|
||||||
|
Text(action)
|
||||||
|
Spacer(Modifier.width(4.dp))
|
||||||
|
Icon(Icons.AutoMirrored.Rounded.ArrowForward, contentDescription = null, modifier = Modifier.size(16.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun EmptyState(title: String, description: String, icon: ImageVector = Icons.Rounded.Inbox) {
|
||||||
|
OutlinedCard(Modifier.fillMaxWidth(), shape = RoundedCornerShape(20.dp)) {
|
||||||
|
Column(Modifier.fillMaxWidth().padding(28.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
Surface(color = MaterialTheme.colorScheme.secondaryContainer, shape = CircleShape) {
|
||||||
|
Icon(icon, null, modifier = Modifier.padding(14.dp).size(28.dp), tint = MaterialTheme.colorScheme.onSecondaryContainer)
|
||||||
|
}
|
||||||
|
Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||||
|
Text(description, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun statusLabel(status: String, isProposal: Boolean = false): String = when (status.uppercase()) {
|
||||||
|
"RECEIVED" -> "Přijata"
|
||||||
|
"ASSIGNED" -> "Přiřazena"
|
||||||
|
"IN_PROGRESS" -> "V řešení"
|
||||||
|
"PENDING_VERIFICATION" -> "K ověření"
|
||||||
|
"RESOLVED" -> "Vyřešena"
|
||||||
|
"REJECTED" -> if (isProposal) "Zamítnut" else "Zamítnuta"
|
||||||
|
"SUBMITTED" -> "Podán"
|
||||||
|
"UNDER_REVIEW" -> "V posouzení"
|
||||||
|
"ACCEPTED" -> "Přijat"
|
||||||
|
"IMPLEMENTED" -> "Realizován"
|
||||||
|
else -> status
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun StatusBadge(status: String, isProposal: Boolean = false) {
|
||||||
|
val tint = when (status.uppercase()) {
|
||||||
|
"ASSIGNED" -> Color(0xFF3267A0)
|
||||||
|
"IN_PROGRESS" -> Color(0xFF986015)
|
||||||
|
"PENDING_VERIFICATION", "UNDER_REVIEW" -> Color(0xFF7953A5)
|
||||||
|
"RESOLVED", "ACCEPTED", "IMPLEMENTED" -> Color(0xFF25725B)
|
||||||
|
"REJECTED" -> Color(0xFFAC3E42)
|
||||||
|
else -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
}
|
||||||
|
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)) {
|
||||||
|
Box(Modifier.size(5.dp).background(tint, CircleShape))
|
||||||
|
Text(statusLabel(status, isProposal), style = MaterialTheme.typography.labelMedium, color = tint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun IssueCard(issue: Issue, onClick: () -> Unit) {
|
||||||
|
OutlinedCard(onClick = onClick, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(20.dp)) {
|
||||||
|
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("#${issue.id} · ${issue.categoryName}", modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
StatusBadge(issue.status)
|
||||||
|
}
|
||||||
|
Text(issue.title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||||
|
val place = listOfNotNull(issue.buildingName?.takeIf { it.isNotBlank() }, issue.location.takeIf { it.isNotBlank() }).joinToString(" · ")
|
||||||
|
Text(place.ifBlank { "Místo není upřesněno" }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
Text(formatDate(issue.createdAt), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun ProposalCard(proposal: Proposal, onClick: () -> Unit, footer: @Composable (() -> Unit)? = null) {
|
||||||
|
OutlinedCard(onClick = onClick, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(20.dp)) {
|
||||||
|
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text(proposal.categoryName, modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
StatusBadge(proposal.status, isProposal = true)
|
||||||
|
}
|
||||||
|
Text(proposal.title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, 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(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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun LoadMoreButton(hasMore: Boolean, onLoadMore: () -> Unit) {
|
||||||
|
if (hasMore) OutlinedButton(onClick = onLoadMore, modifier = Modifier.fillMaxWidth()) { Text("Načíst další") }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun formatDate(value: String): String {
|
||||||
|
val formatter = DateTimeFormatter.ofPattern("d. M. yyyy · H:mm", Locale.forLanguageTag("cs-CZ"))
|
||||||
|
return runCatching { formatter.format(Instant.parse(value).atZone(ZoneId.systemDefault())) }.getOrElse {
|
||||||
|
runCatching { formatter.format(LocalDateTime.parse(value)) }.getOrDefault(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
internal fun <T> SelectionField(label: String, selected: T?, items: List<T>, itemLabel: (T) -> String, onSelect: (T) -> Unit, modifier: Modifier = Modifier, placeholder: String = "Vyberte možnost") {
|
||||||
|
var expanded by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(false) }
|
||||||
|
ExposedDropdownMenuBox(expanded = expanded, onExpandedChange = { expanded = !expanded }, modifier = modifier) {
|
||||||
|
OutlinedTextField(value = selected?.let(itemLabel).orEmpty(), onValueChange = {}, readOnly = true,
|
||||||
|
label = { Text(label) }, placeholder = { Text(placeholder) },
|
||||||
|
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
|
||||||
|
modifier = Modifier.fillMaxWidth().menuAnchor(MenuAnchorType.PrimaryNotEditable), singleLine = true)
|
||||||
|
ExposedDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
|
||||||
|
items.forEach { item -> DropdownMenuItem(text = { Text(itemLabel(item)) }, onClick = { onSelect(item); expanded = false }) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package cz.ntbug.mobile.ui.features
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.lifecycle.AndroidViewModel
|
||||||
|
import androidx.lifecycle.SavedStateHandle
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import cz.ntbug.mobile.data.Upload
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlinx.serialization.encodeToString
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import java.io.File
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
private data class DraftFile(val cacheName: String, val name: String, val mime: String)
|
||||||
|
|
||||||
|
/** One instance per navigation entry; saved state contains metadata, never file bytes. */
|
||||||
|
internal class DraftAttachmentsViewModel(application: Application, private val saved: SavedStateHandle) : AndroidViewModel(application) {
|
||||||
|
private val directory = File(application.cacheDir, "shared/drafts")
|
||||||
|
private var metadata = emptyList<DraftFile>()
|
||||||
|
var files by mutableStateOf<List<Upload>>(emptyList())
|
||||||
|
private set
|
||||||
|
var busy by mutableStateOf(false)
|
||||||
|
private set
|
||||||
|
var error by mutableStateOf<String?>(null)
|
||||||
|
private set
|
||||||
|
|
||||||
|
init {
|
||||||
|
val encoded: String? = saved["attachmentDraft"]
|
||||||
|
if (encoded != null) {
|
||||||
|
busy = true
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val restored = withContext(Dispatchers.IO) {
|
||||||
|
val records = Json.decodeFromString<List<DraftFile>>(encoded)
|
||||||
|
require(records.size <= 5)
|
||||||
|
records.map { record ->
|
||||||
|
record to runCatching {
|
||||||
|
require(record.cacheName.matches(Regex("[a-f0-9-]+\\.bin")))
|
||||||
|
val file = File(directory, record.cacheName)
|
||||||
|
require(file.isFile && file.length() in 1..(10 * 1024 * 1024).toLong())
|
||||||
|
Upload(record.name, record.mime, file.readBytes())
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
metadata = restored.filter { it.second != null }.map { it.first }
|
||||||
|
files = restored.mapNotNull { it.second }
|
||||||
|
saved["attachmentDraft"] = Json.encodeToString(metadata)
|
||||||
|
if (restored.any { it.second == null }) error = "Některé rozepsané přílohy už nejsou v úložišti. Vyberte je prosím znovu."
|
||||||
|
} catch (cancelled: CancellationException) {
|
||||||
|
throw cancelled
|
||||||
|
} catch (_: Exception) {
|
||||||
|
saved["attachmentDraft"] = "[]"
|
||||||
|
error = "Rozepsané přílohy se nepodařilo obnovit. Vyberte je prosím znovu."
|
||||||
|
} finally {
|
||||||
|
busy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun replace(selected: List<Upload>) {
|
||||||
|
if (busy) return
|
||||||
|
busy = true
|
||||||
|
error = null
|
||||||
|
viewModelScope.launch {
|
||||||
|
val old = metadata
|
||||||
|
val created = mutableListOf<DraftFile>()
|
||||||
|
try {
|
||||||
|
withContext(Dispatchers.IO) {
|
||||||
|
require(selected.size <= 5)
|
||||||
|
require(selected.all { it.bytes.isNotEmpty() && it.bytes.size <= 10 * 1024 * 1024 })
|
||||||
|
check(directory.isDirectory || directory.mkdirs())
|
||||||
|
selected.forEach { upload ->
|
||||||
|
val record = DraftFile("${UUID.randomUUID()}.bin", upload.name, upload.mimeType)
|
||||||
|
created += record
|
||||||
|
File(directory, record.cacheName).writeBytes(upload.bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
metadata = created.toList()
|
||||||
|
saved["attachmentDraft"] = Json.encodeToString(metadata)
|
||||||
|
files = selected.toList()
|
||||||
|
withContext(Dispatchers.IO) { old.forEach { File(directory, it.cacheName).delete() } }
|
||||||
|
} catch (cancelled: CancellationException) {
|
||||||
|
throw cancelled
|
||||||
|
} catch (_: Exception) {
|
||||||
|
error = "Přílohy se nepodařilo uložit do rozepsaného hlášení. Vyberte je prosím znovu."
|
||||||
|
} finally {
|
||||||
|
busy = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCleared() {
|
||||||
|
// Popping the entry abandons its draft; process death keeps cache files for restoration.
|
||||||
|
metadata.forEach { File(directory, it.cacheName).delete() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
package cz.ntbug.mobile.ui.features
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.rounded.Send
|
||||||
|
import androidx.compose.material.icons.rounded.*
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||||
|
import cz.ntbug.mobile.data.*
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun NewIssueScreen(catalogs: Catalogs, busy: Boolean, onSubmit: (NewIssue, List<Upload>) -> Unit) {
|
||||||
|
IssueForm(catalogs, busy, initial = null, onSubmit = onSubmit)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun EditIssueScreen(issue: Issue, catalogs: Catalogs, busy: Boolean, onSubmit: (NewIssue) -> Unit) {
|
||||||
|
key(issue.id, issue.rowVersion) {
|
||||||
|
IssueForm(catalogs, busy, initial = issue) { updated, _ -> onSubmit(updated) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun IssueForm(catalogs: Catalogs, busy: Boolean, initial: Issue?, onSubmit: (NewIssue, List<Upload>) -> Unit) {
|
||||||
|
var title by rememberSaveable(initial?.id) { mutableStateOf(initial?.title.orEmpty()) }
|
||||||
|
var description by rememberSaveable(initial?.id) { mutableStateOf(initial?.description.orEmpty()) }
|
||||||
|
var categoryId by rememberSaveable(initial?.id) { mutableIntStateOf(initial?.categoryId ?: -1) }
|
||||||
|
var buildingId by rememberSaveable(initial?.id) { mutableIntStateOf(initial?.buildingId ?: -1) }
|
||||||
|
var location by rememberSaveable(initial?.id) { mutableStateOf(initial?.location.orEmpty()) }
|
||||||
|
var showErrors by rememberSaveable { mutableStateOf(false) }
|
||||||
|
val draft: DraftAttachmentsViewModel = viewModel()
|
||||||
|
val files = draft.files
|
||||||
|
var readingFiles by remember { mutableStateOf(false) }
|
||||||
|
val categories = issueCategoryOptions(catalogs, initial)
|
||||||
|
val category = categories.find { it.id == categoryId }
|
||||||
|
val buildings = issueBuildingOptions(catalogs, initial)
|
||||||
|
val building = buildings.find { it.id == buildingId }
|
||||||
|
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()) {
|
||||||
|
item {
|
||||||
|
Text(if (initial == null) "Co je potřeba opravit?" else "Upravit hlášení", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
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 { SelectionField(label = "Kategorie *", selected = category, items = categories, itemLabel = ::categoryOptionLabel, onSelect = { categoryId = 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 = 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 {
|
||||||
|
Text("Fotografie a přílohy", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||||
|
Spacer(Modifier.height(10.dp))
|
||||||
|
AttachmentPicker(files, draft::replace, enabled = !busy && !draft.busy, onReading = { readingFiles = it })
|
||||||
|
if (draft.busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
draft.error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
||||||
|
}
|
||||||
|
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 i budovu, případně možnost Bez vazby na budovu.", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
||||||
|
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 && 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)
|
||||||
|
Spacer(Modifier.width(8.dp)); Text(if (busy) "Ukládání…" else if (initial == null) "Odeslat hlášení" else "Uložit změny")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
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 actionDialog by rememberSaveable(issue.id) { mutableStateOf<String?>(null) }
|
||||||
|
var reason by rememberSaveable(issue.id) { mutableStateOf("") }
|
||||||
|
val draft: DraftAttachmentsViewModel = viewModel()
|
||||||
|
val files = draft.files
|
||||||
|
var readingFiles by remember { mutableStateOf(false) }
|
||||||
|
val actions = issue.allowedActions.toSet()
|
||||||
|
val canComment = "COMMENT" in actions
|
||||||
|
val canAttach = "ADD_ATTACHMENTS" in actions
|
||||||
|
val supportedActions = issueActionEndpoints.filterKeys { it in actions }.values
|
||||||
|
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(20.dp), modifier = Modifier.fillMaxSize().imePadding()) {
|
||||||
|
item {
|
||||||
|
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("HLÁŠENÍ #${issue.id}", modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
StatusBadge(issue.status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item { Text(issue.title, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold) }
|
||||||
|
item {
|
||||||
|
OutlinedCard(Modifier.fillMaxWidth(), shape = RoundedCornerShape(20.dp)) {
|
||||||
|
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
DetailLine("Kategorie", issue.categoryName)
|
||||||
|
DetailLine("Místo", listOfNotNull(issue.buildingName, issue.location.takeIf { it.isNotBlank() }).joinToString(" · ").ifBlank { "Neuvedeno" })
|
||||||
|
DetailLine("Nahlásil/a", issue.reporterName.ifBlank { "Uživatel #${issue.reporterId}" })
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (issue.description.isNotBlank()) item { Text(issue.description, style = MaterialTheme.typography.bodyLarge) }
|
||||||
|
if ("EDIT" in actions) item {
|
||||||
|
OutlinedButton(onClick = onEdit, enabled = !busy, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Icon(Icons.Rounded.Edit, null, modifier = Modifier.size(18.dp))
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Text("Upravit hlášení")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (supportedActions.isNotEmpty()) item {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
Text("Další krok", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||||
|
supportedActions.forEach { action ->
|
||||||
|
OutlinedButton(onClick = {
|
||||||
|
if (action in listOf("reopen", "reject", "submit-for-verification")) { actionDialog = action; reason = "" }
|
||||||
|
else onAction(action, "")
|
||||||
|
}, enabled = !busy, modifier = Modifier.fillMaxWidth()) { Text(actionLabel(action)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (issue.attachments.isNotEmpty()) item {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
Text("Přílohy", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||||
|
issue.attachments.forEach { file ->
|
||||||
|
TextButton(onClick = { onAttachment(file) }, enabled = !busy, modifier = Modifier.fillMaxWidth(), contentPadding = PaddingValues(vertical = 8.dp)) {
|
||||||
|
Icon(Icons.Rounded.Download, null, modifier = Modifier.size(20.dp))
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Text(file.fileName, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||||
|
Icon(Icons.Rounded.OpenInNew, contentDescription = "Otevřít přílohu", modifier = Modifier.size(16.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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) }
|
||||||
|
items(issue.events, key = { it.id }) { event ->
|
||||||
|
TimelineEventCard(event.authorName, event.type, event.text, event.createdAt, event.fromStatus, event.toStatus)
|
||||||
|
}
|
||||||
|
if (canComment) item {
|
||||||
|
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))
|
||||||
|
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 {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
Text("Doplnit přílohy", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||||
|
AttachmentPicker(files, draft::replace, enabled = !busy && !draft.busy, onReading = { readingFiles = it })
|
||||||
|
if (draft.busy) LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||||
|
draft.error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
||||||
|
if (files.isNotEmpty()) Button(onClick = { onAttachments(files) { draft.replace(emptyList()) } }, enabled = !busy && !readingFiles && !draft.busy, modifier = Modifier.fillMaxWidth()) { Text("Nahrát přílohy") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
actionDialog?.let { action ->
|
||||||
|
val required = action == "reopen" || action == "reject"
|
||||||
|
AlertDialog(onDismissRequest = { actionDialog = null }, title = { Text(actionLabel(action)) }, text = {
|
||||||
|
OutlinedTextField(value = reason, onValueChange = { reason = it.take(5000) }, label = { Text(if (required) "Důvod *" else "Poznámka (nepovinná)") }, minLines = 3, maxLines = 8, keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences))
|
||||||
|
}, confirmButton = { TextButton(onClick = { actionDialog = null; onAction(action, reason.trim()) }, enabled = !busy && (!required || reason.isNotBlank())) { Text("Potvrdit") } }, dismissButton = { TextButton(onClick = { actionDialog = null }) { Text("Zrušit") } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun DetailLine(label: String, value: String) {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||||
|
Text(label, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
Text(value, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun actionLabel(action: String): String = when (action) {
|
||||||
|
"start" -> "Zahájit řešení"
|
||||||
|
"submit-for-verification" -> "Předat k ověření"
|
||||||
|
"confirm" -> "Potvrdit vyřešení"
|
||||||
|
"reopen" -> "Znovu otevřít závadu"
|
||||||
|
"reject" -> "Zamítnout závadu"
|
||||||
|
else -> action
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Server action codes are distinct from the URL paths used by action requests. */
|
||||||
|
private val issueActionEndpoints = linkedMapOf(
|
||||||
|
"START_WORK" to "start",
|
||||||
|
"SUBMIT_FOR_VERIFICATION" to "submit-for-verification",
|
||||||
|
"CONFIRM" to "confirm",
|
||||||
|
"REOPEN" to "reopen",
|
||||||
|
"REJECT" to "reject",
|
||||||
|
)
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
package cz.ntbug.mobile.ui.features
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.horizontalScroll
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.automirrored.rounded.ArrowForward
|
||||||
|
import androidx.compose.material.icons.rounded.*
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import cz.ntbug.mobile.data.*
|
||||||
|
|
||||||
|
@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, unreadCount: Int = notices.count { !it.isRead }) {
|
||||||
|
val myIssues = issues.filter { it.reporterId == user.id }
|
||||||
|
val openIssues = myIssues.filter { it.status !in listOf("RESOLVED", "REJECTED") }
|
||||||
|
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(18.dp), modifier = Modifier.fillMaxSize()) {
|
||||||
|
item {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||||
|
Text("VÁŠ UNIVERZITNÍ HELPDESK", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary, letterSpacing = 1.4.sp)
|
||||||
|
Text("Ahoj, ${user.firstName}.", style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold)
|
||||||
|
Text("Lepší univerzita začíná u vás.", style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
Surface(color = Color(0xFF163D35), contentColor = Color(0xFFF4FBF5), shape = RoundedCornerShape(24.dp)) {
|
||||||
|
Column(Modifier.fillMaxWidth().padding(24.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) {
|
||||||
|
Surface(color = Color(0xFF31554B), shape = RoundedCornerShape(12.dp)) {
|
||||||
|
Icon(Icons.Rounded.Build, null, tint = Color(0xFFC9E6B9), modifier = Modifier.padding(12.dp).size(24.dp))
|
||||||
|
}
|
||||||
|
Text("Něco nefunguje?\nDejte nám vědět.", style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.SemiBold)
|
||||||
|
Text("Vyfoťte závadu, přidejte místo a sledujte její řešení na jednom místě.", style = MaterialTheme.typography.bodyMedium, color = Color(0xFFD4E6DF))
|
||||||
|
Button(onClick = onNewIssue, colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFCEE9BB), contentColor = Color(0xFF173C32)), modifier = Modifier.fillMaxWidth(), contentPadding = PaddingValues(14.dp)) {
|
||||||
|
Icon(Icons.Rounded.Add, null)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Text("Nahlásit závadu", fontWeight = FontWeight.Bold)
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
Icon(Icons.AutoMirrored.Rounded.ArrowForward, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
|
MetricCard(openIssues.size.toString(), "Otevřená v přehledu", Modifier.weight(1f))
|
||||||
|
MetricCard(unreadCount.toString(), "Nepřečtená oznámení", Modifier.weight(1f))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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) }
|
||||||
|
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) } }
|
||||||
|
item { SectionHeading("Nápady pro univerzitu", "Všechny", onAllProposals) }
|
||||||
|
if (proposals.isEmpty()) item { EmptyState("Prostor pro nové nápady", "Podělte se o to, co by na univerzitě mohlo fungovat lépe.", Icons.Rounded.Lightbulb) }
|
||||||
|
items(proposals.sortedByDescending { it.score }.take(2), key = { "proposal-${it.id}" }) { proposal -> ProposalCard(proposal, onClick = { onProposal(proposal.id) }) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun MetricCard(value: String, label: String, modifier: Modifier) {
|
||||||
|
OutlinedCard(modifier, shape = RoundedCornerShape(20.dp)) {
|
||||||
|
Column(Modifier.padding(18.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
Text(value, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary)
|
||||||
|
Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun IssuesScreen(issues: List<Issue>, query: String, status: String?, assigned: Boolean, canResolve: Boolean, onQuery: (String) -> Unit, onStatus: (String?) -> Unit, onAssigned: (Boolean) -> Unit, onOpen: (Int) -> Unit, onCreate: () -> Unit, onLoadMore: () -> Unit, hasMore: Boolean) {
|
||||||
|
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxSize()) {
|
||||||
|
item {
|
||||||
|
SectionHeading(if (assigned) "Přiřazené závady" else "Moje hlášení")
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
Button(onClick = onCreate, modifier = Modifier.fillMaxWidth()) { Icon(Icons.Rounded.Add, null); Spacer(Modifier.width(8.dp)); Text("Nahlásit závadu") }
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
OutlinedTextField(value = query, onValueChange = onQuery, modifier = Modifier.fillMaxWidth(), placeholder = { Text("Hledat v hlášeních") }, leadingIcon = { Icon(Icons.Rounded.Search, null) }, singleLine = true, shape = RoundedCornerShape(16.dp), trailingIcon = { if (query.isNotEmpty()) IconButton(onClick = { onQuery("") }) { Icon(Icons.Rounded.Close, "Vymazat hledání") } })
|
||||||
|
}
|
||||||
|
if (canResolve) item {
|
||||||
|
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
FilterChip(selected = !assigned, onClick = { onAssigned(false) }, label = { Text("Moje hlášení") })
|
||||||
|
FilterChip(selected = assigned, onClick = { onAssigned(true) }, label = { Text("Přiřazené mně") })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
FilterChip(selected = status == null, onClick = { onStatus(null) }, label = { Text("Všechny stavy") })
|
||||||
|
listOf("RECEIVED", "ASSIGNED", "IN_PROGRESS", "PENDING_VERIFICATION", "RESOLVED", "REJECTED").forEach { code ->
|
||||||
|
FilterChip(selected = status == code, onClick = { onStatus(if (status == code) null else code) }, label = { Text(statusLabel(code)) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (issues.isEmpty()) item { EmptyState("Žádná hlášení k zobrazení", if (query.isNotBlank() || status != null) "Zkuste jiné hledání nebo změňte filtr." else "Až nahlásíte závadu, najdete zde její stav i komunikaci.", Icons.Rounded.FactCheck) }
|
||||||
|
items(issues, key = { it.id }) { issue -> IssueCard(issue) { onOpen(issue.id) } }
|
||||||
|
item { LoadMoreButton(hasMore, onLoadMore) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
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()) {
|
||||||
|
item { SectionHeading("Oznámení") }
|
||||||
|
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) }
|
||||||
|
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))) {
|
||||||
|
Row(Modifier.padding(18.dp), horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.Top) {
|
||||||
|
Box(Modifier.padding(top = 7.dp).size(8.dp).background(if (notice.isRead) MaterialTheme.colorScheme.outlineVariant else MaterialTheme.colorScheme.primary, CircleShape))
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(7.dp)) {
|
||||||
|
Text(notice.title, style = MaterialTheme.typography.titleMedium, fontWeight = if (notice.isRead) FontWeight.Medium else FontWeight.Bold)
|
||||||
|
Text(notice.text, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
Text(formatDate(notice.createdAt), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item { LoadMoreButton(hasMore, onLoadMore) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
package cz.ntbug.mobile.ui.features
|
||||||
|
|
||||||
|
import androidx.compose.foundation.horizontalScroll
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.rounded.*
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.input.KeyboardCapitalization
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import cz.ntbug.mobile.data.*
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ProposalsScreen(proposals: List<Proposal>, userId: Int, query: String, sort: String, onQuery: (String) -> Unit, onSort: (String) -> Unit, onOpen: (Int) -> Unit, onVote: (Int, Int?) -> Unit, onCreate: () -> Unit, onLoadMore: () -> Unit, hasMore: Boolean) {
|
||||||
|
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxSize()) {
|
||||||
|
item {
|
||||||
|
SectionHeading("Návrhy na zlepšení")
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
Text("Malé nápady. Lepší místo ke studiu.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
Button(onClick = onCreate, modifier = Modifier.fillMaxWidth()) { Icon(Icons.Rounded.Add, null); Spacer(Modifier.width(8.dp)); Text("Přidat návrh") }
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
OutlinedTextField(value = query, onValueChange = onQuery, modifier = Modifier.fillMaxWidth(), placeholder = { Text("Hledat návrhy") }, singleLine = true, leadingIcon = { Icon(Icons.Rounded.Search, null) }, shape = RoundedCornerShape(16.dp), trailingIcon = { if (query.isNotEmpty()) IconButton(onClick = { onQuery("") }) { Icon(Icons.Rounded.Close, "Vymazat hledání") } })
|
||||||
|
}
|
||||||
|
item {
|
||||||
|
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
FilterChip(selected = sort == "score", onClick = { onSort("score") }, label = { Text("Nejpodporovanější") }, leadingIcon = { Icon(Icons.Rounded.TrendingUp, null, Modifier.size(18.dp)) })
|
||||||
|
FilterChip(selected = sort == "newest", onClick = { onSort("newest") }, label = { Text("Nejnovější") }, leadingIcon = { Icon(Icons.Rounded.Schedule, null, Modifier.size(18.dp)) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (proposals.isEmpty()) item { EmptyState("Žádné návrhy k zobrazení", if (query.isNotBlank()) "Zkuste změnit hledaný výraz." else "Máte nápad na zlepšení? Přidejte první návrh.", Icons.Rounded.Lightbulb) }
|
||||||
|
items(proposals, key = { it.id }) { proposal ->
|
||||||
|
ProposalCard(proposal, onClick = { onOpen(proposal.id) }) {
|
||||||
|
VoteControls(proposal, userId, onVote = { onVote(proposal.id, it) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item { LoadMoreButton(hasMore, onLoadMore) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ProposalDetailScreen(proposal: Proposal, userId: Int, busy: Boolean, onVote: (Int?) -> Unit) {
|
||||||
|
LazyColumn(contentPadding = screenPadding, verticalArrangement = Arrangement.spacedBy(20.dp), modifier = Modifier.fillMaxSize()) {
|
||||||
|
item {
|
||||||
|
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("NÁVRH #${proposal.id}", modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
StatusBadge(proposal.status, isProposal = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item { Text(proposal.title, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold) }
|
||||||
|
item {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
|
||||||
|
Text(proposal.categoryName, style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary)
|
||||||
|
Text(listOf(proposal.authorName.takeIf { it.isNotBlank() }, formatDate(proposal.createdAt)).filterNotNull().joinToString(" · "), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (proposal.description.isNotBlank()) item { Text(proposal.description, style = MaterialTheme.typography.bodyLarge) }
|
||||||
|
item {
|
||||||
|
OutlinedCard(Modifier.fillMaxWidth(), shape = RoundedCornerShape(20.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)
|
||||||
|
VoteControls(proposal, userId, enabled = !busy, onVote = onVote)
|
||||||
|
Text(votingExplanation(proposal, userId), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 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 {
|
||||||
|
Card(colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer), shape = RoundedCornerShape(20.dp)) {
|
||||||
|
Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
|
Text("Vyjádření vedení", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold)
|
||||||
|
Text(note, style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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
|
||||||
|
private fun VoteControls(proposal: Proposal, userId: Int, enabled: Boolean = true, onVote: (Int?) -> Unit) {
|
||||||
|
val votingOpen = proposal.status in openVotingStatuses
|
||||||
|
val canVote = enabled && proposal.authorId != userId && votingOpen
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
FilterChip(selected = proposal.myVote == 1, onClick = { if (canVote) onVote(if (proposal.myVote == 1) null else 1) }, enabled = canVote,
|
||||||
|
label = { Text("Pro") }, leadingIcon = { Icon(Icons.Rounded.ThumbUp, null, Modifier.size(16.dp)) })
|
||||||
|
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)) })
|
||||||
|
Spacer(Modifier.weight(1f))
|
||||||
|
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
|
||||||
|
fun NewProposalScreen(catalogs: Catalogs, busy: Boolean, onSubmit: (NewProposal) -> Unit) {
|
||||||
|
var title by rememberSaveable { mutableStateOf("") }
|
||||||
|
var description by rememberSaveable { mutableStateOf("") }
|
||||||
|
var categoryId by rememberSaveable { mutableIntStateOf(-1) }
|
||||||
|
var showErrors by rememberSaveable { mutableStateOf(false) }
|
||||||
|
val categories = proposalCategoryOptions(catalogs)
|
||||||
|
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()) {
|
||||||
|
item {
|
||||||
|
Text("Máte nápad?", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
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 {
|
||||||
|
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 (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) }
|
||||||
|
item {
|
||||||
|
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)
|
||||||
|
Spacer(Modifier.width(8.dp)); Text(if (busy) "Odesílání…" else "Odeslat návrh")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="48dp" android:height="48dp" android:viewportWidth="48" android:viewportHeight="48">
|
||||||
|
<path android:fillColor="#102C36" android:pathData="M0,0h48v48h-48z" />
|
||||||
|
<path android:fillColor="#57DFC5" android:pathData="M12,12h6l12,17v-17h6v24h-6l-12,-17v17h-6z" />
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<resources>
|
||||||
|
<string name="app_name">NTBug</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<resources>
|
||||||
|
<style name="Theme.NTBug" parent="android:style/Theme.Material.Light.NoActionBar">
|
||||||
|
<item name="android:fontFamily">sans</item>
|
||||||
|
<item name="android:windowLightStatusBar">true</item>
|
||||||
|
<item name="android:windowActionModeOverlay">true</item>
|
||||||
|
<item name="android:windowBackground">#F5F7F9</item>
|
||||||
|
</style>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<data-extraction-rules>
|
||||||
|
<cloud-backup>
|
||||||
|
<exclude domain="root" path="." />
|
||||||
|
<exclude domain="file" path="." />
|
||||||
|
<exclude domain="database" path="." />
|
||||||
|
<exclude domain="sharedpref" path="." />
|
||||||
|
<exclude domain="external" path="." />
|
||||||
|
</cloud-backup>
|
||||||
|
<device-transfer>
|
||||||
|
<exclude domain="root" path="." />
|
||||||
|
<exclude domain="file" path="." />
|
||||||
|
<exclude domain="database" path="." />
|
||||||
|
<exclude domain="sharedpref" path="." />
|
||||||
|
<exclude domain="external" path="." />
|
||||||
|
</device-transfer>
|
||||||
|
</data-extraction-rules>
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<cache-path name="shared_photos" path="shared/" />
|
||||||
|
</paths>
|
||||||
@@ -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 }
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class DemoRepositoryTest {
|
||||||
|
@Test fun `vote can be changed removed and never duplicated`() = runBlocking {
|
||||||
|
val repository = DemoRepository()
|
||||||
|
val initial = repository.proposal(21).score
|
||||||
|
repository.vote(21, 1)
|
||||||
|
repository.vote(21, 1)
|
||||||
|
assertEquals(initial + 1, repository.proposal(21).score)
|
||||||
|
repository.vote(21, -1)
|
||||||
|
assertEquals(initial - 1, repository.proposal(21).score)
|
||||||
|
repository.vote(21, null)
|
||||||
|
assertEquals(initial, repository.proposal(21).score)
|
||||||
|
assertNull(repository.proposal(21).myVote)
|
||||||
|
try { repository.vote(23, 1); fail("Own proposal must reject votes") } catch (error: ApiException) { assertEquals(403, error.status) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `confirm closes issue while stale version and later comments are rejected`() = runBlocking {
|
||||||
|
val repository = DemoRepository()
|
||||||
|
val before = repository.issue(103)
|
||||||
|
try { repository.issueAction(before.id, "confirm", before.rowVersion - 1); fail("Stale version must fail") } catch (error: ApiException) { assertEquals(409, error.status) }
|
||||||
|
repository.issueAction(before.id, "confirm", before.rowVersion)
|
||||||
|
assertEquals("RESOLVED", repository.issue(before.id).status)
|
||||||
|
assertTrue(repository.issue(before.id).allowedActions.isEmpty())
|
||||||
|
try { repository.comment(before.id, "Hello"); fail("Closed issue must reject comments") } catch (error: ApiException) { assertEquals(403, error.status) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `reopening requires reason and records event`() = runBlocking {
|
||||||
|
val repository = DemoRepository()
|
||||||
|
val issue = repository.issue(103)
|
||||||
|
try { repository.issueAction(issue.id, "reopen", issue.rowVersion); fail("Reason is required") } catch (_: IllegalArgumentException) { }
|
||||||
|
repository.issueAction(issue.id, "reopen", issue.rowVersion, "Světlo stále nefunguje.")
|
||||||
|
val reopened = repository.issue(issue.id)
|
||||||
|
assertEquals("IN_PROGRESS", reopened.status)
|
||||||
|
assertEquals("Světlo stále nefunguje.", reopened.events.last().text)
|
||||||
|
assertEquals(issue.rowVersion + 1, reopened.rowVersion)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `new issue persists within demo session and notifications can be marked read`() = runBlocking {
|
||||||
|
val repository = DemoRepository()
|
||||||
|
val unreadBefore = repository.unreadCount()
|
||||||
|
val created = repository.createIssue(NewIssue("Rozbitá židle", "Ulomená noha židle", 5, 1, "A-101"))
|
||||||
|
assertEquals(created, repository.issue(created.id))
|
||||||
|
assertEquals("RECEIVED", created.status)
|
||||||
|
assertTrue(repository.issues(query = "židle").items.any { it.id == created.id })
|
||||||
|
assertTrue(repository.notices().items.any { !it.isRead && it.issueId == created.id })
|
||||||
|
assertEquals(unreadBefore + 1, repository.unreadCount())
|
||||||
|
repository.readAllNotices()
|
||||||
|
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`() {
|
||||||
|
val file = Upload("photo.jpg", "image/jpeg", byteArrayOf(1))
|
||||||
|
validateUploads(listOf(file))
|
||||||
|
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(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 {
|
||||||
|
val repository = DemoRepository()
|
||||||
|
val initial = repository.issue(102)
|
||||||
|
val update = NewIssue("Upravená klika", "Je u vstupu do studovny.", 5, 3, "Přízemí")
|
||||||
|
try { repository.updateIssue(102, update, initial.rowVersion - 1); fail("Stale version must fail") } catch (error: ApiException) { assertEquals(409, error.status) }
|
||||||
|
val edited = repository.updateIssue(102, update, initial.rowVersion)
|
||||||
|
assertEquals(update.title, edited.title)
|
||||||
|
assertEquals(initial.rowVersion + 1, edited.rowVersion)
|
||||||
|
assertEquals("UPDATED", edited.events.last().type)
|
||||||
|
try { repository.updateIssue(104, update, repository.issue(104).rowVersion); fail("In-progress edit must fail") } catch (error: ApiException) { assertEquals(403, error.status) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `demo attachments retain bytes and ids are unique across issues`() = runBlocking {
|
||||||
|
val repository = DemoRepository()
|
||||||
|
val first = Upload("first.png", "image/png", byteArrayOf(1, 2))
|
||||||
|
repository.addAttachments(102, listOf(first))
|
||||||
|
repository.addAttachments(103, listOf(Upload("second.png", "image/png", byteArrayOf(3))))
|
||||||
|
val firstId = repository.issue(102).attachments.single().id
|
||||||
|
val secondId = repository.issue(103).attachments.single().id
|
||||||
|
assertNotEquals(firstId, secondId)
|
||||||
|
assertArrayEquals(first.bytes, repository.downloadAttachment(firstId).bytes)
|
||||||
|
assertArrayEquals(byteArrayOf(3), repository.downloadAttachment(secondId).bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import okhttp3.mockwebserver.Dispatcher
|
||||||
|
import okhttp3.mockwebserver.MockResponse
|
||||||
|
import okhttp3.mockwebserver.MockWebServer
|
||||||
|
import okhttp3.mockwebserver.RecordedRequest
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
|
||||||
|
class MutableCatalogContractTest {
|
||||||
|
private lateinit var server: MockWebServer
|
||||||
|
private lateinit var repository: RemoteRepository
|
||||||
|
|
||||||
|
@Before fun setup() {
|
||||||
|
server = MockWebServer().apply { start() }
|
||||||
|
repository = RemoteRepository(server.url("/").toString(), object : SessionPersistence {
|
||||||
|
private var session: AuthSession? = AuthSession("access", "2099-01-01T00:00:00Z", "refresh", "2099-02-01T00:00:00Z",
|
||||||
|
User(1, "[email protected]", "Jana", "Nováková", role = "STUDENT"))
|
||||||
|
override fun read() = session
|
||||||
|
override fun write(session: AuthSession) { this.session = session }
|
||||||
|
override fun clear() { session = null }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
@After fun teardown() { server.shutdown() }
|
||||||
|
|
||||||
|
@Test fun `explicit refresh picks up renamed new and deactivated categories without reloading per row`() = runBlocking {
|
||||||
|
val revision = AtomicInteger()
|
||||||
|
server.dispatcher = object : Dispatcher() {
|
||||||
|
override fun dispatch(request: RecordedRequest): MockResponse {
|
||||||
|
assertEquals("Bearer access", request.getHeader("Authorization"))
|
||||||
|
// Ordinary catalog access must not request administrator-only inactive rows.
|
||||||
|
assertNull(request.requestUrl!!.queryParameter("includeInactive"))
|
||||||
|
return when (request.requestUrl!!.encodedPath) {
|
||||||
|
"/api/buildings" -> json(buildings(if (revision.get() == 0) "Budova A" else "Hlavní budova"))
|
||||||
|
"/api/issue-categories" -> json(if (revision.get() == 0)
|
||||||
|
"""[{"id":1,"name":"Technika","isActive":true},{"id":2,"name":"Stará kategorie","isActive":true}]"""
|
||||||
|
else """[{"id":1,"name":"Technické vybavení","isActive":true},{"id":5,"name":"Nová kategorie","isActive":true}]""")
|
||||||
|
"/api/proposal-categories" -> json(if (revision.get() == 0)
|
||||||
|
"""[{"id":3,"name":"Prostředí","isActive":true}]"""
|
||||||
|
else """[{"id":4,"name":"Výuka","isActive":true}]""")
|
||||||
|
else -> MockResponse().setResponseCode(404)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val original = repository.catalogs()
|
||||||
|
revision.set(1)
|
||||||
|
assertSame(original, repository.catalogs())
|
||||||
|
assertEquals(3, server.requestCount)
|
||||||
|
|
||||||
|
val updated = repository.catalogs(refresh = true)
|
||||||
|
assertEquals("Hlavní budova", updated.buildings.single().name)
|
||||||
|
assertEquals("Technické vybavení", updated.issueCategories.first { it.id == 1 }.name)
|
||||||
|
assertEquals(setOf(1, 5), updated.issueCategories.map { it.id }.toSet())
|
||||||
|
assertEquals(listOf(4), updated.proposalCategories.map { it.id })
|
||||||
|
assertSame(updated, repository.catalogs())
|
||||||
|
assertEquals(6, server.requestCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `failed refresh does not replace any part of the previously complete catalog`() = runBlocking {
|
||||||
|
val failing = AtomicBoolean(false)
|
||||||
|
server.dispatcher = object : Dispatcher() {
|
||||||
|
override fun dispatch(request: RecordedRequest): MockResponse = when (request.requestUrl!!.encodedPath) {
|
||||||
|
"/api/buildings" -> json(buildings(if (failing.get()) "Nový název" else "Budova A"))
|
||||||
|
"/api/issue-categories" -> if (failing.get()) MockResponse().setResponseCode(503)
|
||||||
|
else json("""[{"id":1,"name":"Technika","isActive":true}]""")
|
||||||
|
"/api/proposal-categories" -> json("""[{"id":3,"name":"Prostředí","isActive":true}]""")
|
||||||
|
else -> MockResponse().setResponseCode(404)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val original = repository.catalogs()
|
||||||
|
failing.set(true)
|
||||||
|
try {
|
||||||
|
repository.catalogs(refresh = true)
|
||||||
|
fail("Expected service failure")
|
||||||
|
} catch (error: ApiException) { assertEquals(503, error.status) }
|
||||||
|
val cached = repository.catalogs()
|
||||||
|
assertSame(original, cached)
|
||||||
|
assertEquals("Budova A", cached.buildings.single().name)
|
||||||
|
assertEquals("Technika", cached.issueCategories.single().name)
|
||||||
|
assertEquals(5, server.requestCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildings(name: String) = """[{"id":1,"code":"A","name":"$name","isActive":true}]"""
|
||||||
|
private fun json(value: String) = MockResponse().setHeader("Content-Type", "application/json").setBody(value)
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import okhttp3.mockwebserver.MockResponse
|
||||||
|
import okhttp3.mockwebserver.MockWebServer
|
||||||
|
import org.junit.After
|
||||||
|
import org.junit.Assert.*
|
||||||
|
import org.junit.Before
|
||||||
|
import org.junit.Test
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class RegistrationDeliveryContractTest {
|
||||||
|
private lateinit var server: MockWebServer
|
||||||
|
private lateinit var repository: RemoteRepository
|
||||||
|
private var session: AuthSession? = null
|
||||||
|
|
||||||
|
@Before fun setup() {
|
||||||
|
server = MockWebServer().apply { start() }
|
||||||
|
repository = RemoteRepository(server.url("/").toString(), object : SessionPersistence {
|
||||||
|
override fun read() = session
|
||||||
|
override fun write(session: AuthSession) { this@RegistrationDeliveryContractTest.session = session }
|
||||||
|
override fun clear() { session = null }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
@After fun teardown() { server.shutdown() }
|
||||||
|
|
||||||
|
@Test fun `failed email delivery is shown without retry and same registration can be manually resent`() = runBlocking {
|
||||||
|
val message = "E-mail se nepodařilo odeslat. Zkuste požadavek později."
|
||||||
|
server.enqueue(json("""{"status":503,"title":"$message"}""").setResponseCode(503))
|
||||||
|
try {
|
||||||
|
register()
|
||||||
|
fail("Expected email delivery failure")
|
||||||
|
} catch (error: ApiException) {
|
||||||
|
assertEquals(503, error.status)
|
||||||
|
assertEquals(message, error.message)
|
||||||
|
}
|
||||||
|
val failed = server.takeRequest()
|
||||||
|
assertEquals("/api/auth/register", failed.path)
|
||||||
|
assertEquals("POST", failed.method)
|
||||||
|
val failedBody = failed.body.readUtf8()
|
||||||
|
assertNull(server.takeRequest(100, TimeUnit.MILLISECONDS))
|
||||||
|
assertNull(session)
|
||||||
|
|
||||||
|
server.enqueue(json("""{"id":1,"email":"[email protected]","firstName":"Jana","lastName":"Nováková","role":"STUDENT","emailNotificationsEnabled":true}""").setResponseCode(201))
|
||||||
|
register()
|
||||||
|
val repeated = server.takeRequest()
|
||||||
|
assertEquals("/api/auth/register", repeated.path)
|
||||||
|
assertEquals(failedBody, repeated.body.readUtf8())
|
||||||
|
assertEquals(2, server.requestCount)
|
||||||
|
assertNull("Registration must not sign in an unverified account", session)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `service failure without problem details has a Czech fallback`() = runBlocking {
|
||||||
|
server.enqueue(MockResponse().setResponseCode(503))
|
||||||
|
try {
|
||||||
|
register()
|
||||||
|
fail("Expected service failure")
|
||||||
|
} catch (error: ApiException) {
|
||||||
|
assertEquals(503, error.status)
|
||||||
|
assertEquals("Služba je dočasně nedostupná. Zkuste požadavek později.", error.message)
|
||||||
|
}
|
||||||
|
assertEquals(1, server.requestCount)
|
||||||
|
assertNull(session)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun register() = repository.register("[email protected]", "test-password", "Jana", "Nováková")
|
||||||
|
private fun json(value: String) = MockResponse().setHeader("Content-Type", "application/json").setBody(value)
|
||||||
|
}
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
package cz.ntbug.mobile.data
|
||||||
|
|
||||||
|
import kotlinx.coroutines.async
|
||||||
|
import kotlinx.coroutines.awaitAll
|
||||||
|
import kotlinx.coroutines.cancelAndJoin
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.coroutines.withTimeout
|
||||||
|
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 okio.Buffer
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
class RepositoryTest {
|
||||||
|
private lateinit var server: MockWebServer
|
||||||
|
private lateinit var store: MemorySessionStore
|
||||||
|
private lateinit var repository: RemoteRepository
|
||||||
|
|
||||||
|
@Before fun setup() {
|
||||||
|
server = MockWebServer().apply { start() }
|
||||||
|
store = MemorySessionStore()
|
||||||
|
repository = RemoteRepository(server.url("/").toString(), store)
|
||||||
|
}
|
||||||
|
@After fun teardown() { server.shutdown() }
|
||||||
|
|
||||||
|
@Test fun `login matches server contract and persists session without storing password`() = runBlocking {
|
||||||
|
server.enqueue(json(sessionJson()))
|
||||||
|
val user = repository.login(" [email protected] ", "test-password")
|
||||||
|
val request = server.takeRequest()
|
||||||
|
assertEquals("/api/auth/login", request.path)
|
||||||
|
assertEquals("POST", request.method)
|
||||||
|
assertEquals("{\"email\":\"[email protected]\",\"password\":\"test-password\"}", request.body.readUtf8())
|
||||||
|
assertNull(request.getHeader("Authorization"))
|
||||||
|
assertEquals("Jana", user.firstName)
|
||||||
|
assertEquals("old-access", store.session?.accessToken)
|
||||||
|
assertEquals("old-refresh", store.session?.refreshToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `concurrent unauthorized calls rotate refresh token only once`() = runBlocking {
|
||||||
|
val refreshes = AtomicInteger()
|
||||||
|
server.dispatcher = object : Dispatcher() {
|
||||||
|
override fun dispatch(request: RecordedRequest): MockResponse = when (request.path?.substringBefore('?')) {
|
||||||
|
"/api/auth/login" -> json(sessionJson())
|
||||||
|
"/api/auth/refresh" -> {
|
||||||
|
refreshes.incrementAndGet()
|
||||||
|
assertTrue(request.body.readUtf8().contains("old-refresh"))
|
||||||
|
json(sessionJson("new-access", "new-refresh"))
|
||||||
|
}
|
||||||
|
"/api/issues" -> if (request.getHeader("Authorization") == "Bearer new-access") json(emptyPage) else MockResponse().setResponseCode(401)
|
||||||
|
else -> MockResponse().setResponseCode(404)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
repository.login("[email protected]", "password")
|
||||||
|
val results = listOf(async { repository.issues() }, async { repository.issues() }, async { repository.issues() }).awaitAll()
|
||||||
|
assertTrue(results.all { it.items.isEmpty() })
|
||||||
|
assertEquals(1, refreshes.get())
|
||||||
|
assertEquals("new-refresh", store.session?.refreshToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `missing resource preserves server problem details and does not imply unsupported backend`() = runBlocking {
|
||||||
|
server.enqueue(json(sessionJson()))
|
||||||
|
repository.login("[email protected]", "password")
|
||||||
|
server.enqueue(json("""{"status":404,"title":"Závada neexistuje."}""").setResponseCode(404))
|
||||||
|
val error = expectApiError { repository.issue(987) }
|
||||||
|
assertEquals(404, error.status)
|
||||||
|
assertEquals("Závada neexistuje.", error.message)
|
||||||
|
assertFalse(error.message!!.contains("Backend musí doplnit API"))
|
||||||
|
assertNotNull(store.session)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `screen cancellation cannot lose rotated refresh token`() = runBlocking {
|
||||||
|
val refreshes = AtomicInteger()
|
||||||
|
server.dispatcher = object : Dispatcher() {
|
||||||
|
override fun dispatch(request: RecordedRequest): MockResponse = when (request.path?.substringBefore('?')) {
|
||||||
|
"/api/auth/login" -> json(sessionJson())
|
||||||
|
"/api/auth/refresh" -> {
|
||||||
|
refreshes.incrementAndGet()
|
||||||
|
json(sessionJson("new-access", "new-refresh")).setBodyDelay(250, TimeUnit.MILLISECONDS)
|
||||||
|
}
|
||||||
|
"/api/issues" -> if (request.getHeader("Authorization") == "Bearer new-access") json(emptyPage) else MockResponse().setResponseCode(401)
|
||||||
|
else -> MockResponse().setResponseCode(404)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
repository.login("[email protected]", "password")
|
||||||
|
val request = launch { repository.issues() }
|
||||||
|
withTimeout(3000) { while (refreshes.get() == 0) delay(10) }
|
||||||
|
request.cancelAndJoin()
|
||||||
|
assertEquals("new-refresh", store.session?.refreshToken)
|
||||||
|
assertTrue(repository.issues().items.isEmpty())
|
||||||
|
assertEquals(1, refreshes.get())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `validation problem details display field errors`() = runBlocking {
|
||||||
|
server.enqueue(json("""{"status":400,"title":"Neplatná vstupní data.","errors":{"password":["Heslo je příliš krátké."],"email":["Neplatný e-mail."]}}""").setResponseCode(400))
|
||||||
|
val error = expectApiError { repository.register("bad", "x", "Jana", "Nováková") }
|
||||||
|
assertEquals(400, error.status)
|
||||||
|
assertTrue(error.message!!.contains("Heslo je příliš krátké."))
|
||||||
|
assertTrue(error.message!!.contains("Neplatný e-mail."))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `expired refresh clears credentials rather than retrying consumed token`() = runBlocking {
|
||||||
|
server.enqueue(json(sessionJson()))
|
||||||
|
repository.login("[email protected]", "password")
|
||||||
|
server.enqueue(MockResponse().setResponseCode(401))
|
||||||
|
server.enqueue(MockResponse().setResponseCode(401))
|
||||||
|
assertEquals(401, expectApiError { repository.issues() }.status)
|
||||||
|
assertNull(store.session)
|
||||||
|
assertNull(repository.restoreUser())
|
||||||
|
assertEquals(3, server.requestCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `logout clears local session even when server rejects revocation`() = runBlocking {
|
||||||
|
server.enqueue(json(sessionJson()))
|
||||||
|
repository.login("[email protected]", "password")
|
||||||
|
server.enqueue(MockResponse().setResponseCode(403))
|
||||||
|
expectApiError { repository.logout() }
|
||||||
|
assertNull(store.session)
|
||||||
|
assertNull(repository.restoreUser())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `base URL handles origin and api prefix and rejects credentials`() {
|
||||||
|
assertEquals("https://school.cz/api/", normalizeBaseUrl(" https://school.cz/ "))
|
||||||
|
assertEquals("http://10.0.2.2:8080/api/", normalizeBaseUrl("http://10.0.2.2:8080/api"))
|
||||||
|
assertEquals("https://school.cz/helpdesk/api/", normalizeBaseUrl("https://school.cz/helpdesk"))
|
||||||
|
try { normalizeBaseUrl("https://user:[email protected]"); fail("Credentials must not be accepted") } catch (_: IllegalArgumentException) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `attachment download sends authorization decodes filename and preserves bytes`() = runBlocking {
|
||||||
|
server.enqueue(json(sessionJson()))
|
||||||
|
repository.login("[email protected]", "password")
|
||||||
|
server.takeRequest()
|
||||||
|
server.enqueue(MockResponse().setHeader("Content-Type", "image/png").setHeader("Content-Disposition", "attachment; filename*=UTF-8''fotka%20z%C3%A1vady.png").setBody(Buffer().write(byteArrayOf(1, 2, 3))))
|
||||||
|
val file = repository.downloadAttachment(8)
|
||||||
|
assertEquals("fotka závady.png", file.name)
|
||||||
|
assertEquals("image/png", file.mimeType)
|
||||||
|
assertArrayEquals(byteArrayOf(1, 2, 3), file.bytes)
|
||||||
|
val request = server.takeRequest()
|
||||||
|
assertEquals("/api/attachments/8", request.path)
|
||||||
|
assertEquals("Bearer old-access", request.getHeader("Authorization"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test fun `chunked attachment download rejects more than ten megabytes`() = runBlocking {
|
||||||
|
server.enqueue(json(sessionJson()))
|
||||||
|
repository.login("[email protected]", "password")
|
||||||
|
server.enqueue(MockResponse().setHeader("Content-Type", "image/jpeg").setChunkedBody(Buffer().write(ByteArray(10 * 1024 * 1024 + 1)), 8192))
|
||||||
|
assertEquals(413, expectApiError { repository.downloadAttachment(8) }.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun expectApiError(block: suspend () -> Unit): ApiException {
|
||||||
|
try { block() } catch (error: ApiException) { return error }
|
||||||
|
throw AssertionError("Expected ApiException")
|
||||||
|
}
|
||||||
|
private fun json(value: String) = MockResponse().setHeader("Content-Type", "application/json").setBody(value)
|
||||||
|
private fun sessionJson(access: String = "old-access", refresh: String = "old-refresh") = """{"accessToken":"$access","accessTokenExpiresAt":"2099-01-01T00:00:00Z","refreshToken":"$refresh","refreshTokenExpiresAt":"2099-02-01T00:00:00Z","user":{"id":1,"email":"[email protected]","firstName":"Jana","lastName":"Nováková","phone":null,"role":"STUDENT","emailNotificationsEnabled":true}}"""
|
||||||
|
private val emptyPage = """{"items":[],"totalCount":0,"page":1,"pageSize":20}"""
|
||||||
|
}
|
||||||
|
|
||||||
|
private class MemorySessionStore : SessionPersistence {
|
||||||
|
var session: AuthSession? = null
|
||||||
|
override fun read() = session
|
||||||
|
override fun write(session: AuthSession) { this.session = session }
|
||||||
|
override fun clear() { session = null }
|
||||||
|
}
|
||||||
@@ -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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
plugins {
|
||||||
|
id("com.android.application") version "8.13.2" apply false
|
||||||
|
id("org.jetbrains.kotlin.android") version "2.1.20" apply false
|
||||||
|
id("org.jetbrains.kotlin.plugin.compose") version "2.1.20" apply false
|
||||||
|
id("org.jetbrains.kotlin.plugin.serialization") version "2.1.20" apply false
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
org.gradle.jvmargs=-Xmx3g -Dfile.encoding=UTF-8
|
||||||
|
android.useAndroidX=true
|
||||||
|
kotlin.code.style=official
|
||||||
|
android.nonTransitiveRClass=true
|
||||||
BIN
Binary file not shown.
@@ -0,0 +1,7 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
+251
@@ -0,0 +1,251 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015-2021 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-classpath "$CLASSPATH" \
|
||||||
|
org.gradle.wrapper.GradleWrapperMain \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
Vendored
+94
@@ -0,0 +1,94 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dependencyResolutionManagement {
|
||||||
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rootProject.name = "NTBug"
|
||||||
|
include(":app")
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
<Project>
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net10.0</TargetFramework>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<LangVersion>latest</LangVersion>
|
|
||||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
|
||||||
<!-- Web zobrazuje data a čísla česky (cs-CZ), proto plná podpora kultur. -->
|
|
||||||
<InvariantGlobalization>false</InvariantGlobalization>
|
|
||||||
</PropertyGroup>
|
|
||||||
</Project>
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
<Project>
|
|
||||||
<PropertyGroup>
|
|
||||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
|
||||||
</PropertyGroup>
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageVersion Include="Swashbuckle.AspNetCore.SwaggerUI" Version="10.3.1" />
|
|
||||||
<!-- Testy -->
|
|
||||||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
|
|
||||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
|
||||||
<PackageVersion Include="xunit.v3" Version="4.0.2" />
|
|
||||||
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
|
|
||||||
</ItemGroup>
|
|
||||||
</Project>
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
# Vícefázový build webové aplikace. Kontext sestavení = kořen repozitáře.
|
|
||||||
# docker build -f web/Dockerfile .
|
|
||||||
|
|
||||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
|
||||||
WORKDIR /src
|
|
||||||
# Nejdřív jen projektové soubory – restore se cachuje, dokud se nezmění závislosti.
|
|
||||||
COPY web/Directory.Build.props web/Directory.Packages.props ./
|
|
||||||
COPY web/Helpdesk.Web/Helpdesk.Web.csproj Helpdesk.Web/
|
|
||||||
RUN dotnet restore Helpdesk.Web/Helpdesk.Web.csproj
|
|
||||||
COPY web/Helpdesk.Web/ Helpdesk.Web/
|
|
||||||
RUN dotnet publish Helpdesk.Web/Helpdesk.Web.csproj -c Release -o /out --no-restore
|
|
||||||
|
|
||||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
|
||||||
WORKDIR /app
|
|
||||||
COPY --from=build /out .
|
|
||||||
# Klíče Data Protection (šifrování autentizační cookie) – v Compose je tu volume web-keys.
|
|
||||||
RUN mkdir -p /app/keys && chown "$APP_UID" /app/keys
|
|
||||||
USER $APP_UID
|
|
||||||
ENV ASPNETCORE_HTTP_PORTS=8080 \
|
|
||||||
DataProtection__KeysPath=/app/keys
|
|
||||||
EXPOSE 8080
|
|
||||||
ENTRYPOINT ["dotnet", "Helpdesk.Web.dll"]
|
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Security.Claims;
|
|
||||||
using System.Text;
|
|
||||||
using Helpdesk.Web.Api;
|
|
||||||
using Helpdesk.Web.Auth;
|
|
||||||
using Helpdesk.Web.Infrastructure;
|
|
||||||
using Helpdesk.Web.Models;
|
|
||||||
using Microsoft.AspNetCore.Authentication;
|
|
||||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
|
||||||
|
|
||||||
namespace Helpdesk.Web.Tests;
|
|
||||||
|
|
||||||
public class AuthCookieTests
|
|
||||||
{
|
|
||||||
private static readonly TokenSet Tokens = new(
|
|
||||||
"access", new DateTimeOffset(2026, 12, 1, 10, 15, 0, TimeSpan.Zero),
|
|
||||||
"refresh", new DateTimeOffset(2026, 12, 15, 10, 0, 0, TimeSpan.Zero));
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Tokeny_ulozene_v_cookie_se_prectou_zpet()
|
|
||||||
{
|
|
||||||
var properties = new AuthenticationProperties();
|
|
||||||
AuthCookie.StoreTokens(properties, Tokens);
|
|
||||||
|
|
||||||
Assert.Equal(Tokens, AuthCookie.ReadTokens(properties));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Trvale_prihlaseni_plati_stejne_dlouho_jako_refresh_token()
|
|
||||||
{
|
|
||||||
var properties = new AuthenticationProperties { IsPersistent = true };
|
|
||||||
AuthCookie.StoreTokens(properties, Tokens);
|
|
||||||
|
|
||||||
Assert.Equal(Tokens.RefreshTokenExpiresAt, properties.ExpiresUtc);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Cookie_bez_tokenu_neni_platna() => Assert.Null(AuthCookie.ReadTokens(new AuthenticationProperties()));
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Identita_nese_roli_pro_IsInRole()
|
|
||||||
{
|
|
||||||
var principal = AuthCookie.CreatePrincipal(new UserDto(7, "[email protected]", "Eva", "Malá", null, UserRoles.Management, true));
|
|
||||||
|
|
||||||
Assert.True(principal.IsInRole(UserRoles.Management));
|
|
||||||
Assert.Equal("Eva Malá", principal.Identity!.Name);
|
|
||||||
Assert.Equal("7", principal.FindFirst(ClaimTypes.NameIdentifier)!.Value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public class ApiExceptionTests
|
|
||||||
{
|
|
||||||
private static HttpResponseMessage Problem(HttpStatusCode status, string json) => new(status)
|
|
||||||
{
|
|
||||||
Content = new StringContent(json, Encoding.UTF8, "application/problem+json"),
|
|
||||||
};
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Validacni_chyby_z_ProblemDetails_se_nactou_podle_poli()
|
|
||||||
{
|
|
||||||
using var response = Problem(HttpStatusCode.BadRequest,
|
|
||||||
"""{"title":"Neplatná vstupní data.","status":400,"errors":{"password":["Heslo je příliš krátké."]}}""");
|
|
||||||
|
|
||||||
var error = await ApiException.FromResponseAsync(response, CancellationToken.None);
|
|
||||||
|
|
||||||
Assert.Equal(HttpStatusCode.BadRequest, error.StatusCode);
|
|
||||||
Assert.Equal("Neplatná vstupní data.", error.UserMessage);
|
|
||||||
Assert.Equal(["Heslo je příliš krátké."], error.Errors["Password"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Odpoved_bez_tela_ma_srozumitelnou_zpravu()
|
|
||||||
{
|
|
||||||
using var response = new HttpResponseMessage(HttpStatusCode.TooManyRequests);
|
|
||||||
|
|
||||||
var error = await ApiException.FromResponseAsync(response, CancellationToken.None);
|
|
||||||
|
|
||||||
Assert.Equal("Příliš mnoho pokusů. Zkuste to prosím za minutu.", error.UserMessage);
|
|
||||||
Assert.Empty(error.Errors);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Poskozeny_JSON_nezpusobi_vyjimku()
|
|
||||||
{
|
|
||||||
using var response = Problem(HttpStatusCode.InternalServerError, "{nejde o json");
|
|
||||||
|
|
||||||
var error = await ApiException.FromResponseAsync(response, CancellationToken.None);
|
|
||||||
|
|
||||||
Assert.Equal(HttpStatusCode.InternalServerError, error.StatusCode);
|
|
||||||
Assert.Null(error.Title);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public class ModelStateExtensionsTests
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public void Chyba_pole_z_API_patri_k_vlastnosti_formulare()
|
|
||||||
{
|
|
||||||
var modelState = new ModelStateDictionary();
|
|
||||||
var error = new ApiException(HttpStatusCode.BadRequest, "Neplatná vstupní data.",
|
|
||||||
new Dictionary<string, string[]> { ["newPassword"] = ["Heslo musí mít alespoň 8 znaků."] });
|
|
||||||
|
|
||||||
modelState.AddApiErrors(error, typeof(ResetPasswordViewModel));
|
|
||||||
|
|
||||||
Assert.Equal("Heslo musí mít alespoň 8 znaků.", modelState[nameof(ResetPasswordViewModel.NewPassword)]!.Errors.Single().ErrorMessage);
|
|
||||||
Assert.False(modelState.ContainsKey(string.Empty));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Chyba_bez_pole_jde_do_souhrnu()
|
|
||||||
{
|
|
||||||
var modelState = new ModelStateDictionary();
|
|
||||||
var error = new ApiException(HttpStatusCode.Conflict, "Účet s tímto e-mailem už existuje.", new Dictionary<string, string[]>());
|
|
||||||
|
|
||||||
modelState.AddApiErrors(error, typeof(RegisterViewModel));
|
|
||||||
|
|
||||||
Assert.Equal("Účet s tímto e-mailem už existuje.", modelState[string.Empty]!.Errors.Single().ErrorMessage);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public class NavigationTests
|
|
||||||
{
|
|
||||||
private static ClaimsPrincipal UserWithRole(string role) =>
|
|
||||||
new(new ClaimsIdentity([new Claim(ClaimTypes.Role, role)], "test"));
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Neprihlaseny_uzivatel_menu_nevidi() =>
|
|
||||||
Assert.Empty(Navigation.For(new ClaimsPrincipal(new ClaimsIdentity())));
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Polozka_s_roli_je_videt_jen_te_roli()
|
|
||||||
{
|
|
||||||
var item = new NavItem("Statistiky", "Statistics", "Index", UserRoles.Management);
|
|
||||||
|
|
||||||
Assert.True(item.IsVisibleTo(UserWithRole(UserRoles.Management)));
|
|
||||||
Assert.False(item.IsVisibleTo(UserWithRole(UserRoles.Student)));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Polozka_bez_roli_je_videt_vsem_prihlasenym() =>
|
|
||||||
Assert.True(new NavItem("Nástěnka", "Home", "Index").IsVisibleTo(UserWithRole(UserRoles.Student)));
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using Helpdesk.Web.Api;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
|
|
||||||
namespace Helpdesk.Web.Tests;
|
|
||||||
|
|
||||||
public sealed class ForwardedClientIpHandlerTests
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public async Task UsesTheCurrentConnectionAddressInsteadOfTheIncomingHeader()
|
|
||||||
{
|
|
||||||
const string header = "X-Forwarded-For";
|
|
||||||
var context = new DefaultHttpContext();
|
|
||||||
context.Connection.RemoteIpAddress = IPAddress.Parse("198.51.100.10");
|
|
||||||
context.Request.Headers[header] = "203.0.113.11";
|
|
||||||
var accessor = new HttpContextAccessor { HttpContext = context };
|
|
||||||
using var client = new HttpMessageInvoker(new ForwardedClientIpHandler(accessor) { InnerHandler = new Responder() });
|
|
||||||
using var request = new HttpRequestMessage(HttpMethod.Post, "http://api-web:8080/api/v1/auth/login");
|
|
||||||
using var response = await client.SendAsync(request, TestContext.Current.CancellationToken);
|
|
||||||
Assert.Equal("198.51.100.10", Assert.Single(request.Headers.GetValues(header)));
|
|
||||||
|
|
||||||
accessor.HttpContext = null;
|
|
||||||
using var next = new HttpRequestMessage(HttpMethod.Post, request.RequestUri);
|
|
||||||
using var nextResponse = await client.SendAsync(next, TestContext.Current.CancellationToken);
|
|
||||||
Assert.False(next.Headers.Contains(header));
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class Responder : HttpMessageHandler
|
|
||||||
{
|
|
||||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
|
||||||
Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<IsPackable>false</IsPackable>
|
|
||||||
<OutputType>Exe</OutputType>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
|
||||||
<ProjectReference Include="..\Helpdesk.Web\Helpdesk.Web.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
|
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
|
||||||
<PackageReference Include="xunit.v3" />
|
|
||||||
<PackageReference Include="xunit.runner.visualstudio" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Using Include="Xunit" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
@@ -1,174 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Net.Http.Headers;
|
|
||||||
using System.Text;
|
|
||||||
using System.Text.Json.Nodes;
|
|
||||||
using Helpdesk.Web.Api;
|
|
||||||
using Helpdesk.Web.Models;
|
|
||||||
|
|
||||||
namespace Helpdesk.Web.Tests;
|
|
||||||
|
|
||||||
public class IssueDetailViewModelTests
|
|
||||||
{
|
|
||||||
private static readonly DateTimeOffset T = DateTimeOffset.UnixEpoch;
|
|
||||||
|
|
||||||
private static IssueEventDto Event(string type, string? from, string to, string actor, string? note = null) =>
|
|
||||||
new(1, type, from, to, 1, actor, note, T);
|
|
||||||
|
|
||||||
private static IssueDetailViewModel Model(int? assigneeId, params IssueEventDto[] events) => new()
|
|
||||||
{
|
|
||||||
Issue = new IssueDetail(42, "Projektor", "Bliká.", 2, null, null, "IN_PROGRESS", "HIGH", 5, assigneeId, T, 3,
|
|
||||||
[IssueActions.SubmitForVerification, IssueActions.Reject, IssueActions.Comment], []),
|
|
||||||
Events = events,
|
|
||||||
CategoryName = "Technické vybavení",
|
|
||||||
};
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Jmena_hlasice_a_resitele_vezme_z_casove_osy()
|
|
||||||
{
|
|
||||||
var model = Model(7,
|
|
||||||
Event("CREATED", null, "RECEIVED", "Jan Novák"),
|
|
||||||
Event("ASSIGNED", "RECEIVED", "ASSIGNED", "Vedení Školy", "Petr Svoboda"),
|
|
||||||
Event("ASSIGNED", "ASSIGNED", "ASSIGNED", "Vedení Školy", "Eva Malá"));
|
|
||||||
|
|
||||||
Assert.Equal("Jan Novák", model.ReporterName);
|
|
||||||
Assert.Equal("Eva Malá", model.AssigneeName); // po přeřazení platí poslední přiřazení
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Nepriprazena_zavada_nema_resitele() => Assert.Null(Model(null, Event("CREATED", null, "RECEIVED", "Jan")).AssigneeName);
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Akce_zmeny_stavu_jsou_jen_povolene_a_v_poradi_zivotniho_cyklu() =>
|
|
||||||
Assert.Equal([IssueActions.SubmitForVerification, IssueActions.Reject], Model(7).Transitions);
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("CREATED", null, "RECEIVED", null, "nahlásil/a závadu", null)]
|
|
||||||
[InlineData("ASSIGNED", "RECEIVED", "ASSIGNED", "Petr Svoboda", "přiřadil/a závadu řešiteli Petr Svoboda", null)]
|
|
||||||
[InlineData("ASSIGNED", "IN_PROGRESS", "ASSIGNED", "Eva Malá", "přeřadil/a závadu na Eva Malá", null)]
|
|
||||||
[InlineData("STATUS_CHANGED", "ASSIGNED", "IN_PROGRESS", null, "zahájil/a řešení", null)]
|
|
||||||
[InlineData("STATUS_CHANGED", "PENDING_VERIFICATION", "IN_PROGRESS", "Pořád bliká", "znovu otevřel/a závadu", "Důvod")]
|
|
||||||
[InlineData("STATUS_CHANGED", "IN_PROGRESS", "PENDING_VERIFICATION", "Vyměněna lampa", "předal/a závadu k ověření", "Poznámka")]
|
|
||||||
[InlineData("STATUS_CHANGED", "IN_PROGRESS", "REJECTED", "Duplicitní hlášení", "zamítl/a závadu", "Důvod")]
|
|
||||||
[InlineData("COMMENTED", null, "IN_PROGRESS", "Funguje HDMI?", "napsal/a komentář", null)]
|
|
||||||
public void Udalost_casove_osy_ma_srozumitelny_popis(string type, string? from, string to, string? note, string text, string? noteLabel)
|
|
||||||
{
|
|
||||||
var entry = TimelineEntry.From(Event(type, from, to, "Někdo", note));
|
|
||||||
|
|
||||||
Assert.Equal(text, entry.Text);
|
|
||||||
Assert.Equal(noteLabel, entry.NoteLabel);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Komentar_nema_stitek_stavu()
|
|
||||||
{
|
|
||||||
var entry = TimelineEntry.From(Event("COMMENTED", null, "IN_PROGRESS", "Jan", "Funguje HDMI?"));
|
|
||||||
|
|
||||||
Assert.True(entry.IsComment);
|
|
||||||
Assert.Null(entry.Status);
|
|
||||||
Assert.Equal("Funguje HDMI?", entry.Note);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData(900, "900 B")]
|
|
||||||
[InlineData(300_000, "293 kB")]
|
|
||||||
[InlineData(2_500_000, "2,4 MB")]
|
|
||||||
public void Velikost_prilohy_je_citelna(long bytes, string expected) =>
|
|
||||||
Assert.Equal(expected, IssueDetailViewModel.FileSize(bytes).Replace('.', ','));
|
|
||||||
}
|
|
||||||
|
|
||||||
public class IssueActionsApiTests
|
|
||||||
{
|
|
||||||
[Theory]
|
|
||||||
[InlineData(IssueActions.StartWork, null, "/api/v1/issues/42/start", """{"rowVersion":3}""")]
|
|
||||||
[InlineData(IssueActions.SubmitForVerification, "Hotovo", "/api/v1/issues/42/submit-for-verification", """{"rowVersion":3,"note":"Hotovo"}""")]
|
|
||||||
[InlineData(IssueActions.Confirm, null, "/api/v1/issues/42/confirm", """{"rowVersion":3}""")]
|
|
||||||
[InlineData(IssueActions.Reopen, "Bliká dál", "/api/v1/issues/42/reopen", """{"rowVersion":3,"reason":"Bliká dál"}""")]
|
|
||||||
[InlineData(IssueActions.Reject, "Duplicita", "/api/v1/issues/42/reject", """{"rowVersion":3,"reason":"Duplicita"}""")]
|
|
||||||
public async Task Zmena_stavu_jde_na_akcni_endpoint_s_rowVersion(string action, string? text, string path, string body)
|
|
||||||
{
|
|
||||||
var handler = new RecordingHandler(DetailJson);
|
|
||||||
await Client(handler).TransitionIssueAsync(42, action, 3, text, CancellationToken.None);
|
|
||||||
|
|
||||||
Assert.Equal(HttpMethod.Post, handler.Method);
|
|
||||||
Assert.Equal(path, handler.Path);
|
|
||||||
Assert.True(JsonNode.DeepEquals(JsonNode.Parse(body), JsonNode.Parse(handler.Body!)), handler.Body);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Neznama_akce_se_do_API_neposle() =>
|
|
||||||
await Assert.ThrowsAsync<ArgumentException>(() =>
|
|
||||||
Client(new RecordingHandler(DetailJson)).TransitionIssueAsync(42, "DELETE", 3, null, CancellationToken.None));
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Prirazeni_posle_resitele_prioritu_a_verzi()
|
|
||||||
{
|
|
||||||
var handler = new RecordingHandler(DetailJson);
|
|
||||||
await Client(handler).AssignIssueAsync(42, new AssignIssueRequest(7, "HIGH", 3), CancellationToken.None);
|
|
||||||
|
|
||||||
Assert.Equal("/api/v1/issues/42/assign", handler.Path);
|
|
||||||
Assert.Equal("""{"assigneeId":7,"priority":"HIGH","rowVersion":3}""", handler.Body);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Detail_nacte_akce_i_prilohy()
|
|
||||||
{
|
|
||||||
var issue = await Client(new RecordingHandler(DetailJson)).GetIssueAsync(42, CancellationToken.None);
|
|
||||||
|
|
||||||
Assert.True(issue.Can(IssueActions.Comment));
|
|
||||||
Assert.False(issue.Can(IssueActions.Assign));
|
|
||||||
Assert.Equal("foto.jpg", Assert.Single(issue.Attachments).FileName);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Priloha_si_zachova_cesky_nazev_souboru()
|
|
||||||
{
|
|
||||||
var handler = new RecordingHandler("", response =>
|
|
||||||
{
|
|
||||||
response.Content = new ByteArrayContent([0xFF, 0xD8, 0xFF]);
|
|
||||||
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
|
|
||||||
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileNameStar = "učebna B-205.jpg" };
|
|
||||||
});
|
|
||||||
|
|
||||||
using var file = await Client(handler).DownloadAttachmentAsync(9, CancellationToken.None);
|
|
||||||
|
|
||||||
Assert.Equal("/api/v1/attachments/9", handler.Path);
|
|
||||||
Assert.Equal("učebna B-205.jpg", file.FileName);
|
|
||||||
Assert.Equal("image/jpeg", file.ContentType);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Chyby_poli_z_API_se_spoji_do_jedne_zpravy()
|
|
||||||
{
|
|
||||||
var ex = new ApiException(HttpStatusCode.BadRequest, "One or more validation errors occurred.",
|
|
||||||
new Dictionary<string, string[]> { ["reason"] = ["Důvod je povinný."], ["rowVersion"] = ["Chybí verze."] });
|
|
||||||
|
|
||||||
Assert.Equal("Důvod je povinný. Chybí verze.", ex.AllMessages);
|
|
||||||
}
|
|
||||||
|
|
||||||
private const string DetailJson = """
|
|
||||||
{"id":42,"title":"Projektor","description":"Bliká.","categoryId":2,"buildingId":null,"locationDetail":null,
|
|
||||||
"status":"IN_PROGRESS","priority":"NORMAL","reporterId":5,"assigneeId":7,"createdAt":"2026-10-03T08:00:00Z",
|
|
||||||
"rowVersion":4,"allowedActions":["COMMENT","ADD_ATTACHMENTS"],
|
|
||||||
"attachments":[{"id":9,"fileName":"foto.jpg","contentType":"image/jpeg","sizeBytes":3,"createdAt":"2026-10-03T08:00:00Z"}]}
|
|
||||||
""";
|
|
||||||
|
|
||||||
private static HelpdeskApiClient Client(HttpMessageHandler handler) =>
|
|
||||||
new(new HttpClient(handler) { BaseAddress = new ApiOptions { BaseUrl = "http://api/" }.VersionedBaseAddress() });
|
|
||||||
|
|
||||||
private sealed class RecordingHandler(string json, Action<HttpResponseMessage>? customize = null) : HttpMessageHandler
|
|
||||||
{
|
|
||||||
public HttpMethod? Method { get; private set; }
|
|
||||||
public string? Path { get; private set; }
|
|
||||||
public string? Body { get; private set; }
|
|
||||||
|
|
||||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
|
||||||
{
|
|
||||||
Method = request.Method;
|
|
||||||
Path = request.RequestUri!.AbsolutePath;
|
|
||||||
Body = request.Content is null ? null : await request.Content.ReadAsStringAsync(ct);
|
|
||||||
var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
|
||||||
customize?.Invoke(response);
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Text;
|
|
||||||
using Helpdesk.Web.Api;
|
|
||||||
using Helpdesk.Web.Models;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
|
|
||||||
namespace Helpdesk.Web.Tests;
|
|
||||||
|
|
||||||
public class AttachmentRulesTests
|
|
||||||
{
|
|
||||||
private static IFormFile File(string name, long length) =>
|
|
||||||
new FormFile(new MemoryStream(new byte[Math.Min(length, 16)]), 0, length, "Files", name);
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Povolene_soubory_projdou() =>
|
|
||||||
Assert.Empty(AttachmentRules.Validate([File("projektor.JPG", 2_000_000), File("protokol.pdf", 300_000)]));
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Vic_nez_pet_souboru_neprojde() =>
|
|
||||||
Assert.Contains(AttachmentRules.Validate(Enumerable.Range(1, 6).Select(i => File($"foto{i}.png", 1000)).ToList()),
|
|
||||||
e => e.Contains("nejvýše 5"));
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("virus.exe", "povolený typ")]
|
|
||||||
[InlineData("velka.jpg", "10 MB")]
|
|
||||||
[InlineData("prazdny.png", "prázdný")]
|
|
||||||
public void Nepovoleny_soubor_ma_srozumitelnou_chybu(string name, string expected)
|
|
||||||
{
|
|
||||||
var length = name switch { "velka.jpg" => AttachmentRules.MaxFileBytes + 1, "prazdny.png" => 0, _ => 100 };
|
|
||||||
Assert.Contains(AttachmentRules.Validate([File(name, length)]), e => e.Contains(expected));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public class IssueListViewModelTests
|
|
||||||
{
|
|
||||||
private static readonly IssueListViewModel Model = new()
|
|
||||||
{
|
|
||||||
Issues = new PagedResult<IssueSummary>([], 0, 1, 20),
|
|
||||||
CategoryNames = new Dictionary<int, string> { [2] = "Technické vybavení" },
|
|
||||||
BuildingNames = new Dictionary<int, string> { [2] = "Budova B" },
|
|
||||||
};
|
|
||||||
|
|
||||||
private static IssueSummary Issue(int? buildingId, string? detail) =>
|
|
||||||
new(1, "Projektor", 2, buildingId, detail, "RECEIVED", "NORMAL", 1, null, DateTimeOffset.UnixEpoch);
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData(2, "učebna B-205", "Budova B – učebna B-205")]
|
|
||||||
[InlineData(2, null, "Budova B")]
|
|
||||||
[InlineData(null, "venku u vchodu", "venku u vchodu")]
|
|
||||||
[InlineData(null, null, null)]
|
|
||||||
public void Misto_spoji_budovu_a_upresneni(int? buildingId, string? detail, string? expected) =>
|
|
||||||
Assert.Equal(expected, Model.Location(Issue(buildingId, detail)));
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Neznama_kategorie_neshodi_stranku() => Assert.Equal("Neznámá kategorie", Model.CategoryName(99));
|
|
||||||
}
|
|
||||||
|
|
||||||
public class CreateIssueRequestTests
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public async Task Hlaseni_s_prilohou_jde_do_API_jako_multipart()
|
|
||||||
{
|
|
||||||
var handler = new RecordingHandler();
|
|
||||||
var api = new HelpdeskApiClient(new HttpClient(handler) { BaseAddress = new ApiOptions { BaseUrl = "http://api/" }.VersionedBaseAddress() });
|
|
||||||
|
|
||||||
var issue = await api.CreateIssueAsync(
|
|
||||||
new CreateIssueRequest("Projektor", "Bliká.", 2, BuildingId: null, LocationDetail: "B-205"),
|
|
||||||
[new UploadFile("foto.jpg", "image/jpeg", () => new MemoryStream([0xFF, 0xD8, 0xFF]))],
|
|
||||||
CancellationToken.None);
|
|
||||||
|
|
||||||
Assert.Equal(7, issue.Id);
|
|
||||||
Assert.Equal("/api/v1/issues", handler.Path);
|
|
||||||
Assert.StartsWith("multipart/form-data", handler.ContentType);
|
|
||||||
Assert.Contains("name=title", handler.Body);
|
|
||||||
Assert.Contains("name=categoryId", handler.Body);
|
|
||||||
Assert.Contains("name=files; filename=foto.jpg", handler.Body);
|
|
||||||
Assert.DoesNotContain("name=buildingId", handler.Body); // nepovinná pole bez hodnoty se neposílají
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class RecordingHandler : HttpMessageHandler
|
|
||||||
{
|
|
||||||
public string? Path { get; private set; }
|
|
||||||
public string? ContentType { get; private set; }
|
|
||||||
public string Body { get; private set; } = "";
|
|
||||||
|
|
||||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
|
||||||
{
|
|
||||||
Path = request.RequestUri!.AbsolutePath;
|
|
||||||
ContentType = request.Content!.Headers.ContentType!.ToString();
|
|
||||||
Body = await request.Content.ReadAsStringAsync(ct);
|
|
||||||
return new HttpResponseMessage(HttpStatusCode.Created)
|
|
||||||
{
|
|
||||||
Content = new StringContent("""{"id":7,"title":"Projektor","status":"RECEIVED","rowVersion":0,"allowedActions":["EDIT"]}""",
|
|
||||||
Encoding.UTF8, "application/json"),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
using Helpdesk.Web.Infrastructure;
|
|
||||||
|
|
||||||
namespace Helpdesk.Web.Tests;
|
|
||||||
|
|
||||||
public class StatusLabelsTests
|
|
||||||
{
|
|
||||||
[Theory]
|
|
||||||
[InlineData("RECEIVED", "Přijata")]
|
|
||||||
[InlineData("IN_PROGRESS", "V řešení")]
|
|
||||||
[InlineData("PENDING_VERIFICATION", "Čeká na ověření")]
|
|
||||||
[InlineData("in_progress", "V řešení")]
|
|
||||||
public void Stav_zavady_ma_cesky_nazev(string status, string label) => Assert.Equal(label, StatusLabels.For(status));
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Zamitnuti_se_sklonuje_podle_zavady_a_navrhu()
|
|
||||||
{
|
|
||||||
Assert.Equal("Zamítnuta", StatusLabels.For("REJECTED"));
|
|
||||||
Assert.Equal("Zamítnut", StatusLabels.For("REJECTED", isProposal: true));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Neznamy_kod_se_zobrazi_tak_jak_prisel() => Assert.Equal("ARCHIVED", StatusLabels.For("ARCHIVED"));
|
|
||||||
}
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Text;
|
|
||||||
using Helpdesk.Web.Api;
|
|
||||||
using Helpdesk.Web.Auth;
|
|
||||||
using Microsoft.AspNetCore.Authentication;
|
|
||||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
|
||||||
using Microsoft.AspNetCore.Mvc.Testing;
|
|
||||||
using Microsoft.AspNetCore.TestHost;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
|
|
||||||
namespace Helpdesk.Web.Tests;
|
|
||||||
|
|
||||||
public sealed class SwaggerAccessTests
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public async Task SwaggerAndItsAssetsRequireAnAdministratorSession()
|
|
||||||
{
|
|
||||||
await using var application = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
|
||||||
builder.ConfigureTestServices(services => services.AddHttpClient(nameof(HelpdeskApiClient))
|
|
||||||
.ConfigurePrimaryHttpMessageHandler(() => new OpenApiBackend())));
|
|
||||||
using var client = application.CreateClient(new WebApplicationFactoryClientOptions
|
|
||||||
{
|
|
||||||
AllowAutoRedirect = false,
|
|
||||||
BaseAddress = new Uri("https://localhost"),
|
|
||||||
});
|
|
||||||
var ct = TestContext.Current.CancellationToken;
|
|
||||||
string[] paths = ["/swagger", "/swagger/index.html", "/swagger/index.js", "/swagger/swagger-ui.css", "/swagger/v1/swagger.json"];
|
|
||||||
foreach (var path in paths)
|
|
||||||
{
|
|
||||||
using var response = await client.GetAsync(path, ct);
|
|
||||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
|
||||||
Assert.Equal("/login", response.Headers.Location?.AbsolutePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
SignIn(application.Services, client, UserRoles.Student);
|
|
||||||
foreach (var path in paths)
|
|
||||||
{
|
|
||||||
using var response = await client.GetAsync(path, ct);
|
|
||||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
|
||||||
Assert.Equal("/error/403", response.Headers.Location?.AbsolutePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
SignIn(application.Services, client, UserRoles.Admin);
|
|
||||||
using var entry = await client.GetAsync("/swagger", ct);
|
|
||||||
Assert.Equal(HttpStatusCode.MovedPermanently, entry.StatusCode);
|
|
||||||
using var index = await client.GetAsync("/swagger/index.html", ct);
|
|
||||||
Assert.Equal(HttpStatusCode.OK, index.StatusCode);
|
|
||||||
Assert.Contains("Helpdesk API", await index.Content.ReadAsStringAsync(ct));
|
|
||||||
Assert.True(index.Headers.CacheControl?.NoStore == true);
|
|
||||||
using var script = await client.GetAsync("/swagger/index.js", ct);
|
|
||||||
Assert.Equal(HttpStatusCode.OK, script.StatusCode);
|
|
||||||
Assert.Contains("v1/swagger.json", await script.Content.ReadAsStringAsync(ct));
|
|
||||||
using var css = await client.GetAsync("/swagger/swagger-ui.css", ct);
|
|
||||||
Assert.Equal(HttpStatusCode.OK, css.StatusCode);
|
|
||||||
using var document = await client.GetAsync("/swagger/v1/swagger.json", ct);
|
|
||||||
Assert.Equal(HttpStatusCode.OK, document.StatusCode);
|
|
||||||
Assert.Contains("\"openapi\"", await document.Content.ReadAsStringAsync(ct));
|
|
||||||
Assert.True(document.Headers.CacheControl?.NoStore == true);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void SignIn(IServiceProvider services, HttpClient client, string role)
|
|
||||||
{
|
|
||||||
var scheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
|
||||||
var options = services.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>().Get(scheme);
|
|
||||||
var now = DateTimeOffset.UtcNow;
|
|
||||||
var properties = new AuthenticationProperties { IssuedUtc = now, ExpiresUtc = now.AddHours(1) };
|
|
||||||
AuthCookie.StoreTokens(properties, new TokenSet("test-access", now.AddMinutes(15), "test-refresh", now.AddDays(1)));
|
|
||||||
var user = new UserDto(1, "[email protected]", "Test", "User", null, role, true);
|
|
||||||
var ticket = new AuthenticationTicket(AuthCookie.CreatePrincipal(user), properties, scheme);
|
|
||||||
|
|
||||||
client.DefaultRequestHeaders.Remove("Cookie");
|
|
||||||
client.DefaultRequestHeaders.Add("Cookie", $"{AuthCookie.Name}={options.TicketDataFormat.Protect(ticket)}");
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed class OpenApiBackend : HttpMessageHandler
|
|
||||||
{
|
|
||||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
Assert.Equal("/api/v1/admin/openapi/v1.json", request.RequestUri?.AbsolutePath);
|
|
||||||
Assert.Equal("Bearer", request.Headers.Authorization?.Scheme);
|
|
||||||
Assert.Equal("test-access", request.Headers.Authorization?.Parameter);
|
|
||||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
|
|
||||||
{
|
|
||||||
Content = new StringContent("""{"openapi":"3.0.4"}""", Encoding.UTF8, "application/json"),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
using Helpdesk.Web.Api;
|
|
||||||
using Helpdesk.Web.Auth;
|
|
||||||
|
|
||||||
namespace Helpdesk.Web.Tests;
|
|
||||||
|
|
||||||
public class TokenRefresherTests
|
|
||||||
{
|
|
||||||
private static readonly DateTimeOffset Now = new(2026, 12, 1, 10, 0, 0, TimeSpan.Zero);
|
|
||||||
private readonly FakeClock _clock = new(Now);
|
|
||||||
|
|
||||||
private static TokenSet NewTokens(string suffix) =>
|
|
||||||
new($"access-{suffix}", Now.AddMinutes(15), $"refresh-{suffix}", Now.AddDays(14));
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Soubezne_obnovy_stejneho_tokenu_volaji_API_jen_jednou()
|
|
||||||
{
|
|
||||||
var refresher = new TokenRefresher(_clock);
|
|
||||||
var calls = 0;
|
|
||||||
var gate = new TaskCompletionSource<TokenSet?>();
|
|
||||||
|
|
||||||
Task<TokenSet?> Refresh(string _)
|
|
||||||
{
|
|
||||||
Interlocked.Increment(ref calls);
|
|
||||||
return gate.Task;
|
|
||||||
}
|
|
||||||
|
|
||||||
var pending = Enumerable.Range(0, 5).Select(_ => refresher.RefreshAsync("refresh-old", Refresh)).ToArray();
|
|
||||||
gate.SetResult(NewTokens("new"));
|
|
||||||
var results = await Task.WhenAll(pending);
|
|
||||||
|
|
||||||
Assert.Equal(1, calls);
|
|
||||||
Assert.All(results, r => Assert.Equal("access-new", r!.AccessToken));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Pozdni_pozadavek_se_starou_cookie_dostane_stejny_vysledek()
|
|
||||||
{
|
|
||||||
var refresher = new TokenRefresher(_clock);
|
|
||||||
var calls = 0;
|
|
||||||
Task<TokenSet?> Refresh(string _) { calls++; return Task.FromResult<TokenSet?>(NewTokens($"{calls}")); }
|
|
||||||
|
|
||||||
var first = await refresher.RefreshAsync("refresh-old", Refresh);
|
|
||||||
_clock.Advance(TimeSpan.FromSeconds(20));
|
|
||||||
var late = await refresher.RefreshAsync("refresh-old", Refresh);
|
|
||||||
|
|
||||||
Assert.Equal(1, calls);
|
|
||||||
Assert.Equal(first, late);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Vysledek_se_po_uplynuti_doby_zapomene()
|
|
||||||
{
|
|
||||||
var refresher = new TokenRefresher(_clock);
|
|
||||||
var calls = 0;
|
|
||||||
Task<TokenSet?> Refresh(string _) { calls++; return Task.FromResult<TokenSet?>(null); }
|
|
||||||
|
|
||||||
await refresher.RefreshAsync("refresh-old", Refresh);
|
|
||||||
_clock.Advance(TokenRefresher.ResultLifetime + TimeSpan.FromSeconds(1));
|
|
||||||
await refresher.RefreshAsync("refresh-old", Refresh);
|
|
||||||
|
|
||||||
Assert.Equal(2, calls);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Ruzne_tokeny_se_obnovuji_nezavisle()
|
|
||||||
{
|
|
||||||
var refresher = new TokenRefresher(_clock);
|
|
||||||
var calls = 0;
|
|
||||||
Task<TokenSet?> Refresh(string token) { calls++; return Task.FromResult<TokenSet?>(NewTokens(token)); }
|
|
||||||
|
|
||||||
var a = await refresher.RefreshAsync("refresh-a", Refresh);
|
|
||||||
var b = await refresher.RefreshAsync("refresh-b", Refresh);
|
|
||||||
|
|
||||||
Assert.Equal(2, calls);
|
|
||||||
Assert.NotEqual(a, b);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task Docasna_chyba_se_nepamatuje()
|
|
||||||
{
|
|
||||||
var refresher = new TokenRefresher(_clock);
|
|
||||||
var calls = 0;
|
|
||||||
Task<TokenSet?> Refresh(string _) =>
|
|
||||||
++calls == 1 ? throw new HttpRequestException("API nedostupné") : Task.FromResult<TokenSet?>(NewTokens("new"));
|
|
||||||
|
|
||||||
await Assert.ThrowsAsync<HttpRequestException>(() => refresher.RefreshAsync("refresh-old", Refresh));
|
|
||||||
var retry = await refresher.RefreshAsync("refresh-old", Refresh);
|
|
||||||
|
|
||||||
Assert.Equal(2, calls);
|
|
||||||
Assert.Equal("access-new", retry!.AccessToken);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal sealed class FakeClock(DateTimeOffset now) : TimeProvider
|
|
||||||
{
|
|
||||||
private DateTimeOffset _now = now;
|
|
||||||
|
|
||||||
public override DateTimeOffset GetUtcNow() => _now;
|
|
||||||
|
|
||||||
public void Advance(TimeSpan by) => _now += by;
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
using Helpdesk.Web.Api;
|
|
||||||
using Helpdesk.Web.Infrastructure;
|
|
||||||
|
|
||||||
namespace Helpdesk.Web.Tests;
|
|
||||||
|
|
||||||
public class ApiVersioningTests
|
|
||||||
{
|
|
||||||
[Theory]
|
|
||||||
[InlineData("http://api:8080/")]
|
|
||||||
[InlineData("http://api:8080")]
|
|
||||||
public void Zaklad_adresy_obsahuje_verzi_API(string baseUrl) =>
|
|
||||||
Assert.Equal("http://api:8080/api/v1/", new ApiOptions { BaseUrl = baseUrl }.VersionedBaseAddress().ToString());
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Relativni_cesta_se_slozi_pod_verzi()
|
|
||||||
{
|
|
||||||
var baseAddress = new ApiOptions { BaseUrl = "http://api:8080/" }.VersionedBaseAddress();
|
|
||||||
|
|
||||||
Assert.Equal("/api/v1/auth/login", new Uri(baseAddress, "auth/login").AbsolutePath);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public class AppVersionTests
|
|
||||||
{
|
|
||||||
[Theory]
|
|
||||||
[InlineData("0.2.0+6e742b4029cca8896173c0d64783b7fb7540f214", "0.2.0 (6e742b4)")]
|
|
||||||
[InlineData("0.2.0", "0.2.0")]
|
|
||||||
[InlineData(null, "neznámá")]
|
|
||||||
public void Verze_se_zobrazi_s_kratkym_hashem_commitu(string? informational, string expected) =>
|
|
||||||
Assert.Equal(expected, AppVersion.Format(informational));
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
|
|
||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
|
||||||
# Visual Studio Version 17
|
|
||||||
VisualStudioVersion = 17.0.31903.59
|
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Web", "Helpdesk.Web\Helpdesk.Web.csproj", "{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Web.Tests", "Helpdesk.Web.Tests\Helpdesk.Web.Tests.csproj", "{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}"
|
|
||||||
EndProject
|
|
||||||
Global
|
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
|
||||||
Debug|Any CPU = Debug|Any CPU
|
|
||||||
Debug|x64 = Debug|x64
|
|
||||||
Debug|x86 = Debug|x86
|
|
||||||
Release|Any CPU = Release|Any CPU
|
|
||||||
Release|x64 = Release|x64
|
|
||||||
Release|x86 = Release|x86
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
|
||||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Debug|x64.ActiveCfg = Debug|Any CPU
|
|
||||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Debug|x64.Build.0 = Debug|Any CPU
|
|
||||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Debug|x86.ActiveCfg = Debug|Any CPU
|
|
||||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Debug|x86.Build.0 = Debug|Any CPU
|
|
||||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Release|x64.ActiveCfg = Release|Any CPU
|
|
||||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Release|x64.Build.0 = Release|Any CPU
|
|
||||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Release|x86.ActiveCfg = Release|Any CPU
|
|
||||||
{25D75863-E1EF-4B3E-B5FE-CE8F7E21F2F6}.Release|x86.Build.0 = Release|Any CPU
|
|
||||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Debug|x64.ActiveCfg = Debug|Any CPU
|
|
||||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Debug|x64.Build.0 = Debug|Any CPU
|
|
||||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Debug|x86.ActiveCfg = Debug|Any CPU
|
|
||||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Debug|x86.Build.0 = Debug|Any CPU
|
|
||||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Release|x64.ActiveCfg = Release|Any CPU
|
|
||||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Release|x64.Build.0 = Release|Any CPU
|
|
||||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Release|x86.ActiveCfg = Release|Any CPU
|
|
||||||
{A1D048EA-6B9C-4920-A3F2-5DB3B92404CA}.Release|x86.Build.0 = Release|Any CPU
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
|
||||||
HideSolutionNode = FALSE
|
|
||||||
EndGlobalSection
|
|
||||||
EndGlobal
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
using System.Net;
|
|
||||||
using System.Net.Http.Json;
|
|
||||||
using System.Text.Json;
|
|
||||||
|
|
||||||
namespace Helpdesk.Web.Api;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Neúspěšná odpověď API ve formátu ProblemDetails (RFC 9457). Nese stav, titulek
|
|
||||||
/// a u validačních chyb seznam chyb podle polí (klíče jsou názvy vlastností v camelCase).
|
|
||||||
/// </summary>
|
|
||||||
public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary<string, string[]> errors)
|
|
||||||
: Exception(title ?? $"API vrátilo stav {(int)statusCode}.")
|
|
||||||
{
|
|
||||||
public HttpStatusCode StatusCode { get; } = statusCode;
|
|
||||||
public string? Title { get; } = title;
|
|
||||||
public IReadOnlyDictionary<string, string[]> Errors { get; } = errors;
|
|
||||||
|
|
||||||
/// <summary>Text pro uživatele. API píše titulky chyb česky, kromě odpovědí bez těla (např. 429).</summary>
|
|
||||||
public string UserMessage => StatusCode switch
|
|
||||||
{
|
|
||||||
HttpStatusCode.TooManyRequests => "Příliš mnoho pokusů. Zkuste to prosím za minutu.",
|
|
||||||
_ when !string.IsNullOrWhiteSpace(Title) => Title,
|
|
||||||
HttpStatusCode.Forbidden => "K této akci nemáte oprávnění.",
|
|
||||||
HttpStatusCode.NotFound => "Záznam nebyl nalezen.",
|
|
||||||
_ => "Požadavek se nepodařilo zpracovat. Zkuste to prosím znovu.",
|
|
||||||
};
|
|
||||||
|
|
||||||
/// <summary>Chyby polí, pokud je API poslalo, jinak <see cref="UserMessage"/> – pro zprávu mimo formulář.</summary>
|
|
||||||
public string AllMessages => Errors.Count == 0
|
|
||||||
? UserMessage
|
|
||||||
: string.Join(" ", Errors.Values.SelectMany(messages => messages).Distinct());
|
|
||||||
|
|
||||||
public static async Task<ApiException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
|
|
||||||
{
|
|
||||||
string? title = null;
|
|
||||||
Dictionary<string, string[]> errors = new(StringComparer.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
if (response.Content.Headers.ContentType?.MediaType is { } mediaType && mediaType.Contains("json", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var problem = await response.Content.ReadFromJsonAsync<ProblemBody>(ct);
|
|
||||||
title = problem?.Title;
|
|
||||||
if (problem?.Errors is { } fieldErrors)
|
|
||||||
{
|
|
||||||
foreach (var (field, messages) in fieldErrors)
|
|
||||||
errors[field] = messages;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (JsonException)
|
|
||||||
{
|
|
||||||
// Tělo není ProblemDetails – zůstane jen stavový kód.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return new ApiException(response.StatusCode, title, errors);
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed record ProblemBody(string? Title, Dictionary<string, string[]>? Errors);
|
|
||||||
}
|
|
||||||
|
|
||||||
internal static class ApiResponse
|
|
||||||
{
|
|
||||||
public static async Task EnsureSuccessAsync(HttpResponseMessage response, CancellationToken ct)
|
|
||||||
{
|
|
||||||
if (!response.IsSuccessStatusCode)
|
|
||||||
throw await ApiException.FromResponseAsync(response, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task<T> ReadAsync<T>(HttpResponseMessage response, CancellationToken ct)
|
|
||||||
{
|
|
||||||
await EnsureSuccessAsync(response, ct);
|
|
||||||
return await response.Content.ReadFromJsonAsync<T>(ct)
|
|
||||||
?? throw new InvalidOperationException($"API vrátilo prázdnou odpověď místo {typeof(T).Name}.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,171 +0,0 @@
|
|||||||
namespace Helpdesk.Web.Api;
|
|
||||||
|
|
||||||
// Kontrakt REST API /api/v1 tak, jak ho web používá. Web je tenký klient a na projekty
|
|
||||||
// backendu nemá referenci – DTO jsou zde zrcadlem dokumentace ve Swaggeru.
|
|
||||||
|
|
||||||
public sealed record UserDto(
|
|
||||||
int Id,
|
|
||||||
string Email,
|
|
||||||
string FirstName,
|
|
||||||
string LastName,
|
|
||||||
string? Phone,
|
|
||||||
string Role,
|
|
||||||
bool EmailNotificationsEnabled)
|
|
||||||
{
|
|
||||||
public string FullName => $"{FirstName} {LastName}";
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed record AuthResponse(
|
|
||||||
string AccessToken,
|
|
||||||
DateTimeOffset AccessTokenExpiresAt,
|
|
||||||
string RefreshToken,
|
|
||||||
DateTimeOffset RefreshTokenExpiresAt,
|
|
||||||
UserDto User)
|
|
||||||
{
|
|
||||||
public TokenSet Tokens => new(AccessToken, AccessTokenExpiresAt, RefreshToken, RefreshTokenExpiresAt);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Pár tokenů uložený v autentizační cookie webu.</summary>
|
|
||||||
public sealed record TokenSet(
|
|
||||||
string AccessToken,
|
|
||||||
DateTimeOffset AccessTokenExpiresAt,
|
|
||||||
string RefreshToken,
|
|
||||||
DateTimeOffset RefreshTokenExpiresAt);
|
|
||||||
|
|
||||||
public sealed record LoginRequest(string Email, string Password);
|
|
||||||
|
|
||||||
public sealed record RegisterRequest(string Email, string Password, string FirstName, string LastName);
|
|
||||||
|
|
||||||
public sealed record RefreshTokenRequest(string RefreshToken);
|
|
||||||
|
|
||||||
public sealed record EmailTokenRequest(string Token);
|
|
||||||
|
|
||||||
public sealed record ForgotPasswordRequest(string Email);
|
|
||||||
|
|
||||||
public sealed record ResetPasswordRequest(string Token, string NewPassword);
|
|
||||||
|
|
||||||
public sealed record UpdateProfileRequest(string FirstName, string LastName, string? Phone, bool EmailNotificationsEnabled);
|
|
||||||
|
|
||||||
/// <summary>Stránkovaný seznam z API: <c>{ items, totalCount, page, pageSize }</c>.</summary>
|
|
||||||
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize)
|
|
||||||
{
|
|
||||||
public int PageCount => PageSize <= 0 ? 0 : (int)Math.Ceiling(TotalCount / (double)PageSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed record CategoryDto(int Id, string Name, string? Description, bool IsActive);
|
|
||||||
|
|
||||||
public sealed record BuildingDto(int Id, string Code, string Name, string? Address, bool IsActive);
|
|
||||||
|
|
||||||
/// <summary>Závada v seznamu. Kategorie a budova jsou jen ID – názvy doplňuje web z číselníků.</summary>
|
|
||||||
public sealed record IssueSummary(
|
|
||||||
int Id, string Title, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
|
|
||||||
string Priority, int ReporterId, int? AssigneeId, DateTimeOffset CreatedAt);
|
|
||||||
|
|
||||||
/// <summary>Nové hlášení. Přílohy jdou ve stejném požadavku (multipart, pole <c>files</c>).</summary>
|
|
||||||
public sealed record CreateIssueRequest(string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail);
|
|
||||||
|
|
||||||
/// <summary>Soubor přeposílaný z formuláře webu do API.</summary>
|
|
||||||
public sealed record UploadFile(string FileName, string ContentType, Func<Stream> OpenRead);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Detail závady. <c>AllowedActions</c> říká, co smí aktuální uživatel udělat (kódy z <see cref="IssueActions"/>),
|
|
||||||
/// <c>RowVersion</c> se posílá zpět s každou úpravou a změnou stavu (optimistické zamykání, jinak 409).
|
|
||||||
/// </summary>
|
|
||||||
public sealed record IssueDetail(
|
|
||||||
int Id, string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
|
|
||||||
string Priority, int ReporterId, int? AssigneeId, DateTimeOffset CreatedAt, int RowVersion,
|
|
||||||
IReadOnlyList<string> AllowedActions, IReadOnlyList<AttachmentDto> Attachments)
|
|
||||||
{
|
|
||||||
public bool Can(string action) => AllowedActions?.Contains(action) == true;
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed record AttachmentDto(int Id, string FileName, string ContentType, long SizeBytes, DateTimeOffset CreatedAt);
|
|
||||||
|
|
||||||
/// <summary>Událost na časové ose závady – vytvoření, přiřazení, změna stavu i komentář (FR-17).</summary>
|
|
||||||
public sealed record IssueEventDto(
|
|
||||||
int Id, string EventType, string? FromStatus, string ToStatus, int ActorId, string ActorName, string? Note,
|
|
||||||
DateTimeOffset OccurredAt);
|
|
||||||
|
|
||||||
/// <summary>Možný řešitel (jen pro vedení) s počtem jeho otevřených závad (FR-13).</summary>
|
|
||||||
public sealed record AssignableUserDto(int Id, string FirstName, string LastName, string Role, int OpenIssues)
|
|
||||||
{
|
|
||||||
public string FullName => $"{FirstName} {LastName}";
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed record EditIssueRequest(
|
|
||||||
string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail, int RowVersion);
|
|
||||||
|
|
||||||
public sealed record AssignIssueRequest(int AssigneeId, string? Priority, int RowVersion);
|
|
||||||
|
|
||||||
public sealed record CommentRequest(string Text);
|
|
||||||
|
|
||||||
/// <summary>Stažená příloha. Proud čte přímo odpověď API a uvolní se spolu s ní.</summary>
|
|
||||||
public sealed class ApiFile(Stream content, string contentType, string fileName, IDisposable response) : IDisposable
|
|
||||||
{
|
|
||||||
public Stream Content { get; } = content;
|
|
||||||
public string ContentType { get; } = contentType;
|
|
||||||
public string FileName { get; } = fileName;
|
|
||||||
|
|
||||||
public void Dispose() => response.Dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Kódy akcí z <c>allowedActions</c> v detailu závady.</summary>
|
|
||||||
public static class IssueActions
|
|
||||||
{
|
|
||||||
public const string Edit = "EDIT";
|
|
||||||
public const string Assign = "ASSIGN";
|
|
||||||
public const string StartWork = "START_WORK";
|
|
||||||
public const string SubmitForVerification = "SUBMIT_FOR_VERIFICATION";
|
|
||||||
public const string Confirm = "CONFIRM";
|
|
||||||
public const string Reopen = "REOPEN";
|
|
||||||
public const string Reject = "REJECT";
|
|
||||||
public const string Comment = "COMMENT";
|
|
||||||
public const string AddAttachments = "ADD_ATTACHMENTS";
|
|
||||||
|
|
||||||
/// <summary>Změny stavu v pořadí, v jakém je web nabízí (T4 – T9).</summary>
|
|
||||||
public static readonly IReadOnlyList<string> Transitions = [StartWork, SubmitForVerification, Confirm, Reopen, Reject];
|
|
||||||
|
|
||||||
/// <summary>Akční endpoint <c>POST /issues/{id}/…</c> pro změnu stavu.</summary>
|
|
||||||
public static string? TransitionPath(string? action) => action switch
|
|
||||||
{
|
|
||||||
StartWork => "start",
|
|
||||||
SubmitForVerification => "submit-for-verification",
|
|
||||||
Confirm => "confirm",
|
|
||||||
Reopen => "reopen",
|
|
||||||
Reject => "reject",
|
|
||||||
_ => null,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// <summary>Zamítnutí a znovuotevření vyžadují důvod (T7 – T9).</summary>
|
|
||||||
public static bool RequiresReason(string action) => action is Reopen or Reject;
|
|
||||||
|
|
||||||
/// <summary>Předání k ověření má nepovinnou poznámku (T5).</summary>
|
|
||||||
public static bool AcceptsText(string action) => action is SubmitForVerification || RequiresReason(action);
|
|
||||||
|
|
||||||
/// <summary>Texty tlačítek – stejné jako v mobilní aplikaci.</summary>
|
|
||||||
public static string Label(string action) => action switch
|
|
||||||
{
|
|
||||||
StartWork => "Zahájit řešení",
|
|
||||||
SubmitForVerification => "Předat k ověření",
|
|
||||||
Confirm => "Potvrdit vyřešení",
|
|
||||||
Reopen => "Znovu otevřít závadu",
|
|
||||||
Reject => "Zamítnout závadu",
|
|
||||||
_ => action,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Priorita závady; názvy jako v mobilní aplikaci.</summary>
|
|
||||||
public static class IssuePriorities
|
|
||||||
{
|
|
||||||
public static readonly IReadOnlyList<string> All = ["LOW", "NORMAL", "HIGH"];
|
|
||||||
|
|
||||||
public static string Label(string? priority) => priority switch
|
|
||||||
{
|
|
||||||
"LOW" => "Nízká",
|
|
||||||
"HIGH" => "Vysoká",
|
|
||||||
_ => "Běžná",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>Filtry <c>GET /api/v1/issues</c>; prázdné hodnoty se do dotazu neposílají.</summary>
|
|
||||||
public sealed record IssueListQuery(string? Status = null, bool Mine = false, string Sort = "newest", int Page = 1, int PageSize = 20);
|
|
||||||
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user