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