Compare commits
6
Commits
v0.1.0
..
9e8b01b135
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e8b01b135 | ||
|
|
456579880e | ||
|
|
25aedb431e | ||
|
|
25bab43b21 | ||
|
|
cbc94c8722 | ||
|
|
d1b0807d38 |
+120
-164
@@ -1,190 +1,146 @@
|
||||
# FEEDBACK — Audit bugs mobile-kotlin (local-first)
|
||||
|
||||
> Généré le 2026-09-22 par 5 agents d'exploration parallèles (scopes : Room/DB, sync/outbox/SAF, réseau/auth/repos, UI/navigation/VM, scan/pdf/review/thumbnails).
|
||||
> Chaque finding est vérifié avec preuve `file:line`. Méthode : lecture intégrale des fichiers + croisement `docs/api-v1.md`, `AGENTS.md`, handlers Go.
|
||||
> Scope : `mobile-kotlin/` uniquement. Pas de fix appliqué — diagnostic seul.
|
||||
> Légende : 🔴 Critique (data loss / crash / sync bloquée) · 🟠 Majeur (divergence silencieuse, contrat violé) · 🟡 Mineur (UX, perf, dette).
|
||||
> Mise à jour le 2026-09-24 : les items corrigés par `d89c0d0 (fix 1 to 6)` et `22286aa (fix mobile audit review)` ont été re-vérifiés code en main et retirés. Ce document ne liste que le **reliquat confirmé**.
|
||||
> Màj 2026-09-24 (soir) : tout le reliquat ci-dessous est **corrigé et testé** (`:app:testDebugUnitTest` : 162/162 verts, DB v16, schéma `app/schemas/16.json` exporté). Les sections 🟠/🟡/🛠️ sont conservées comme traçabilité.
|
||||
> Chaque finding restant est vérifié avec preuve `file:line`.
|
||||
> Scope : `mobile-kotlin/` uniquement.
|
||||
> Légende : 🟠 Majeur (divergence silencieuse, contrat violé) · 🟡 Mineur (UX, perf, dette).
|
||||
|
||||
Base paths : `mobile-kotlin/app/src/main/java/com/kazier/mobile/…`
|
||||
|
||||
---
|
||||
|
||||
## 🔴 Critiques (à corriger en priorité)
|
||||
## ✅ Corrigés et retirés (vérifiés le 2026-09-24)
|
||||
|
||||
### C1 — `domain/GenerateId.kt:19` — IDs 32-hex non conformes (sign-extension `Byte` → `%02x`)
|
||||
`bytes.joinToString("") { "%02x".format(it) }` promeut chaque `Byte` signé en `int` : tout octet négatif produit `ffffffxx` (8 chars). Longueur 32→128, P(32 exact) ≈ 1/65536.
|
||||
Impact : `resource_id` / `operation_id` / `device_user_id` violent `^[0-9a-f]{32}$` (CHECK serveur) → `POST /sync/ops` rejetés, outbox bloquée, identités invalides.
|
||||
Repro : boucler `newResourceId()` et tester `length == 32 && matches([0-9a-f]{32})` → échec quasi systématique.
|
||||
### 🔴 Critiques : 9/9 corrigés
|
||||
- **C1** `domain/GenerateId.kt:19` — masque `and 0xFF` contre la sign-extension, 32-hex conforme.
|
||||
- **C2** `features/sync/OutboxSyncWorker.kt:139-145` — erreurs non-attribuables (`INVALID_RESPONSE`, 429/408, 4xx batch-level) → `Result.retry()` sans toucher aux ops.
|
||||
- **C3** `data/local/dao/PendingOperationDao.kt:66-72` — `purgeSynced` exclut les `create_resource` (tombstones), gates `countCreateOperations` préservés.
|
||||
- **C4** `features/saf/FileDeleter.kt:122-128` + `FolderDeleter.kt:122-124` — journal-first (`withTransaction` avant suppression SAF) + `sweepPendingPhysicalDeletes`.
|
||||
- **C5** `auth/SessionManager.kt:70-77` — `clear()` purge les ops non poussées (`pending`/`failed`), appelé par `AuthViewModel.signOut/signOutToLocal`.
|
||||
- **C6** `OutboxSyncWorker.kt:185-188` — stop au 1er échec (`return success()`, jamais `continue`) + cascade transitive `cascadeCreateFailure` via `parent_resource_id`/payload.
|
||||
- **C7** `OutboxSyncWorker.kt:152,170-174,193-196` — `applied.coerceIn`, `failedIndex < 0 → stop`, `applied == 0 → stop` (anti busy-loop/crash).
|
||||
- **C8** Scan export — `ScanExport.pendingForExport` idempotent, `shouldFinishSession` gate `DONE`, `uniquePageFile()` UUID, `deletePage` DB-d'abord, `exportPdf` ne marque que les succès.
|
||||
- **C9** `features/scan/ScanImageProcessor.kt:91-92` + `ScanViewModel.kt:213` — jamais de `recycle()` sur l'alias affiché (`!==` check).
|
||||
|
||||
### C2 — `features/sync/OutboxSyncWorker.kt:101-106` — dead-letter abusive sur erreurs non-attribuables
|
||||
Le `else` dead-letter `pending.first()` pour toute `ApiException` non-`NETWORK_ERROR`/5xx/401. `INVALID_RESPONSE` (200 sans enveloppe `{data}`) et `HTTP_429`/`408` (transitoires) tombent dedans. La faute est imputée à la 1re op du batch quelle que soit l'op rejetée.
|
||||
Impact : op saine → `failed` à vie sur erreur batch-level ou transitoire ; inclut le cas `429 RATE_LIMITED` (login/devices/sync) qui devrait suivre le chemin `retry()`.
|
||||
Repro : serveur 200 sans `data` ou 429 → 1re op dead-lettrée.
|
||||
### 🟠 Majeurs corrigés (31)
|
||||
M1 (garde pending-move dossiers), M2 (gate `create` avant `move`), M3 (`FileMover` sans repli mensonger), M4 (exclusion `exists=0` pending seul), M6 (parent inconnu → `continue`), M7 (`importRoot` schedule le drain), M8 (fichiers 0-octet acceptés), M10 (`DeviceIdentity` mutex + `insertIgnore`), M11 (décision assumée : pas de backfill `create_resource`), M12 (`upsertTolerant` sur `resource_id`/`uri`), M14 (colonne `device_id`, `UNIQUE(device_id, operation_id)` + migration 11→12), M15 (`failDescendants` élargi, cf. C6), M21 (boucle `listFilesPaged` + `meta.total`), M22 (`ApiClient` distingue `CancellationException`/`JsonDataException`/`IOException`), M23 (`activeUserStore` vs `ownerId`, plus de confusion device/user), M24 (`normalizePayloadNumbers` Double→Long), M25 (`SessionManager` possède `onUnauthorized`), M26 (`ServerUrlInterceptor` `runBlocking load()` anti-race), M28 (validation URL `toHttpUrl()`), M29 (`pendingDefaultPick` saveable), M30 (pager `rememberSaveable`), M31 (debounce sur résultats seuls), M32 (gate `canShare` FolderDetail), M33 (`refreshShareGate` au login/logout), M34 (`selection.clear()` + chips figés en sélection), M35 (`resolveViewerPage` clamp), M36 (sélecteur thème 3 états), M37 (flag `dirty` anti-écrasement saisie), M38 (`MAX(sortOrder)+1`), M42 (`processed=true` PDF builder), M43 (réinsertion optimiste review), M44 (`remember(existingIds)` stable).
|
||||
|
||||
### C3 — `features/sync/OutboxSyncWorker.kt:83` + `data/local/dao/PendingOperationDao.kt:42-43` — purge >7j qui casse le gate `processed`/`hasCreateOperation`
|
||||
`purgeSynced` efface les lignes `synced`, or `countCreateOperations` (`IN ('pending','synced')`) fonde les gates delete/create dessus.
|
||||
Impact : (a) fichier poussé puis purgé → `SafFileDeleter`/`FileDeleter`/`treeMarkMissing` omettent le `delete_resource` → fantôme serveur indélébile ; (b) `markProcessed` ré-enqueue un `create_resource` dupliqué.
|
||||
Repro : pousser un fichier, attendre 7j, le supprimer → aucun `delete_resource`, serveur garde la ressource.
|
||||
|
||||
### C4 — `features/saf/FolderDeleter.kt:106-124` + `features/saf/FileDeleter.kt:109-119` — suppression physique avant transaction, delete perdu sur crash
|
||||
`deleteTreePhysically` (SAF, irréversible) avant `withTransaction { treeMarkMissing }`.
|
||||
Impact : kill/crash entre les deux → octets supprimés, aucun `delete_resource` journalisé, walk suivant marque `exists=0` sans outbox (aucun chemin walk→enqueue) → fantôme serveur + divergence définitive.
|
||||
Repro : `deleteFull` puis kill avant commit Room → serveur jamais notifié.
|
||||
|
||||
### C5 — `ui/auth/AuthViewModel.kt:112-121` — pas de vidage outbox au sign-out, replay cross-account
|
||||
`signOut`/`signOutToLocal` purgent session et mode local mais aucune suppression de `pending_operations`. Les ops du compte A survivent au login du compte B (même `device_id`, `UNIQUE(device_id, operation_id)` sans historique partagé).
|
||||
Impact : ops de A appliquées dans le scope de B (`NOT_FOUND`/`NAME_CONFLICT`, voire créations croisées).
|
||||
Repro : enqueue offline sous A → sign-out → login B → drain pousse les ops de A sous token B.
|
||||
|
||||
### C6 — `features/sync/OutboxSyncWorker.kt:118-133` — drain poursuivi après échec + cascade limitée au même `resource_id`
|
||||
Après `markFailed`, `continue` envoie le batch suivant, et `failDescendants` (`PendingOperationDao.kt:38`) ne cible que `resource_id = :resourceId` alors que les enfants portent un autre `resource_id` (lien dans le payload).
|
||||
Impact : viole « serveur stop à la 1re erreur, client reprend à cet index » — creates enfants poussés et rejetés `NOT_FOUND` un par un, head-of-line blocking + dead-letters en cascade.
|
||||
Repro : `create` dossier-parent en échec → le run pousse quand même les creates enfants au tour suivant.
|
||||
|
||||
### C7 — `features/sync/OutboxSyncWorker.kt:112-131` — gardes absents sur réponse serveur (boucle infinie / crash)
|
||||
(a) `result.failed.operationId` absent du batch (`indexOfFirst < 0`) → silence + re-sélection du même batch → boucle serrée sans backoff ; (b) `result.applied > pending.size` → `pending[i]` lève `IndexOutOfBoundsException` → crash worker.
|
||||
Impact : (a) drain CPU/batterie ; (b) batch jamais acquitté. Complété par `data/remote` : `while(true)` sans garde `applied==0 && failed==null` → busy-loop si serveur renvoie `{applied:0, failed:null}`.
|
||||
Repro : mocker `syncOps → applied=0, failed=null` ou `operation_id` inconnu → boucle infinie ; `applied` incohérent → crash.
|
||||
|
||||
### C8 — Scan : perte de données à l'export
|
||||
- `ui/scan/ScanViewModel.kt:387-389` (`exportPdf`) — pages en échec seulement loggées (`failedIds`), puis **toutes** marquées `EXPORTED` + session `DONE` → PDF incomplet, sources abandonnées.
|
||||
- `ui/scan/ScanViewModel.kt:259-298` (`export`) — retry non idempotent : `getPages` retourne aussi les `EXPORTED`, chaque retry crée un nouvel URI SAF → documents + lignes Room + ops outbox dupliqués.
|
||||
- `ui/scan/ScanViewModel.kt:263` — fichier temp manquant → page sautée sans marquage mais `finishSession` ferme la session → page `PENDING` dans session `DONE`, jamais reprise ni nettoyée.
|
||||
- `ui/scan/ScanViewModel.kt:186-201` — nom page `page_$order.jpg` avec `order = pageCount+1` → collision après suppression (A,B → del A → C écrase B) → deux entités même `tempUri`, `deletePage` orpheline B.
|
||||
Repro : cf. chaque item (export partiel, retry après perte permission SAF, temp supprimé, capture-suppression-capture).
|
||||
|
||||
### C9 — `features/scan/ScanImageProcessor.kt:87-88` + `ui/scan/ScanViewModel.kt:192` — `recycle()` du bitmap encore affiché quand OpenCV indisponible
|
||||
`process()` retourne l'instance d'entrée si `!isAvailable()` ; l'appelant `recycle()` le `processed` qui alias le draft dessiné par `CropStage` → crash `recycled bitmap`.
|
||||
Repro : device sans lib OpenCV → valider un crop → crash au retour caméra.
|
||||
### 🟡 Mineurs corrigés dans `d89c0d0` (voir `git show --stat d89c0d0`)
|
||||
m4 (gardes cursor SAF), m6 (`deleteLocally` transactionnel), m8 (`FileOrdering` aligné SQL), m9 (commentaire `attempts` diagnostic), m10-m14 (`updateUri`, `LocalModeStore`, `load` réarmable, `StateFlow` après succès DB, clé `SYNC_MODE` retirée), m16-m18 (index, `defaultValue processed`, `swapOrder` contraint), m22 (`ApiService` endpoints contrat ajoutés), m23 (`registerDevice` erreurs visibles), m24 (garde mode local), m25 (logging sans PII), m26 (`Bearer` hors routes publiques), m27 (`expiresAt` persisté), m28 (`SecureTokenStore` lazy + Direct Boot), m29-m31 (nav `pdfbuilder/empty`, `launchSingleTop`, controller hoisté), m33-m39 (side-effects `buildPhase`, dialogs `rememberSaveable`, badge collectes, saisie serveur debouncée, flash thème, bandeau import, `FileStatus.LOCAL`), m40-m56 (scan/camera/thumbnails : résolution bornée, `toBitmap` throttlé, listener retiré, `else` rotation, garde `sourceRect`, arrondi crop, `combine` nettoyé, purge `ABANDONED`, unicité session active, `FileCategory` CSV cohérent, purge map `Mutex`, `.tmp` nettoyés, `isUpToDate` taille+mtime, `runCatching` close, commentaire `max`, `release()` sur exception, deck conservé sur erreur).
|
||||
|
||||
---
|
||||
|
||||
## 🟠 Majeurs
|
||||
## 🟠 Majeurs restants (4) — ✅ tous corrigés le 2026-09-24 (162/162 tests verts)
|
||||
|
||||
### Sync / Outbox / SAF
|
||||
- **M1 — `features/sync/DeviceSync.kt:85-91` + `data/repository/FolderRepository.kt:99-134`** : le walk écrase le parent des dossiers sans garde pending-move (`saveFolder` écrase toujours, `reparentSubFolders` métadonnée-seule sans déplacement SAF). Les fichiers ont `hasPendingMoveOperation` (`FileRepository.kt:190`), les dossiers rien → tout reparent/merge revert au tick 30s suivant, divergence disque/serveur permanente.
|
||||
- **M2 — `data/repository/FileRepository.kt:238-250`** : `applyMove` enqueue `move_resource` sans gate `create` (contrairement aux deletes) → move d'un fichier jamais poussé = `NOT_FOUND`/no-op serveur + ligne figée par `hasPendingMoveOperation`. Même cause `reparentSubFolders` (`FolderRepository.kt:144-157`) pour dossier au `create` purgé (>7j).
|
||||
- **M3 — `features/saf/FileMover.kt:47-53`** : repli métadonnée-seule incohérent (nouveau parent + ancienne uri quand `moveDocument` refusé) → Room ment durablement, walk bloqué par le garde pending-move, divergence serveur/disque.
|
||||
- **M4 — `features/sync/DeviceSync.kt:122-134`** : réconciliation `exists=0` asymétrique — fichiers exclus via `hasMoveOperation` (pending **ou** synced → à vie après un move syncé, fichier supprimé ensuite = fantôme `exists=1` éternel) ; dossiers sans exclusion (move en transition marqué `missing` à tort).
|
||||
- **M5 — `features/saf/FileDeleter.kt:88-100` + `features/saf/FolderDeleter.kt:91-103`** : `deleteInCloud` sans tombstone locale (`exists` reste 1) → ressource toujours affichée, walk la revoit, `refreshFromServer` ne supprime jamais de lignes → fantôme local vs serveur supprimé.
|
||||
- **M6 — `features/sync/DeviceSync.kt:84`** : `?: root.resourceId` masque toute violation parent-avant-enfant (parent absent de `resourceIdByUri` → enfant rattaché racine) → arbre serveur corrompu silencieusement.
|
||||
- **M7 — `features/sync/SyncViewModel.kt:135-156`** : `importRoot` ne schedule jamais le drain (contraire `syncAll:110`, login `AuthViewModel:54,77`) → `create_resource` racine dort jusqu'au prochain tick, badge faussement à jour.
|
||||
- **M8 — `features/sync/SafScanner.kt:146`** : `if (size == 0L) continue` → fichiers vides légitimes exclus du miroir, jamais reviewés ni poussés (perte silencieuse).
|
||||
- **M9 — `features/saf/FolderMerger.kt:45-85`** : merge multi-transactions non-atomique, non-idempotent (`createMergedFolder` recrée un dossier à chaque appel) → crash à mi-fusion = état partiel poussé, relance = dossier dupliqué côté serveur.
|
||||
|
||||
### Room / DB / Domain
|
||||
- **M10 — `domain/DeviceIdentity.kt:18-26`** : `getOrCreate()` non atomique (read/insert/re-read hors transaction) + fallback `newResourceId()` jamais persisté → deux identités concurrentes, `owner_id` incohérents, outbox sous identité fantôme (aggravé par C1).
|
||||
- **M11 — `data/local/migration/Migrations.kt:90-96`** : `MIGRATION_5_6` fait `UPDATE files SET processed = 1` sans `create_resource` rétroactif → backlog jamais poussé, invisible de la review (`getUnprocessed`) et du serveur, à vie.
|
||||
- **M12 — `data/local/dao/FolderDao.kt:50-54` + `data/local/dao/FileDao.kt:48-49`** : `@Upsert` résout sur PK (`id`) pas sur uniques `resource_id`/`uri` ; pattern read-then-upsert (`id=0`) → deux inserts concurrents même `uri` = `SQLiteConstraintException` (crash walk SAF / refresh serveur).
|
||||
- **M13 — entités `exists: Int? = null` + filtres `= 1`** (`FolderEntity.kt:36`, `FileEntity.kt:45`, `FolderDao.kt:34,41`, `FileDao.kt:15,18,21,32,42,95,98,108,135`, `Migrations.kt:51-72` sans DEFAULT) : toute ligne sans `exists` explicite disparaît UI/recherche/review — perte fonctionnelle silencieuse.
|
||||
- **M14 — `data/local/entity/PendingOperationEntity.kt:28-53` + `Migrations.kt:101-123`** : pas de colonne `device_id`, unicité locale sur `operation_id` seul vs contrat `UNIQUE(device_id, operation_id)` → après régénération `device_user_id`, rejeu = `create_resource` dupliqués serveur.
|
||||
- **M15 — `data/local/dao/PendingOperationDao.kt:38`** : `failDescendants` ne cascade que sur le même `resource_id`, pas les enfants (cf. C6).
|
||||
- **M16 — `data/local/dao/FileDao.kt:133-145` + `Migrations.kt:75-82`** : `category` ajoutée sans backfill, `getOcrAutoCandidates()` exige `category IN (…)` → tout PDF/image/texte pré-v4 exclu de l'OCR auto à vie.
|
||||
- **M17 — `data/local/dao/FileDao.kt:151-152`** : `clearOcrQueued` reset `ocr_attempts = 0` inconditionnellement (contredit commentaire `:130-132`) → échec permanent rejoué indéfiniment.
|
||||
- **M18 — pas de FK `files → folders`** (`FileEntity.kt:18-26`, `FolderEntity.kt:18-25`, `FolderDao.kt:95-96`, `FileDao.kt:92-93` deletes physiques) → `remove(dossier)` laisse orphelins, `moveToFolder` vers parent inexistant accepté, cycles possibles.
|
||||
- **M19 — `FolderDao.kt:56-57` + `FileDao.kt:51-52`** : `markMissing` = `SET exists = 0` seul (ni `sync_status` ni annulation `create` pending) → ressource disparue quand même poussée (fantôme serveur), placement `local-cloud` mensonger.
|
||||
- **M20 — `data/local/dao/ScanDao.kt:12-64` + `entity/ScanSessionEntity.kt:15-20`** : sessions `active` multiples possibles (aucun index unique/partiel), aucun `deleteSession` → doubles inserts concurrents = session orpheline + pages fuyantes.
|
||||
|
||||
### Réseau / Auth / Repos
|
||||
- **M21 — `data/repository/FileRepository.kt:261-272` + `data/remote/ApiClient.kt:64-65`** : pagination jetée (`pageSize=50` sans `page`, `meta` ignoré) alors que le serveur pagine → dossiers > 50 fichiers ne convergent jamais, silencieusement.
|
||||
- **M22 — `data/remote/ApiClient.kt:119-125`** : `catch (Exception) → NETWORK_ERROR` attrape aussi `JsonDataException` (Moshi) et `InterruptedIOException` (annulation) → parsing cassé = `retry()` infini, coroutine annulée = `ApiException` au lieu de `CancellationException` (scope/WorkManager corrompus).
|
||||
- **M23 — `data/repository/ShareRepository.kt:45,99-104` + `FolderRepository.kt:115`** : confusion `device_id` vs `user_id` — `syncSnapshot` compare `deviceIdentity.getOrCreate()` (device) à `perm.ownerId` (user serveur), `saveFolder` stocke le device dans `ownerId`, `ActiveUserStore` ignoré. Le snapshot serveur **exclut les ressources possédées** → toute ligne cloud-only au vrai `ownerId=user` est `markMissing` à chaque login/restore (ex. note `createNote(ownerId=userId)` disparaît).
|
||||
- **M24 — `features/sync/OutboxSyncWorker.kt:159-170` + `data/repository/OutboxRepository.kt:29-31`** : round-trip `expiresAt` Long→Double (Moshi `Map<String,Any?>`) → `enqueueShare(expiresAt: Long)` réémis `1.7E12` → serveur `*int64` refuse → `400 INVALID_REQUEST` → **tout partage avec expiration dead-lettered**.
|
||||
- **M25 — `ui/auth/AuthViewModel.kt:43,123-125`** : callback 401 singleton possédé par un ViewModel (`apiClient.onUnauthorized`, `ApiClient` `@Singleton` survit au VM, annulé dans `onCleared`) → après destruction, 401 ne purge plus la session → token expiré réutilisé, worker `success()` sur 401 fige l'outbox, utilisateur jamais déconnecté.
|
||||
- **M26 — `domain/ServerConfigStore.kt:32-43` + `data/remote/ServerUrlInterceptor.kt:25-38`** : race `load()` — interceptor lit `current` (défaut `10.0.2.2`) sur thread OkHttp pendant que `load()` restaure l'URL ; `registerDevice()` part avant `load()` → cold start avec URL custom = premières requêtes (y compris `Authorization: Bearer` restauré) vers l'hôte par défaut (**fuite du bearer**).
|
||||
- **M27 — `data/repository/ShareRepository.kt:44-93` + `data/remote/dto/Dtos.kt:120-132`** : snapshot permissions sans delta (`after` jamais passé), `sharedById`/`expiresAt` en `Any?` jamais lus, `cachedAt` jamais persisté, aucun downgrade 24h ni `canAccess` → grant révoqué/expiré reste visible et ouvrable (`404`) jusqu'au prochain login.
|
||||
- **M28 — `domain/ServerConfigStore.kt:46-59`** : `set()` persiste URL non validée (`"http://"` → `"http:"`, `"foo bar"` → `"http://foo bar"`) → app semi-brickée jusqu'à correction manuelle (recoupé par 2 agents).
|
||||
|
||||
### UI / Navigation / VM
|
||||
- **M29 — `ui/folderlist/FolderListScreen.kt:202+220`** : onboarding racine bloqué après rotation — `pendingDefaultPick` en `remember` (non-saveable), `LaunchedEffect` polling annulé à la rotation, import SAF continu en fond mais `setDefaultRoot()` jamais rappelé → écran figé sur `DefaultRootOnboarding`, re-picker = doublon d'import.
|
||||
- **M30 — `ui/document/DocumentViewerScreen.kt:130-137`** : position pager perdue à la rotation (`jumpPending = remember`), re-scroll vers `initialResourceId` → page N → retour page initiale. Fix : `rememberSaveable` / mémoriser index courant.
|
||||
- **M31 — `ui/search/SearchScreen.kt:276-284` + `SearchViewModel.kt:55-72`** : `TextField` branché sur la valeur **debouncée** (300 ms) → frappe affichée par à-coups, IME/autocorrect écrasés. Correct : champ sur requête brute, debounce pour Room seule.
|
||||
- **M32 — `ui/folderdetail/FolderDetailScreen.kt:196-202`** : Partager sans gate `isShareable` (contraire FolderList `canShare`, `:154-159`) → partage d'un dossier local-only/reçu = op `share` vouée au dead-letter `NOT_FOUND`.
|
||||
- **M33 — `ui/folderlist/FolderListViewModel.kt:165-173`** : `canShare` stale au login/logout (combine `_defaultRootId`/`_browseFolderId` sans token/auth) → « Partager » reste désactivé jusqu'à navigation après connexion depuis Réglages.
|
||||
- **M34 — `ui/folderlist/FolderListScreen.kt:333-375 vs 326-330`** : suppression multi-dossiers filtre les items **visibles** alors que `selection.ids` survit à `openBrowseFolder` (jamais clear) → sélection hors-vue abandonnée silencieusement avec snackbar succès. Même classe `ui/search/SearchScreen.kt:290-305` (chips actifs en mode sélection, delete par snapshot).
|
||||
- **M35 — `ui/document/DocumentViewerScreen.kt:131-144`** : pas de clamp après suppression — supprimer le dernier doc (page 2/2) laisse `pagerState` hors bornes → viewer vide au lieu de retomber sur 1er ou `onBack`.
|
||||
- **M36 — `ui/settings/SettingsScreen.kt:120-128`** : préférence `SYSTEM` inatteignable (Switch DARK/LIGHT depuis `darkNow`, store + thème supportent SYSTEM) → impossible de revenir à « suivre le système ».
|
||||
- **M37 — `ui/settings/SettingsViewModel.kt:30-36`** : `load()` écrase une saisie serveur en cours (`_serverUrl` init défaut puis réassigné après `load()` en `init`).
|
||||
|
||||
### Scan / PDF / Review / Thumbnails
|
||||
- **M38 — `data/repository/ScanRepository.kt:63-78`** : `addPage` avec `sortOrder = pageCount` → doublons après suppression (`ORDER BY sort_order` instable, `swapOrder` ambigu). Cause : compteur au lieu de `MAX+1`.
|
||||
- **M39 — `ui/scan/ScanViewModel.kt:180/199`** : dimensions stockées (pré-scale) ≠ réelles (downscale 2400px dans `process()`) → fiche `W×H` fausse pour grands quads.
|
||||
- **M40 — `ui/scan/ScanViewModel.kt:177-203`** : écriture JPEG hors transaction Room (orphelins si insert échoue) ; `deletePage` supprime le fichier **avant** la ligne DB (crash = ligne vers fichier absent → rejoint C8).
|
||||
- **M41 — `data/repository/FileRepository.kt:206`** : `saveLocalFile` ne remonte jamais `cloud` → `local-cloud` (`existing?.syncStatus ?: …`) → fichier cloud-only réimporté en SAF reste badgé « cloud », ignoré vignette/OCR (`sync_status='local-cloud'` requis, `FileDao.kt:137`).
|
||||
- **M42 — `ui/pdfbuilder/PdfBuilderViewModel.kt:227-237`** : PDF assemblé importé `processed=false` (défaut omis, contraire export scan `true`) → atterrit en review alors que l'utilisateur vient de le construire.
|
||||
- **M43 — `ui/review/SwipeReviewViewModel.kt:68-74,94-100`** : retrait optimiste sans réinsertion sur échec (`keep`/`markAllProcessed`, contraire `delete` qui réinsère) → carte perdue jusqu'au prochain `load()` (init seule).
|
||||
- **M44 — `ui/pdfbuilder/PdfBuilderScreen.kt:248`** : `remember(files)` réinitialise la sélection à chaque update Room → cases cochées effacées pendant un refresh serveur.
|
||||
- **M45 — `ui/pdfbuilder/PdfBuilderEngine.kt:104-107`** : pages PDF sources plafonnées à 1200pt malgré commentaire « format conservé » (`min(1, 1200/max, 3000/max)`, le 1200 gagne toujours) → pixellisation A3/300dpi.
|
||||
- **M46 — `features/scan/CornerGeometry.kt:19-26`** : `orderPoints` sans validation dégénérescence (doublons/quad aplati) → `outputSize = 0` → bitmap 1×1 validé (page blanche) au lieu d'erreur.
|
||||
- **M47 — `ui/scan/CameraStage.kt:162-181`** : overlay calibré sur flux `ImageAnalysis` (hypothèse `FILL_CENTER`) alors que `PreviewView` affiche le flux `Preview` (ratio/crop différents) → quad décalé systématiquement quand les ratios diffèrent.
|
||||
- **M5 — `features/saf/FileDeleter.kt:88-104` + `features/saf/FolderDeleter.kt:91-103`** : `deleteInCloud` sans tombstone locale (`exists` reste 1) → ressource toujours affichée, walk la revoit, `refreshFromServer` ne supprime jamais de lignes → fantôme local vs serveur supprimé.
|
||||
- **M9 — `features/saf/FolderMerger.kt:59,65-101`** : merge toujours multi-transactions (create, moves, deletes séparés) ; seule idempotence `findExistingMerged:154-161` ajoutée, pas d'atomicité → crash à mi-fusion = état partiel poussé.
|
||||
- **M13 — entités `exists: Int? = null` + filtres `= 1`** (`FolderEntity.kt:36`, `FileEntity.kt:46`, `FolderDao.kt:43,50`, `FileDao.kt:27,44`) : toute ligne sans `exists` explicite disparaît UI/recherche/review — perte fonctionnelle silencieuse.
|
||||
- **M27 — `data/repository/ShareRepository.kt:47` + `data/remote/dto/Dtos.kt:150-151`** : snapshot permissions sans delta (`after` jamais passé), `sharedById`/`expiresAt` en `Any?` jamais lus, `cachedAt` jamais persisté, aucun downgrade 24h ni `canAccess` → grant révoqué/expiré reste visible et ouvrable (`404`) jusqu'au prochain login.
|
||||
|
||||
---
|
||||
|
||||
## 🟡 Mineurs (UX, perf, dette)
|
||||
## 🟡 Mineurs restants (8) — ✅ tous corrigés le 2026-09-24 (162/162 tests verts)
|
||||
|
||||
### Sync / Worker / SAF
|
||||
- **m1 — `features/sync/SyncViewModel.kt:103-121`** : `_walkInProgress` sans `finally` (reste `true` si scope annulé) → badge « syncing » collé ; la fenêtre inclut l'appel réseau partage.
|
||||
- **m2 — `features/sync/SyncViewModel.kt:106-112`** : `OutboxSyncWorker.enqueue` + `OcrAutoWorker.enqueue` à chaque tick même sans changement → réveils WorkManager / 30s pour rien.
|
||||
- **m3 — `features/sync/OutboxSyncWorker.kt:97-100`** : 401 → `success()` sans re-signal, ops pendantes figées jusqu'au prochain tick/login (bénin, `AuthViewModel` ré-enqueue au re-login).
|
||||
- **m4 — `features/sync/SafScanner.kt:132-139`** : `cursor.getString(iDoc)` sans garde `iDoc == -1`, `name` plateforme-nullable déréférencé → provider dégénéré = crash de tout `scanTree` à chaque tick.
|
||||
- **m5 — `features/sync/DeviceSync.kt:75-137`** : « transaction courte » en réalité géante (N upserts + `getAll()` dossiers **et** fichiers par racine, O(racines×DB) sous verrou écriture) → lecteurs Room bloqués, jank/ANR sur grosses arborescences.
|
||||
- **m6 — `features/saf/FolderDeleter.kt:74-88`** : `deleteLocally` multi-writes hors transaction (contraire `treeMarkMissing`) → kill à mi-chemin = `exists` partiel.
|
||||
- **m1 — `features/sync/SyncViewModel.kt:108-133`** : `_walkInProgress` sans `finally` dans la boucle (reste `true` si scope annulé ; seul `importRoot:173` a un `finally`) → badge « syncing » collé ; la fenêtre inclut l'appel réseau partage.
|
||||
- **m2 — `features/sync/SyncViewModel.kt:110-116`** : `OutboxSyncWorker.enqueue` + `OcrAutoWorker.enqueue` à chaque tick même sans changement → réveils WorkManager / 30s pour rien.
|
||||
- **m5 — `features/sync/DeviceSync.kt:76-162`** : « transaction courte » en réalité géante (N upserts + `getAll()` dossiers **et** fichiers par racine sous verrou écriture) → lecteurs Room bloqués, jank/ANR sur grosses arborescences.
|
||||
|
||||
### Room / Domain / DI
|
||||
- **m7 — `data/local/dao/FileDao.kt:30-37`** : `searchWithFilters` `LIKE` brut sans `ESCAPE`, casse ASCII-only → `%`/`_` = jokers (match-all), « ete » ne trouve pas « ÉTÉ ».
|
||||
- **m8 — `data/local/FileOrdering.kt:5-11`** : tri mémoire (`referenceDate` seule) divergent du SQL (`name ASC` tiebreak, `FileDao.kt:21,43`) ; `lastModified = 0` SAF trié comme plus vieux → ordre incohérent + fichiers `0` enfouis.
|
||||
- **m9 — `data/local/dao/PendingOperationDao.kt:30-32`** : commentaire `MAX_PENDING_ATTEMPTS` contredit le code (`markFailed()` = dead-letter immédiate, `attempts` diagnostique) — trompeur pour futurs appelants (cohérent avec worker, seul le commentaire est faux).
|
||||
- **m10 — `data/local/dao/FileDao.kt:89`** : `updateUri` ne touche pas `updated_at` → ordre de convergence faussé après move.
|
||||
- **m11 — `domain/LocalModeStore.kt:24`** : `get()` teste `!= null` au lieu de `== "1"` → toute valeur parasite (`"0"`, `""`) = mode local actif à tort.
|
||||
- **m12 — `domain/ServerConfigStore.kt:40-44` + `domain/ThemePreferenceStore.kt:28-32`** : `load()` once-only (`AtomicBoolean`, sans réarmement) → après wipe/logout, URL/thème périmés en mémoire.
|
||||
- **m13 — `domain/ThemePreferenceStore.kt:34-39`** : `set()` publie le `StateFlow` avant succès DB → divergence UI/DB si upsert échoue.
|
||||
- **m14 — `domain/PrefKeys.kt:8`** : clé `SYNC_MODE` morte (0 usage, grep vérifié) → dérive spec/impl.
|
||||
- **m15 — `di/DatabaseModule.kt:25-28`** : aucune stratégie de downgrade → APK plus ancien sur DB v11 = crash `IllegalStateException` au lieu de dégradation contrôlée.
|
||||
- **m16 — index composites manquants** (`PendingOperationEntity.kt:20-27`, `FileEntity.kt:18-26`, `PendingOperationDao.kt:13`, `FileDao.kt:133-145`) : `selectPending` et `getOcrAutoCandidates` = full-table scan → jank/batterie à 10k lignes.
|
||||
- **m17 — `data/local/entity/FileEntity.kt:56-57` vs `Migrations.kt:92`** : `processed` sans `defaultValue` Room alors que la migration met `DEFAULT 0` (contraire `createdInApp`, `FolderEntity.kt:43`) → fresh-install ≠ migré.
|
||||
- **m18 — `data/local/dao/ScanDao.kt:48-57`** : `swapOrder` sans contrôle d'appartenance ni transaction → swap inter-sessions corrompt `sort_order`, concurrence = doublons.
|
||||
- **m19 — `data/local/AppDatabase.kt:27-34`** : `exportSchema = false`, migrations non snapshotées → dérives indétectables en CI.
|
||||
- **m20 — `data/repository/OcrRepository.kt:66-73`** : `poll()` infini (`while(true)` + 3s, sans timeout) alors qu'un job peut rester `processing` 15 min (stale claim serveur) → coroutine tenue indéfiniment.
|
||||
- **m21 — `data/repository/OutboxRepository.kt`** : ops contrat non émissibles (`update_metadata`, `update_share`, `create_link`, `revoke_link` — §6.1 = 9 ops, 5 helpers) → rename partagé, update share, liens publics inopérants.
|
||||
- **m22 — `data/remote/ApiService.kt`** : endpoints contrat absents (`PATCH /users/me/password`, `GET/DELETE /files/:id`, `GET /files/search`, `GET /shares/links/:token`) → changement mot de passe impossible avec tokens 7j non révoqués.
|
||||
- **m23 — `data/repository/AuthRepository.kt:21-35`** : `registerDevice` best-effort avale tout (y compris 400/429) → `INVALID_DEVICE_ID`/`RATE_LIMITED` invisibles, 401 trompeur plus tard.
|
||||
- **m24 — `ui/auth/AuthViewModel.kt:52-55`** : `registerDevice()` émis même en mode local (pas de garde contrairement à `syncSnapshot`).
|
||||
- **m25 — `di/NetworkModule.kt:37-43`** : logging `BASIC` en DEBUG loggue les query PII (`GET /users/resolve?username=…`) dans logcat.
|
||||
- **m26 — `data/remote/AuthInterceptor.kt:20-26`** : `Bearer` joint aux routes publiques (`POST /devices`, `POST /auth/login`) — serveur l'ignore mais hygiène + amplification de la fuite M26.
|
||||
- **m27 — `auth/SessionManager.kt:33-38`** : `expiresAt` du login jeté (paseto TTL 7j) → expiration découverte par 401 brutal, impossible de pré-relancer.
|
||||
- **m28 — `auth/SecureTokenStore.kt:27-36`** : init Keystore/`EncryptedSharedPreferences` au construct Hilt + I/O synchrone possiblement Main (`MasterKeys` déprécié) → ANR au restore, crash Direct Boot avant déverrouillage.
|
||||
- **m7 — `data/local/dao/FileDao.kt:45`** : `searchWithFilters` `LIKE` brut sans `ESCAPE`, casse ASCII-only → `%`/`_` = jokers (match-all), « ete » ne trouve pas « ÉTÉ ».
|
||||
- **m15 — `di/DatabaseModule.kt:25-28`** : aucune stratégie de downgrade → APK plus ancien sur DB v14 = crash `IllegalStateException` au lieu de dégradation contrôlée.
|
||||
- **m19 — `data/local/AppDatabase.kt:36-37`** : `version=14, exportSchema=false`, migrations non snapshotées → dérives indétectables en CI.
|
||||
|
||||
### UI
|
||||
- **m29 — `ui/navigation/NavGraph.kt:50`** : `pdfBuilder(listOf())` → `"pdfbuilder/"` ne matche pas `"pdfbuilder/{ids}"` (protégé aujourd'hui par `enabled = ids.isNotEmpty()` — contrat implicite fragile).
|
||||
- **m30 — `ui/navigation/NavGraph.kt:53-59,165`** : `folder/…` sans `launchSingleTop` → double-tap = doublon de pile.
|
||||
- **m31 — `ui/navigation/KazierApp.kt:54-63`** : `rememberNavController()` par branche SignedIn↔Local → `signOutToLocal()` perd la position d'exploration (hoister le controller).
|
||||
- **m32 — `ui/folderdetail/FolderDetailScreen.kt:395-429`** : dossiers non sélectionnables dans le détail (vs FolderList) — incohérence partage/multi-suppression inter-écrans.
|
||||
- **m33 — `ui/pdfbuilder/PdfBuilderScreen.kt:104-114`** : `LaunchedEffect(buildPhase)` rejoue side-effects à la recomposition racine (rotation → `Failed` re-snackbar, `Saved` re-`onOpenDocument` = double navigation possible).
|
||||
- **m34 — dialogs `remember` perdus à la rotation** (`SyncStatusBadge.kt:129`, `showDeleteWarning/Confirm`, `showMoveDialog`, `showShareSheet`, `showNameDialog`) — sûr mais UX ; `showOcrDialog` en `rememberSaveable` = bon exemple.
|
||||
- **m35 — `ui/components/WatchedFoldersBadge.kt:36-40` + `WatchedFoldersViewModel.kt:25-27`** : double instance VM + `SharingStarted.Eagerly` collecte Room en continu même sur autres onglets.
|
||||
- **m36 — `ui/settings/SettingsViewModel.kt:43-48`** : `onServerUrlChange` écrit en prefs à chaque frappe (churn IO) ; commentaire `testConnection` obsolète.
|
||||
- **m37 — `MainActivity.kt:27-33`** : `themePreferenceStore.load()` fire-and-forget → flash de thème aux premières frames.
|
||||
- **m38 — `ui/navigation/NavGraph.kt:213-219`** : bandeau import global chevauchant la FloatingNavBar, doublon des indicateurs par-écran.
|
||||
- **m39 — `ui/pdfbuilder/PdfBuilderViewModel.kt:236`** : `syncStatus="local"` en littéral au lieu de `FileStatus.LOCAL` — fonctionne mais casse silencieusement à toute renommée.
|
||||
### Sync contrat / OCR
|
||||
- **m20 — `data/repository/OcrRepository.kt:66-73`** : `poll()` infini (`while(true)` + 3s, sans timeout) alors qu'un job peut rester `processing` longtemps (stale claim serveur) → coroutine tenue indéfiniment.
|
||||
- **m21 — `data/repository/OutboxRepository.kt:72-147`** : ops contrat non émissibles (`update_metadata`, `update_share`, `create_link`, `revoke_link` — §6.1 = 9 ops, helpers partiels) → rename partagé, update share, liens publics inopérants.
|
||||
|
||||
### Scan / PDF / Thumbnails
|
||||
- **m40 — `ui/scan/CameraStage.kt:86-91`** : `ImageCapture` forcé 1920×1080 paysage → sur portrait, bitmap pleine-rés + copie tournée (×2 mémoire ~16 Mo) → OOM petits devices.
|
||||
- **m41 — `ui/scan/CameraStage.kt:165-181`** : `toBitmap()` pleine-rés à chaque frame d'analyse (~30fps) puis downscale interne → churn GC + batterie.
|
||||
- **m42 — `ui/scan/CameraStage.kt:99-101`** : `addOnLayoutChangeListener` jamais retiré → fuite mineure du listener.
|
||||
- **m43 — `ui/scan/CameraStage.kt:200-211`** : `when` rotation sans `else` → angle inattendu = copie silencieuse au lieu d'erreur.
|
||||
- **m44 — `ui/scan/ScanGeometry.kt:42-69`** : division par zéro si `sourceRect` dégénérée (`Infinity/NaN` dans le quad ; inatteignable via `initialViewport` mais API publique exposée).
|
||||
- **m45 — `ui/scan/CropStage.kt:188-193`** : arrondi `roundToInt` viewport indépendant de l'offset → dépassement 1px en bordure (frange noire sur images impaires).
|
||||
- **m46 — `ui/scan/ScanViewModel.kt:111-122`** : `combine(pages, pageCount)` avec count ignoré → réassignations `_pages` redondantes.
|
||||
- **m47 — `ui/scan/ScanViewModel.kt:409-418`** : `abandon()` laisse sessions vides `ABANDONED` jamais purgées + `sessionDir()` fait `mkdirs()` en getter (recrée ce qu'on supprime).
|
||||
- **m48 — `data/repository/ScanRepository.kt:27-40`** : race `getOrCreateActiveSession` (double `active` possible, aucune unicité partielle ; fenêtre étroite).
|
||||
- **m49 — `domain/FileCategory.kt:19-27`** : CSV classé `TEXT` (par MIME) ou `OFFICE` (par extension) selon le chemin → icône/filtres/OCR divergents pour le même fichier.
|
||||
- **m50 — `features/thumbnails/ThumbnailStore.kt:51`** : map de `Mutex` jamais purgée → fuite lente par `resourceId`.
|
||||
- **m51 — `features/thumbnails/ThumbnailStore.kt:104-112`** : `.tmp` orphelin si `renameTo` échoue → résidus `*.webp.tmp`.
|
||||
- **m52 — `features/thumbnails/ThumbnailStore.kt:83-87`** : `isUpToDate` sur `mtime` seule (granularité seconde SAF) → vignette périmée après édition rapide (pas de taille/hash).
|
||||
- **m53 — `ui/pdfbuilder/PdfBuilderEngine.kt:121-124`** : `renderer?.close()` non protégé (si `close()` lève, `pfd.close()` sautée → fd leak ; `ThumbnailStore.renderPdfPage` fait `runCatching`).
|
||||
- **m54 — `features/scan/CornerGeometry.kt:40-45`** : commentaire « moyenne » mais code `max` → warp légèrement étiré vs réel.
|
||||
- **m55 — `features/scan/ScanImageProcessor.kt:126-181`** : mats de contours non libérés sur exception (`c.release()` chemin nominal seul) → fuite native OpenCV.
|
||||
- **m56 — `ui/review/SwipeReviewViewModel.kt:52-64`** : échec de reload écrase le deck (`update{cards=files}` même sur `emptyList` d'erreur) → deck vidé à tort.
|
||||
---
|
||||
|
||||
## 🛠️ Plans de correction (reliquat) — ✅ implémentés le 2026-09-24
|
||||
|
||||
Ordre suivi : M13 → M5 → M27+m21 → M9 → mineurs par lot (m1+m2, m5, m7, m20, m15+m19).
|
||||
Écarts d'implémentation vs plan : M13 sans rewrite (colonne restée nullable, défaut Kotlin 1 + backfill — pas de bump de contrainte) ; m7 `COLLATE NOCASE` sans colonne normalisée (repli Unicode « ete » → « ÉTÉ » toujours ouvert, voir suivi) ; M27 `cachedAt` persisté = heure locale du pull (pas l'horloge serveur, skew).
|
||||
|
||||
### M5 — `deleteInCloud` sans tombstone locale
|
||||
Fichiers : `features/saf/FileDeleter.kt:88-104`, `features/saf/FolderDeleter.kt:91-103` (+ descendants via `collectDescendants`).
|
||||
Constat : `deleteInCloud` enqueue `delete_resource` mais laisse `exists = 1` ; la ressource reste affichée et le walk la revoit.
|
||||
Plan :
|
||||
1. Dans `FileDeleter.deleteInCloud`, après `enqueueDeleteResource`, appeler `fileRepository.markMissing(resourceId, now)` dans la même transaction Room (ou `appDatabase.withTransaction` comme `deleteFull`).
|
||||
2. Dans `FolderDeleter.deleteInCloud`, idem pour le dossier ET sa descendance Room (`treeMarkMissing`-léger : `markMissing` sur fichiers + sous-dossiers, sans `delete_resource` supplémentaire sauf si `hasSyncedCreateOperation`).
|
||||
3. Vérifier que le walk ne ressuscite pas : les lignes `exists = 0` + `delete_resource` pending doivent être ignorées par la réconciliation (garde `hasPendingDeleteOperation`, cf. `OutboxRepository.kt:204`).
|
||||
4. UI : vérifier que les listes filtrent `exists = 1` (déjà le cas) → la ligne disparaît aussitôt.
|
||||
Tests : étendre `ProcessedGateTest` ou nouveau `DeleteInCloudTest` — `deleteInCloud` puis assert `exists == 0` + op `delete_resource` présente ; walk simulé ne ressuscite pas.
|
||||
|
||||
### M9 — `FolderMerger` multi-transactions non-atomique
|
||||
Fichier : `features/saf/FolderMerger.kt:53-106`.
|
||||
Constat : `createMergedFolder` (transaction 1), moves (N transactions via `FileMover`/`reparentSubFolders`), deletes (N transactions). Un crash à mi-fusion laisse un état partiel ; la relance est idempotente (dossier réutilisé) mais ne reprend pas les moves manquants proprement.
|
||||
Plan :
|
||||
1. Envelopper `mergeSelectedFolders` dans `appDatabase.withTransaction` pour la partie Room (create + reparent + `treeMarkMissing`) — nécessite d'injecter `AppDatabase` dans `FolderMerger` et de rendre `FileMover.moveFiles` / `reparentSubFolders` appelables dans une transaction existante (ou journaliser les `move_resource`/`delete_resource` dans la transaction et n'exécuter le SAF physique qu'avant/après selon le sens crash-safe : journal-first comme C4).
|
||||
2. Ordre crash-safe : (a) transaction Room = create + moves logiques + deletes logiques (`exists = 0` + outbox), (b) exécution SAF physique (moves + deletes), (c) sweep au prochain tick pour les physiques manqués (réutiliser `sweepPendingPhysicalDeletes`).
|
||||
3. Garder l'idempotence `findExistingMerged` pour les relances.
|
||||
4. À défaut d'une transaction unique (SAF non transactionnel), a minima : rendre chaque étape reprise-safe (skip les sources déjà vides, skip les moves déjà journalisés via `hasPendingMoveOperation`).
|
||||
Tests : nouveau `FolderMergerTest` — fusion 2 dossiers avec fichiers + sous-dossier, assert `movedFiles/deletedFolders`, relance idempotente (pas de doublon), crash simulé entre étape 2 et 3 → reprise sans perte.
|
||||
|
||||
### M13 — `exists: Int? = null` invisible
|
||||
Fichiers : `data/local/entity/FolderEntity.kt:36`, `data/local/entity/FileEntity.kt:46`, DAO (`FolderDao`, `FileDao` filtres `= 1`), `Migrations.kt` (créations tables sans `DEFAULT 1` / `NOT NULL`).
|
||||
Constat : toute ligne insérée sans `exists` explicite (défaut Kotlin `null`) est cachée par les requêtes `WHERE exists = 1`.
|
||||
Plan :
|
||||
1. Durcir les entités : `exists: Int = 1` (non-null, défaut 1) dans `FolderEntity` et `FileEntity`.
|
||||
2. Migration v14→v15 : `UPDATE folders SET exists = 1 WHERE exists IS NULL`, idem `files`, puis recréation ou `NOT NULL DEFAULT 1` (Room : via `autoMigrations` ou SQL `ALTER` + table rewrite selon la version SQLite ; le plus simple : `UPDATE` + contrainte applicative + défaut entité, sans rewrite si Room accepte le changement nullable→non-null via migration manuelle avec recréation de table).
|
||||
3. Auditer tous les `saveFolder`/`saveLocalFile`/`upsertShared*` pour passer `exists = 1` explicitement.
|
||||
4. Option : ajouter un test `ExistsDefaultTest` — insert sans `exists`, assert visible dans `observeByFolder`/`searchWithFilters`.
|
||||
Note : migration à tester via `Migration13To14Test`-style (nouveau `Migration14To15Test`) + `:app:testDebugUnitTest`.
|
||||
|
||||
### M27 — snapshot permissions sans delta ni `canAccess`
|
||||
Fichiers : `data/repository/ShareRepository.kt:44-47`, `data/remote/dto/Dtos.kt:144-156` (`sharedById`/`expiresAt: Any?`), `data/remote/ApiService.kt:74-78`, `ApiClient.kt:106-108`.
|
||||
Constat : `syncPermissions()` sans `after`, champs `sharedById`/`expiresAt` jamais lus, `cachedAt` jamais persisté, aucun downgrade TTL 24h ni `canAccess` → grants révoqués/expirés visibles jusqu'au prochain login.
|
||||
Plan :
|
||||
1. DTO : typer `sharedById: String?`, `expiresAt: Long?` (le serveur renvoie ms epoch ou null — vérifier `docs/api-v1.md §6.2` et adapter avec un adapter Moshi tolérant `Any?`→Long).
|
||||
2. Persistance : stocker `cachedAt`/`expiresAt`/`sharedById`/`effectiveAccess` — soit colonnes sur `files`/`folders`, soit nouvelle table `resource_permissions` (préférable : ne pas polluer les entités). A minima `user_preferences` : `permissions_cached_at`.
|
||||
3. Delta : `syncSnapshot(after: Long? = cachedAt)` → `apiClient.syncPermissions(after)` ; pull complet (`after = null`) au login/restauration + quand `now - cachedAt > 24h` (TTL).
|
||||
4. Expiration locale : au tick, marquer `exists = 0` les lignes dont `expiresAt < now` ; downgrade lecture seule après TTL sans reseed (gate `canAccess` : à exposer via `ShareRepository.canAccess(resourceId, required)` utilisé par les VM avant open/share/rename).
|
||||
5. `canAccess` : ranking viewer < commenter < editor < owner, `ownerId == currentUser` → owner.
|
||||
Tests : étendre `ShareRepositoryTest` — delta `after`, révocation (absent du snapshot → `markMissing`), expiration (`expiresAt` passé → masqué), `canAccess` ranking.
|
||||
|
||||
### m1+m2 — badge sync et réveils WorkManager
|
||||
Fichier : `features/sync/SyncViewModel.kt:100-137`.
|
||||
Plan :
|
||||
1. m1 : envelopper le corps de boucle dans `try { … } finally { _walkInProgress.value = false }` (comme `importRoot:173-176`), et sortir `syncSnapshot` de la fenêtre `_walkInProgress` (flag séparé ou `syncing` = walk || drain déjà calculé via WorkManager).
|
||||
2. m2 : n'enqueuer `OutboxSyncWorker`/`OcrAutoWorker` que si le tick a produit quelque chose (`results.any { folders+files+missing > 0 }` ou `pendingOperationDao.countPending() > 0` / fichier promu). Éviter les réveils /30s à vide.
|
||||
Tests : Robolectric `SyncViewModelTest` — annulation du scope → flag retombe ; tick sans changement → `WorkManager` non sollicité (mock/static ou extraction d'un `SyncScheduler` testable).
|
||||
|
||||
### m5 — walk : transaction géante + `getAll()` par racine
|
||||
Fichier : `features/sync/DeviceSync.kt:67-163`.
|
||||
Plan :
|
||||
1. Découper la phase 2 : upserts dossiers/fichiers par batch (ex. 200) en transactions courtes successives au lieu d'une transaction unique ; la réconciliation `missing` en passe séparée.
|
||||
2. Remplacer `folderRepository.getAll()` + `fileRepository.getAll()` (full-table scan par racine) par des requêtes scopées à la racine (`getByRootUri`/`getDescendants`) — à ajouter aux DAO avec index sur `uri` (déjà unique) ; filtrer en SQL plutôt qu'en mémoire (`isChildOf` en `LIKE rootUri || '/%'`).
|
||||
3. Conserver le `Mutex` single-flight ; vérifier `ensureActive()` dans les boucles longues pour annulation propre.
|
||||
Tests : `SafScannerTest`-style perf — 5k fichiers simulés, assert temps/absence d'ANR ; test de convergence identique avant/après.
|
||||
|
||||
### m7 — recherche `LIKE` sans `ESCAPE`
|
||||
Fichier : `data/local/dao/FileDao.kt:42-49`.
|
||||
Plan : échapper `%`, `_`, `\` dans `:query` côté repository (`searchFiles`) + `LIKE … ESCAPE '\'` dans la requête ; ajouter `COLLATE NOCASE` (ou normalisation) pour « ete » → « ÉTÉ ». Tester : `%`, `_`, `\`, accents, casse.
|
||||
Tests : `SearchFieldTest` ou nouveau `SearchEscapeTest` — `%` littéral ne matche pas tout, `_` littéral, insensible à la casse.
|
||||
|
||||
### m20 — `OcrRepository.poll()` infini
|
||||
Fichier : `data/repository/OcrRepository.kt:66-73`.
|
||||
Plan : ajouter timeout (ex. 10 min) + nombre max de polls + backoff ; lever `OcrTimeoutException` ou retourner le dernier état ; coopérer avec l'annulation (`ensureActive`). Mettre à jour les appelants (viewer auto) pour afficher « OCR indisponible, réessayer ».
|
||||
Tests : `OcrRepositoryTest` — job restant `processing` → timeout au bout de N polls (fake `ApiClient` + virtual time/delays courts).
|
||||
|
||||
### m15+m19 — robustesse DB (downgrade + `exportSchema`)
|
||||
Fichiers : `di/DatabaseModule.kt:25-28`, `data/local/AppDatabase.kt:31-38`.
|
||||
Plan :
|
||||
1. m19 : `exportSchema = true` + `schemas/` commité ; ajouter un test `Migration13To14Test`-style qui échoue en cas de dérive (CI).
|
||||
2. m15 : stratégie downgrade explicite et documentée — soit `fallbackToDestructiveMigrationOnDowngrade()` (avec avertissement perte de données locales, acceptable car miroir SAF + outbox non poussée à préserver → plutôt refuser le démarrage avec message), soit crash contrôlé avec écran « mettez à jour l'app ». Choisir et documenter ; ne jamais laisser `IllegalStateException` brut.
|
||||
Tests : build avec `exportSchema=true` + `room.schemaLocation` ; test downgrade (ouverture v15 avec APK v14 → comportement attendu).
|
||||
|
||||
### m21 — ops contrat non émissibles
|
||||
Fichiers : `data/repository/OutboxRepository.kt:72-147`, `data/local/entity/PendingOperationEntity.kt:76-86` (constantes déjà présentes : `UPDATE_METADATA`, `UPDATE_SHARE`, `CREATE_LINK`, `REVOKE_LINK`).
|
||||
Plan : ajouter `enqueueUpdateMetadata(resourceId, resourceType, name?)`, `enqueueUpdateShare(...)`, `enqueueCreateLink(resourceId, resourceType, token, access, expiresAt?)`, `enqueueRevokeLink(...)` avec payloads §6.1 (`granteeUserId/access/inherit/expiresAt`, `token/access/expiresAt`) ; brancher les appelants (rename partagé, update share, liens publics) ; `GenerateId` pour `token` 32-hex côté client.
|
||||
Tests : `OutboxSyncWorkerTest`-style — sérialisation payload, `normalizePayloadNumbers` (`expiresAt` Long exact, non `1.7E12`), round-trip `POST /sync/ops` mocké.
|
||||
|
||||
---
|
||||
|
||||
@@ -195,7 +151,7 @@ Repro : device sans lib OpenCV → valider un crop → crash au retour caméra.
|
||||
- Ordre interceptors `serverUrl → auth → logging`, `BASIC` ne log ni headers ni bodies — OK.
|
||||
- Contrat HTTP conforme sur endpoints déclarés (query `folderId/page/pageSize`, `deviceId` camel vs `device_id` login, multipart `file`/`resourceId`/`folderId`, enveloppes `{data,meta}`/`{error:{code,message}}`, codes) — OK.
|
||||
- `device_id` claim jamais utilisé comme preuve, seul le `Bearer` parle — conforme middleware.
|
||||
- Worker no-op en mode local (`OutboxSyncWorker.kt:71`), batch 20 ≤ 100 serveur, statuts OCR, `resolveUser` trim compatible, password jamais trimé — OK.
|
||||
- Worker no-op en mode local (`OutboxSyncWorker.kt:111`), batch 20 ≤ 100 serveur, statuts OCR, `resolveUser` trim compatible, password jamais trimé — OK.
|
||||
- Deep-links : aucun défini (absence, pas de bug) ; args nav `folderResourceId`/`documentResourceId`/`ids` cohérents, 32-hex sans `/`.
|
||||
- Hilt : `MainActivity @AndroidEntryPoint`, tous `hiltViewModel()` ↔ `@HiltViewModel`, scopes corrects — aucune injection manquante.
|
||||
- Pas de recomposition infinie trouvée ; `collectAsStateWithLifecycle` partout ; placeholder cloud-only correct (`DocumentContentViewer.kt:39-47`) ; recherche 100 % locale conforme V1 ; back stack onglets correct (`saveState`/`restoreState`) ; `SelectionState` volatile documenté volontaire.
|
||||
|
||||
@@ -21,9 +21,32 @@ set -euo pipefail
|
||||
./gradlew :app:assembleDebug -q
|
||||
APK="app/build/outputs/apk/debug/app-debug.apk"
|
||||
if [ "${usage_target?}" = "emulator" ]; then
|
||||
adb -e install -r "$APK"
|
||||
ADB_FLAGS=(-e)
|
||||
else
|
||||
adb -d install -r "$APK"
|
||||
ADB_FLAGS=(-d)
|
||||
fi
|
||||
# adb natif s'il fonctionne (PATH + binaire exécutable sur cet OS)...
|
||||
if command -v adb >/dev/null 2>&1 && adb version >/dev/null 2>&1; then
|
||||
adb "${ADB_FLAGS[@]}" install -r "$APK"
|
||||
# ...sinon repli NixOS : l'adb du SDK est un binaire FHS dynamiquement
|
||||
# lié, on l'exécute via steam-run (cf. local.properties pour sdk.dir).
|
||||
elif command -v steam-run >/dev/null 2>&1; then
|
||||
SDK_DIR="${ANDROID_SDK_ROOT:-${ANDROID_HOME:-}}"
|
||||
if [ -z "$SDK_DIR" ] && [ -f local.properties ]; then
|
||||
SDK_DIR="$(sed -n 's/^sdk\.dir=//p' local.properties | head -n 1)"
|
||||
fi
|
||||
if [ -z "$SDK_DIR" ] && [ -d "$HOME/Android/Sdk" ]; then
|
||||
SDK_DIR="$HOME/Android/Sdk"
|
||||
fi
|
||||
if [ -z "$SDK_DIR" ] || [ ! -x "$SDK_DIR/platform-tools/adb" ]; then
|
||||
echo "adb introuvable : définissez ANDROID_HOME ou sdk.dir dans local.properties." >&2
|
||||
exit 1
|
||||
fi
|
||||
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH:-}:$HOME/.nix-profile/lib:/run/opengl-driver/lib"
|
||||
steam-run "$SDK_DIR/platform-tools/adb" "${ADB_FLAGS[@]}" install -r "$APK"
|
||||
else
|
||||
echo "adb ne fonctionne pas sur cet OS et steam-run est absent (NixOS)." >&2
|
||||
exit 1
|
||||
fi
|
||||
'''
|
||||
|
||||
|
||||
@@ -84,6 +84,11 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// m19 : export du schéma Room (`app/schemas/`) pour détecter les dérives en CI.
|
||||
ksp {
|
||||
arg("room.schemaLocation", "$projectDir/schemas")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||
|
||||
@@ -0,0 +1,730 @@
|
||||
{
|
||||
"formatVersion": 1,
|
||||
"database": {
|
||||
"version": 16,
|
||||
"identityHash": "ec10fdb23d5da3a76a73222e9c404561",
|
||||
"entities": [
|
||||
{
|
||||
"tableName": "folders",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `exists` INTEGER, `parent_resource_id` TEXT, `owner_id` TEXT, `sync_status` TEXT NOT NULL, `created_in_app` INTEGER NOT NULL DEFAULT 0, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceId",
|
||||
"columnName": "resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "exists",
|
||||
"columnName": "exists",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "parentResourceId",
|
||||
"columnName": "parent_resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "ownerId",
|
||||
"columnName": "owner_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "syncStatus",
|
||||
"columnName": "sync_status",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdInApp",
|
||||
"columnName": "created_in_app",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true,
|
||||
"defaultValue": "0"
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "added_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updated_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_folders_resource_id",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_folders_uri",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"uri"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_folders_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||
},
|
||||
{
|
||||
"name": "index_folders_parent_resource_id",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"parent_resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "user_preferences",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `value` TEXT NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`key`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "key",
|
||||
"columnName": "key",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "value",
|
||||
"columnName": "value",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updated_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"key"
|
||||
]
|
||||
},
|
||||
"indices": [],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "files",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `uri` TEXT, `name` TEXT NOT NULL, `folder_resource_id` TEXT NOT NULL, `extension` TEXT, `size` INTEGER NOT NULL, `mime_type` TEXT, `exists` INTEGER, `last_modified` INTEGER, `owner_id` TEXT, `category` TEXT, `sync_status` TEXT NOT NULL, `content` TEXT, `processed` INTEGER NOT NULL, `ocr_text` TEXT, `ocr_attempts` INTEGER NOT NULL, `ocr_queued_at` INTEGER, `added_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceId",
|
||||
"columnName": "resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "uri",
|
||||
"columnName": "uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "name",
|
||||
"columnName": "name",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "folderResourceId",
|
||||
"columnName": "folder_resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "extension",
|
||||
"columnName": "extension",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "size",
|
||||
"columnName": "size",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "mimeType",
|
||||
"columnName": "mime_type",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "exists",
|
||||
"columnName": "exists",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "lastModified",
|
||||
"columnName": "last_modified",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "ownerId",
|
||||
"columnName": "owner_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "category",
|
||||
"columnName": "category",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "syncStatus",
|
||||
"columnName": "sync_status",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "content",
|
||||
"columnName": "content",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "processed",
|
||||
"columnName": "processed",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "ocrText",
|
||||
"columnName": "ocr_text",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "ocrAttempts",
|
||||
"columnName": "ocr_attempts",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "ocrQueuedAt",
|
||||
"columnName": "ocr_queued_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "addedAt",
|
||||
"columnName": "added_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updated_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_files_resource_id",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_files_uri",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"uri"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_files_uri` ON `${TABLE_NAME}` (`uri`)"
|
||||
},
|
||||
{
|
||||
"name": "index_files_folder_resource_id",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"folder_resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_folder_resource_id` ON `${TABLE_NAME}` (`folder_resource_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_files_category",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"category"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_category` ON `${TABLE_NAME}` (`category`)"
|
||||
},
|
||||
{
|
||||
"name": "index_files_exists_processed_sync_status",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"exists",
|
||||
"processed",
|
||||
"sync_status"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_files_exists_processed_sync_status` ON `${TABLE_NAME}` (`exists`, `processed`, `sync_status`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "pending_operations",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_id` TEXT, `operation_id` TEXT NOT NULL, `ref_type` TEXT, `ref_id` INTEGER, `resource_id` TEXT, `resource_type` TEXT, `operation` TEXT NOT NULL, `payload` TEXT NOT NULL, `parent_resource_id` TEXT, `status` TEXT NOT NULL, `attempts` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "deviceId",
|
||||
"columnName": "device_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "operationId",
|
||||
"columnName": "operation_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "refType",
|
||||
"columnName": "ref_type",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "refId",
|
||||
"columnName": "ref_id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceId",
|
||||
"columnName": "resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceType",
|
||||
"columnName": "resource_type",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "operation",
|
||||
"columnName": "operation",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "payload",
|
||||
"columnName": "payload",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "parentResourceId",
|
||||
"columnName": "parent_resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "status",
|
||||
"columnName": "status",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "attempts",
|
||||
"columnName": "attempts",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdAt",
|
||||
"columnName": "created_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updated_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_pending_operations_device_id_operation_id",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"device_id",
|
||||
"operation_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_pending_operations_device_id_operation_id` ON `${TABLE_NAME}` (`device_id`, `operation_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_pending_operations_status",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"status"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_status` ON `${TABLE_NAME}` (`status`)"
|
||||
},
|
||||
{
|
||||
"name": "index_pending_operations_resource_id",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_pending_operations_resource_id_operation_status",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"resource_id",
|
||||
"operation",
|
||||
"status"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_resource_id_operation_status` ON `${TABLE_NAME}` (`resource_id`, `operation`, `status`)"
|
||||
},
|
||||
{
|
||||
"name": "index_pending_operations_parent_resource_id",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"parent_resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_pending_operations_parent_resource_id` ON `${TABLE_NAME}` (`parent_resource_id`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "scan_sessions",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `root_folder_id` TEXT, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceId",
|
||||
"columnName": "resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "rootFolderId",
|
||||
"columnName": "root_folder_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "status",
|
||||
"columnName": "status",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdAt",
|
||||
"columnName": "created_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updated_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_scan_sessions_resource_id",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_sessions_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
},
|
||||
{
|
||||
"tableName": "scan_pages",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `session_id` INTEGER NOT NULL, `temp_uri` TEXT NOT NULL, `corners_json` TEXT NOT NULL, `width` INTEGER NOT NULL, `height` INTEGER NOT NULL, `sort_order` INTEGER NOT NULL, `status` TEXT NOT NULL, `created_at` INTEGER NOT NULL, FOREIGN KEY(`session_id`) REFERENCES `scan_sessions`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "id",
|
||||
"columnName": "id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceId",
|
||||
"columnName": "resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "sessionId",
|
||||
"columnName": "session_id",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "tempUri",
|
||||
"columnName": "temp_uri",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "cornersJson",
|
||||
"columnName": "corners_json",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "width",
|
||||
"columnName": "width",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "height",
|
||||
"columnName": "height",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "sortOrder",
|
||||
"columnName": "sort_order",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "status",
|
||||
"columnName": "status",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "createdAt",
|
||||
"columnName": "created_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": true,
|
||||
"columnNames": [
|
||||
"id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_scan_pages_resource_id",
|
||||
"unique": true,
|
||||
"columnNames": [
|
||||
"resource_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_scan_pages_resource_id` ON `${TABLE_NAME}` (`resource_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_scan_pages_session_id",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"session_id"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_session_id` ON `${TABLE_NAME}` (`session_id`)"
|
||||
},
|
||||
{
|
||||
"name": "index_scan_pages_sort_order",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"sort_order"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_scan_pages_sort_order` ON `${TABLE_NAME}` (`sort_order`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": [
|
||||
{
|
||||
"table": "scan_sessions",
|
||||
"onDelete": "CASCADE",
|
||||
"onUpdate": "NO ACTION",
|
||||
"columns": [
|
||||
"session_id"
|
||||
],
|
||||
"referencedColumns": [
|
||||
"id"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tableName": "resource_permissions",
|
||||
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`resource_id` TEXT NOT NULL, `resource_type` TEXT NOT NULL, `effective_access` TEXT NOT NULL, `owner_id` TEXT, `shared_by_id` TEXT, `expires_at` INTEGER, `cached_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`resource_id`))",
|
||||
"fields": [
|
||||
{
|
||||
"fieldPath": "resourceId",
|
||||
"columnName": "resource_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "resourceType",
|
||||
"columnName": "resource_type",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "effectiveAccess",
|
||||
"columnName": "effective_access",
|
||||
"affinity": "TEXT",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "ownerId",
|
||||
"columnName": "owner_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "sharedById",
|
||||
"columnName": "shared_by_id",
|
||||
"affinity": "TEXT",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "expiresAt",
|
||||
"columnName": "expires_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": false
|
||||
},
|
||||
{
|
||||
"fieldPath": "cachedAt",
|
||||
"columnName": "cached_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
},
|
||||
{
|
||||
"fieldPath": "updatedAt",
|
||||
"columnName": "updated_at",
|
||||
"affinity": "INTEGER",
|
||||
"notNull": true
|
||||
}
|
||||
],
|
||||
"primaryKey": {
|
||||
"autoGenerate": false,
|
||||
"columnNames": [
|
||||
"resource_id"
|
||||
]
|
||||
},
|
||||
"indices": [
|
||||
{
|
||||
"name": "index_resource_permissions_expires_at",
|
||||
"unique": false,
|
||||
"columnNames": [
|
||||
"expires_at"
|
||||
],
|
||||
"orders": [],
|
||||
"createSql": "CREATE INDEX IF NOT EXISTS `index_resource_permissions_expires_at` ON `${TABLE_NAME}` (`expires_at`)"
|
||||
}
|
||||
],
|
||||
"foreignKeys": []
|
||||
}
|
||||
],
|
||||
"views": [],
|
||||
"setupQueries": [
|
||||
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'ec10fdb23d5da3a76a73222e9c404561')"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,13 @@ import androidx.room.RoomDatabase
|
||||
import com.kazier.mobile.data.local.dao.FileDao
|
||||
import com.kazier.mobile.data.local.dao.FolderDao
|
||||
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||
import com.kazier.mobile.data.local.dao.ResourcePermissionDao
|
||||
import com.kazier.mobile.data.local.dao.ScanDao
|
||||
import com.kazier.mobile.data.local.dao.UserPreferenceDao
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||
import com.kazier.mobile.data.local.entity.ResourcePermissionEntity
|
||||
import com.kazier.mobile.data.local.entity.ScanPageEntity
|
||||
import com.kazier.mobile.data.local.entity.ScanSessionEntity
|
||||
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
||||
@@ -27,14 +29,20 @@ import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
||||
* operation_id) (contrat outbox docs/api-v1.md §6.1).
|
||||
* v13: index composites files(exists, processed, sync_status) et
|
||||
* pending_operations(resource_id, operation, status) (requêtes review/OCR/gates).
|
||||
* v14: parent_resource_id sur pending_operations (cascade P8).
|
||||
* v15: backfill exists NULL→1 sur folders/files (M13).
|
||||
* v16: table resource_permissions (cache snapshot, M27).
|
||||
*/
|
||||
@Database(
|
||||
entities = [
|
||||
FolderEntity::class, UserPreferenceEntity::class, FileEntity::class,
|
||||
PendingOperationEntity::class, ScanSessionEntity::class, ScanPageEntity::class,
|
||||
ResourcePermissionEntity::class,
|
||||
],
|
||||
version = 14,
|
||||
exportSchema = false,
|
||||
version = 16,
|
||||
// m19 : schéma exporté (`app/schemas/`) — toute dérive non migrée casse
|
||||
// la compilation au lieu de briqueter les utilisateurs au démarrage.
|
||||
exportSchema = true,
|
||||
)
|
||||
abstract class AppDatabase : RoomDatabase() {
|
||||
|
||||
@@ -43,4 +51,5 @@ abstract class AppDatabase : RoomDatabase() {
|
||||
abstract fun fileDao(): FileDao
|
||||
abstract fun pendingOperationDao(): PendingOperationDao
|
||||
abstract fun scanDao(): ScanDao
|
||||
abstract fun resourcePermissionDao(): ResourcePermissionDao
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.kazier.mobile.data.local
|
||||
|
||||
/**
|
||||
* Échappe les jokers `LIKE` (`%`, `_`) et l'échappement lui-même (`\`) dans
|
||||
* un fragment destiné à une requête `... LIKE ... ESCAPE '\'` (m5, m7).
|
||||
* Sans ça, un `%`/`_` saisi (recherche) ou présent (uris SAF encodées
|
||||
* `%3A…`) agit comme joker : match-all en recherche, sur-sélection au walk.
|
||||
*/
|
||||
internal fun String.escapeLike(): String =
|
||||
replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
@@ -15,6 +15,12 @@ interface FileDao {
|
||||
@Query("SELECT * FROM files ORDER BY name ASC")
|
||||
suspend fun getAll(): List<FileEntity>
|
||||
|
||||
/**
|
||||
* Lignes sous une racine SAF (m5) — voir `FolderDao.getUnderRoot`.
|
||||
*/
|
||||
@Query("SELECT * FROM files WHERE uri = :rootUri OR uri LIKE :escapedRoot || '/%' ESCAPE '\\'")
|
||||
suspend fun getUnderRoot(rootUri: String, escapedRoot: String): List<FileEntity>
|
||||
|
||||
/**
|
||||
* Repasse C4 : lignes déjà journalisées (`exists = 0`) dont les octets
|
||||
* sont peut-être encore sur le disque (journal-first, crash ou refus SAF
|
||||
@@ -39,10 +45,17 @@ interface FileDao {
|
||||
@Query("SELECT * FROM files WHERE uri = :uri LIMIT 1")
|
||||
suspend fun getByUri(uri: String): FileEntity?
|
||||
|
||||
/**
|
||||
* Recherche par nom (m7) : `:query` arrive déjà échappé (`escapeLike`,
|
||||
* `%`/`_` littéraux, pas des jokers) avec `ESCAPE '\'`. `COLLATE NOCASE`
|
||||
* sur l'opérande gauche pour une casse ASCII insensible explicite
|
||||
* (le repli Unicode « ete » → « ÉTÉ » demanderait une colonne normalisée,
|
||||
* hors scope — voir FEEDBACK).
|
||||
*/
|
||||
@Query("""
|
||||
SELECT * FROM files
|
||||
WHERE "exists" = 1
|
||||
AND (:query IS NULL OR name LIKE '%' || :query || '%')
|
||||
AND (:query IS NULL OR name COLLATE NOCASE LIKE '%' || :query || '%' ESCAPE '\')
|
||||
AND (:category IS NULL OR category = :category)
|
||||
ORDER BY name ASC
|
||||
""")
|
||||
|
||||
@@ -18,6 +18,14 @@ interface FolderDao {
|
||||
@Query("SELECT * FROM folders ORDER BY name ASC")
|
||||
suspend fun getAll(): List<FolderEntity>
|
||||
|
||||
/**
|
||||
* Lignes sous une racine SAF (m5) : le walk et sa réconciliation ne
|
||||
* scannent plus toute la table par racine. `:escapedRoot` est la racine
|
||||
* avec `%`, `_`, `\` échappés côté appelant (`ESCAPE '\'`).
|
||||
*/
|
||||
@Query("SELECT * FROM folders WHERE uri = :rootUri OR uri LIKE :escapedRoot || '/%' ESCAPE '\\'")
|
||||
suspend fun getUnderRoot(rootUri: String, escapedRoot: String): List<FolderEntity>
|
||||
|
||||
/**
|
||||
* Repasse C4 (dossiers) : voir `FileDao.getMissingWithUri`. Un dossier
|
||||
* n'est re-supprimé physiquement que si toute sa descendance Room est
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.kazier.mobile.data.local.dao
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Query
|
||||
import androidx.room.Upsert
|
||||
import com.kazier.mobile.data.local.entity.ResourcePermissionEntity
|
||||
|
||||
@Dao
|
||||
interface ResourcePermissionDao {
|
||||
|
||||
@Upsert
|
||||
suspend fun upsertAll(perms: List<ResourcePermissionEntity>)
|
||||
|
||||
@Query("SELECT * FROM resource_permissions WHERE resource_id = :resourceId LIMIT 1")
|
||||
suspend fun getByResourceId(resourceId: String): ResourcePermissionEntity?
|
||||
|
||||
/** Grants périmés à masquer localement (`expires_at` passé). */
|
||||
@Query("SELECT * FROM resource_permissions WHERE expires_at IS NOT NULL AND expires_at <= :now")
|
||||
suspend fun getExpired(now: Long): List<ResourcePermissionEntity>
|
||||
|
||||
/**
|
||||
* Convergence du pull complet : oublie les grants absents du snapshot
|
||||
* (révocation/expiration côté serveur).
|
||||
*/
|
||||
@Query("DELETE FROM resource_permissions WHERE resource_id NOT IN (:snapshotIds)")
|
||||
suspend fun deleteNotIn(snapshotIds: List<String>)
|
||||
|
||||
@Query("DELETE FROM resource_permissions")
|
||||
suspend fun clear()
|
||||
}
|
||||
@@ -42,8 +42,9 @@ data class FileEntity(
|
||||
val size: Long,
|
||||
@ColumnInfo(name = "mime_type")
|
||||
val mimeType: String? = null,
|
||||
// M13 : voir `FolderEntity.exists` — défaut 1, backfill en migration 14→15.
|
||||
@ColumnInfo(name = "exists")
|
||||
val exists: Int? = null,
|
||||
val exists: Int? = 1,
|
||||
@ColumnInfo(name = "last_modified")
|
||||
val lastModified: Long? = null,
|
||||
@ColumnInfo(name = "owner_id")
|
||||
|
||||
@@ -32,8 +32,11 @@ data class FolderEntity(
|
||||
val uri: String? = null,
|
||||
@ColumnInfo(name = "name")
|
||||
val name: String,
|
||||
// M13 : défaut 1 — une ligne sans `exists` explicite restait invisible
|
||||
// des requêtes `WHERE exists = 1`. La colonne reste nullable côté schéma
|
||||
// (pas de rewrite), le backfill NULL→1 est fait en migration 14→15.
|
||||
@ColumnInfo(name = "exists")
|
||||
val exists: Int? = null,
|
||||
val exists: Int? = 1,
|
||||
@ColumnInfo(name = "parent_resource_id")
|
||||
val parentResourceId: String? = null,
|
||||
@ColumnInfo(name = "owner_id")
|
||||
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.kazier.mobile.data.local.entity
|
||||
|
||||
import androidx.room.ColumnInfo
|
||||
import androidx.room.Entity
|
||||
import androidx.room.Index
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Cache local du snapshot `GET /sync/permissions` (M27, docs/api-v1.md §6.2).
|
||||
*
|
||||
* Une ligne = la permission effective connue pour une ressource NON possédée
|
||||
* (les ressources `owner` ne sont pas stockées : l'ownership se résout depuis
|
||||
* les lignes `files`/`folders`). Fondement de [canAccess][com.kazier.mobile.data.repository.ShareRepository.canAccess]
|
||||
* sans réseau : rang effectif, expiration du grant et fraîcheur du snapshot
|
||||
* (TTL 24h → downgrade lecture seule).
|
||||
*/
|
||||
@Entity(
|
||||
tableName = "resource_permissions",
|
||||
indices = [
|
||||
Index(value = ["expires_at"]),
|
||||
],
|
||||
)
|
||||
data class ResourcePermissionEntity(
|
||||
@PrimaryKey
|
||||
@ColumnInfo(name = "resource_id")
|
||||
val resourceId: String,
|
||||
@ColumnInfo(name = "resource_type")
|
||||
val resourceType: String,
|
||||
@ColumnInfo(name = "effective_access")
|
||||
val effectiveAccess: String,
|
||||
@ColumnInfo(name = "owner_id")
|
||||
val ownerId: String? = null,
|
||||
@ColumnInfo(name = "shared_by_id")
|
||||
val sharedById: String? = null,
|
||||
/** Fin du grant, ms epoch ; null = jamais. */
|
||||
@ColumnInfo(name = "expires_at")
|
||||
val expiresAt: Long? = null,
|
||||
/** Horodatage du snapshot serveur, ms epoch (TTL 24h). */
|
||||
@ColumnInfo(name = "cached_at")
|
||||
val cachedAt: Long,
|
||||
@ColumnInfo(name = "updated_at")
|
||||
val updatedAt: Long,
|
||||
)
|
||||
|
||||
/** Rangs d'accès effectif — `viewer < commenter < editor < owner`. */
|
||||
object AccessRank {
|
||||
const val VIEWER = "viewer"
|
||||
const val COMMENTER = "commenter"
|
||||
const val EDITOR = "editor"
|
||||
const val OWNER = "owner"
|
||||
|
||||
fun rank(access: String?): Int = when (access) {
|
||||
OWNER -> 4
|
||||
EDITOR -> 3
|
||||
COMMENTER -> 2
|
||||
VIEWER -> 1
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
+46
-1
@@ -33,6 +33,9 @@ import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
* v13 : index composites `files(exists, processed, sync_status)` (review +
|
||||
* candidats OCR auto) et `pending_operations(resource_id, operation, status)`
|
||||
* (gates outbox create/move) — requêtes à chaud sans full-table scan.
|
||||
* v14 : colonne `parent_resource_id` sur `pending_operations` (cascade P8).
|
||||
* v15 : backfill `exists` NULL→1 sur `folders`/`files` (M13) + défaut Kotlin 1.
|
||||
* v16 : table `resource_permissions` (cache snapshot, M27) + index `expires_at`.
|
||||
*/
|
||||
object Migrations {
|
||||
|
||||
@@ -246,7 +249,49 @@ object Migrations {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* M13 : backfill `exists` NULL→1 sur `folders` et `files`. Les lignes
|
||||
* insérées sans `exists` explicite (défaut Kotlin `null` avant ce fix)
|
||||
* étaient invisibles des requêtes `WHERE exists = 1` — elles
|
||||
* réapparaissent comme présentes, état le plus sûr (le walk les
|
||||
* re-marque `exists = 0` si elles ont vraiment disparu).
|
||||
*/
|
||||
private val MIGRATION_14_15 = object : Migration(14, 15) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("UPDATE `folders` SET `exists` = 1 WHERE `exists` IS NULL")
|
||||
db.execSQL("UPDATE `files` SET `exists` = 1 WHERE `exists` IS NULL")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* M27 : cache du snapshot permissions — table `resource_permissions`
|
||||
* (rang effectif + expiration + fraîcheur, fondement de `canAccess`).
|
||||
*/
|
||||
private val MIGRATION_15_16 = object : Migration(15, 16) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS `resource_permissions` (
|
||||
`resource_id` TEXT NOT NULL,
|
||||
`resource_type` TEXT NOT NULL,
|
||||
`effective_access` TEXT NOT NULL,
|
||||
`owner_id` TEXT,
|
||||
`shared_by_id` TEXT,
|
||||
`expires_at` INTEGER,
|
||||
`cached_at` INTEGER NOT NULL,
|
||||
`updated_at` INTEGER NOT NULL,
|
||||
PRIMARY KEY(`resource_id`)
|
||||
)
|
||||
""".trimIndent(),
|
||||
)
|
||||
db.execSQL(
|
||||
"CREATE INDEX IF NOT EXISTS `index_resource_permissions_expires_at` " +
|
||||
"ON `resource_permissions` (`expires_at`)",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val ALL: Array<Migration> = arrayOf(
|
||||
MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14,
|
||||
MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16,
|
||||
)
|
||||
}
|
||||
@@ -140,15 +140,19 @@ data class SyncFailedDto(
|
||||
@Json(name = "message") val message: String,
|
||||
)
|
||||
|
||||
/** Snapshot `GET /sync/permissions` (docs/api-v1.md §6.2). */
|
||||
/**
|
||||
* Snapshot `GET /sync/permissions` (docs/api-v1.md §6.2, miroir de
|
||||
* `ResourcePermission` Go : `sharedById *string`, `expiresAt *int64` ms epoch).
|
||||
* M27 : typés (fini les `Any?` jamais lus) — lus par le cache et `canAccess`.
|
||||
*/
|
||||
data class ResourcePermissionDto(
|
||||
@Json(name = "resource_id") val resourceId: String,
|
||||
@Json(name = "resourceType") val resourceType: String,
|
||||
@Json(name = "effectiveAccess") val effectiveAccess: String,
|
||||
@Json(name = "inherit") val inherit: Boolean,
|
||||
@Json(name = "ownerId") val ownerId: String? = null,
|
||||
@Json(name = "sharedById") val sharedById: Any? = null,
|
||||
@Json(name = "expiresAt") val expiresAt: Any? = null,
|
||||
@Json(name = "sharedById") val sharedById: String? = null,
|
||||
@Json(name = "expiresAt") val expiresAt: Long? = null,
|
||||
@Json(name = "cachedAt") val cachedAt: Long,
|
||||
@Json(name = "updatedAt") val updatedAt: Long,
|
||||
@Json(name = "name") val name: String = "",
|
||||
|
||||
+10
-2
@@ -2,6 +2,7 @@ package com.kazier.mobile.data.repository
|
||||
|
||||
import androidx.room.withTransaction
|
||||
import com.kazier.mobile.data.local.AppDatabase
|
||||
import com.kazier.mobile.data.local.escapeLike
|
||||
import com.kazier.mobile.data.local.dao.FileDao
|
||||
import com.kazier.mobile.data.local.dao.FolderDao
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
@@ -46,10 +47,13 @@ class FileRepository @Inject constructor(
|
||||
/** Fichiers visibles de toute l'arborescence — écran d'accueil (grille par date). */
|
||||
fun observeAllVisible(): Flow<List<FileEntity>> = fileDao.observeAllVisible()
|
||||
|
||||
/** Recherche/filtrage par nom et catégorie (utilisé par SearchViewModel). */
|
||||
/**
|
||||
* Recherche/filtrage par nom et catégorie (utilisé par SearchViewModel).
|
||||
* m7 : la saisie est échappée (`%`/`_` littéraux, pas des jokers).
|
||||
*/
|
||||
fun searchFiles(query: String?, category: String?): Flow<List<FileEntity>> =
|
||||
fileDao.searchWithFilters(
|
||||
query = query?.trim()?.takeIf { it.isNotEmpty() },
|
||||
query = query?.trim()?.takeIf { it.isNotEmpty() }?.escapeLike(),
|
||||
category = category,
|
||||
)
|
||||
|
||||
@@ -171,6 +175,10 @@ class FileRepository @Inject constructor(
|
||||
|
||||
suspend fun getAll(): List<FileEntity> = fileDao.getAll()
|
||||
|
||||
/** Lignes sous une racine SAF (m5) — voir `FolderRepository.getUnderRoot`. */
|
||||
suspend fun getUnderRoot(rootUri: String): List<FileEntity> =
|
||||
fileDao.getUnderRoot(rootUri, rootUri.escapeLike())
|
||||
|
||||
/**
|
||||
* Upsert local d'un fichier SAF — miroir de `saveFile()` JS : déduplication
|
||||
* par `resource_id` ou `uri`, conservation de l'identité/sync_status/owner.
|
||||
|
||||
+13
-2
@@ -2,6 +2,7 @@ package com.kazier.mobile.data.repository
|
||||
|
||||
import androidx.room.withTransaction
|
||||
import com.kazier.mobile.data.local.AppDatabase
|
||||
import com.kazier.mobile.data.local.escapeLike
|
||||
import com.kazier.mobile.data.local.dao.FolderDao
|
||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||
import com.kazier.mobile.data.local.entity.FolderStatus
|
||||
@@ -44,6 +45,13 @@ class FolderRepository @Inject constructor(
|
||||
|
||||
suspend fun getAll(): List<FolderEntity> = folderDao.getAll()
|
||||
|
||||
/**
|
||||
* Lignes sous une racine SAF (m5) : la racine est échappée pour le `LIKE`
|
||||
* (les uris SAF contiennent des `%` d'encodage et parfois des `_`).
|
||||
*/
|
||||
suspend fun getUnderRoot(rootUri: String): List<FolderEntity> =
|
||||
folderDao.getUnderRoot(rootUri, rootUri.escapeLike())
|
||||
|
||||
/** Snapshot des sous-dossiers visibles d'un dossier (opérations batch hors UI). */
|
||||
suspend fun getChildren(parentResourceId: String): List<FolderEntity> =
|
||||
folderDao.getByParentOnce(parentResourceId)
|
||||
@@ -83,7 +91,8 @@ class FolderRepository @Inject constructor(
|
||||
resourceId = dto.id,
|
||||
uri = existing?.uri,
|
||||
name = dto.name,
|
||||
exists = existing?.exists,
|
||||
// M13 : une ligne serveur nouvelle n'a pas d'`exists` local — 1 par défaut.
|
||||
exists = existing?.exists ?: 1,
|
||||
parentResourceId = dto.parentId,
|
||||
ownerId = existing?.ownerId,
|
||||
// Le snapshot serveur confirme la présence cloud : si une copie
|
||||
@@ -144,7 +153,9 @@ class FolderRepository @Inject constructor(
|
||||
resourceId = existing?.resourceId ?: input.resourceId ?: generateId.newResourceId(),
|
||||
uri = input.uri,
|
||||
name = input.name,
|
||||
exists = input.exists?.let { if (it) 1 else 0 },
|
||||
// M13 : `null` (défaut de `SaveFolderInput`) = présent, jamais NULL
|
||||
// en base — sinon la ligne disparaît des requêtes `exists = 1`.
|
||||
exists = if (input.exists != false) 1 else 0,
|
||||
parentResourceId = effectiveParent,
|
||||
// `owner_id` Room = user_id du compte actif, jamais l'identité device.
|
||||
ownerId = ownerId ?: existing?.ownerId ?: activeUserStore.get(),
|
||||
|
||||
@@ -62,12 +62,27 @@ class OcrRepository @Inject constructor(
|
||||
/**
|
||||
* Poll toutes les 3 s (docs §5) jusqu'à l'état terminal. [onProgress] est
|
||||
* appelé à chaque réponse du serveur (état courant exposé à l'UI).
|
||||
*
|
||||
* m20 : borné (deadline + nombre max de polls) — un job resté `processing`
|
||||
* (stale claim serveur) levait sinon une coroutine tenue indéfiniment.
|
||||
* Le timeout remonte en `ApiException("OCR_TIMEOUT")`, géré comme échec
|
||||
* par les appelants (`processAuto` → `Failed`, viewer → message d'erreur).
|
||||
*/
|
||||
suspend fun poll(jobId: String, onProgress: (OcrJobDto) -> Unit = {}): OcrJobDto {
|
||||
suspend fun poll(
|
||||
jobId: String,
|
||||
timeoutMs: Long = POLL_TIMEOUT_MS,
|
||||
onProgress: (OcrJobDto) -> Unit = {},
|
||||
): OcrJobDto {
|
||||
val deadline = System.currentTimeMillis() + timeoutMs
|
||||
var polls = 0
|
||||
while (true) {
|
||||
val job = apiClient.getOcrJob(jobId)
|
||||
onProgress(job)
|
||||
if (job.status in OcrJobStatus.TERMINAL) return job
|
||||
polls++
|
||||
if (polls >= POLL_MAX_ATTEMPTS || System.currentTimeMillis() >= deadline) {
|
||||
throw ApiException("OCR_TIMEOUT", "OCR sans réponse (job $jobId)", 0)
|
||||
}
|
||||
delay(POLL_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
@@ -144,6 +159,9 @@ class OcrRepository @Inject constructor(
|
||||
|
||||
companion object {
|
||||
const val POLL_INTERVAL_MS = 3_000L
|
||||
/** Timeout du poll (m20) : 10 min ≈ 200 polls × 3 s. */
|
||||
const val POLL_TIMEOUT_MS = 10 * 60 * 1_000L
|
||||
const val POLL_MAX_ATTEMPTS = 200
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -146,6 +146,79 @@ class OutboxRepository @Inject constructor(
|
||||
payload = mapOf("granteeUserId" to granteeUserId),
|
||||
)
|
||||
|
||||
/**
|
||||
* Raccourci `update_metadata` — payload `{ name }` (rename d'une ressource
|
||||
* partagée, `editor+`, docs/api-v1.md §6.1). m21 : rend le rename partagé
|
||||
* émissible — l'op n'avait aucun écrivain côté client.
|
||||
*/
|
||||
suspend fun enqueueUpdateMetadata(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
name: String,
|
||||
): String = enqueue(
|
||||
operation = PendingOperationType.UPDATE_METADATA,
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
payload = mapOf("name" to name),
|
||||
)
|
||||
|
||||
/**
|
||||
* Raccourci `update_share` — même payload que `share` (m21 : update d'un
|
||||
* partage existant inopérant sans écrivain).
|
||||
*/
|
||||
suspend fun enqueueUpdateShare(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
granteeUserId: String,
|
||||
access: String,
|
||||
inherit: Boolean = true,
|
||||
expiresAt: Long? = null,
|
||||
): String = enqueue(
|
||||
operation = PendingOperationType.UPDATE_SHARE,
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
payload = buildMap {
|
||||
put("granteeUserId", granteeUserId)
|
||||
put("access", access)
|
||||
put("inherit", inherit)
|
||||
expiresAt?.let { put("expiresAt", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Raccourci `create_link` — payload `{ token, access, expiresAt? }`
|
||||
* (m21 : liens publics inopérants sans écrivain). Le `token` 32-hex est
|
||||
* généré côté client (`GenerateId`) : c'est l'identifiant du lien.
|
||||
*/
|
||||
suspend fun enqueueCreateLink(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
token: String,
|
||||
access: String,
|
||||
expiresAt: Long? = null,
|
||||
): String = enqueue(
|
||||
operation = PendingOperationType.CREATE_LINK,
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
payload = buildMap {
|
||||
put("token", token)
|
||||
put("access", access)
|
||||
expiresAt?.let { put("expiresAt", it) }
|
||||
},
|
||||
)
|
||||
|
||||
/** Raccourci `revoke_link` — payload `{ token }` (m21). */
|
||||
suspend fun enqueueRevokeLink(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
token: String,
|
||||
): String = enqueue(
|
||||
operation = PendingOperationType.REVOKE_LINK,
|
||||
resourceId = resourceId,
|
||||
resourceType = resourceType,
|
||||
payload = mapOf("token" to token),
|
||||
)
|
||||
|
||||
/** Nombre d'ops en attente de push (stats UI optionnelles). */
|
||||
suspend fun countPending(): Int = pendingOperationDao.countPending()
|
||||
|
||||
|
||||
+158
-29
@@ -4,11 +4,15 @@ import androidx.room.withTransaction
|
||||
import com.kazier.mobile.data.local.AppDatabase
|
||||
import com.kazier.mobile.data.local.dao.FileDao
|
||||
import com.kazier.mobile.data.local.dao.FolderDao
|
||||
import com.kazier.mobile.data.local.entity.AccessRank
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.data.local.entity.FolderEntity
|
||||
import com.kazier.mobile.data.local.entity.ResourcePermissionEntity
|
||||
import com.kazier.mobile.data.local.entity.UserPreferenceEntity
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.domain.ActiveUserStore
|
||||
import com.kazier.mobile.domain.PrefKeys
|
||||
import com.kazier.mobile.domain.SyncPlacement
|
||||
import timber.log.Timber
|
||||
import javax.inject.Inject
|
||||
@@ -21,8 +25,17 @@ import javax.inject.Singleton
|
||||
* de l'utilisateur. Les ressources non possédées (viewer/commenter/editor)
|
||||
* sont importées en tant que lignes cloud-only (`uri = NULL`, `sync_status = "cloud"`).
|
||||
*
|
||||
* Un pull complet (`after=0`) est effectué au login et à la restauration de
|
||||
* session pour garantir la convergence (révocations = disparition du snapshot).
|
||||
* M27 — delta, expiration et `canAccess` :
|
||||
* - le `cachedAt` du dernier pull est persisté (`user_preferences`) : pull
|
||||
* complet (`after = null`) au premier appel, au login/restauration
|
||||
* (`forceFull = true`) et quand le cache dépasse le TTL 24h ; delta
|
||||
* (`after = cachedAt`) sinon — la convergence (lignes absentes = révoquées)
|
||||
* ne tourne que sur pull complet ;
|
||||
* - chaque grant non-owner est persisté en `resource_permissions` (rang,
|
||||
* expiration, fraîcheur) : un grant expiré (`expiresAt` passé) masque la
|
||||
* ligne locale au lieu de rester visible jusqu'au prochain login ;
|
||||
* - [canAccess] répond offline (ownership local, puis rang persisté, avec
|
||||
* downgrade lecture seule après TTL sans reseed).
|
||||
*/
|
||||
@Singleton
|
||||
class ShareRepository @Inject constructor(
|
||||
@@ -32,31 +45,60 @@ class ShareRepository @Inject constructor(
|
||||
) {
|
||||
|
||||
/**
|
||||
* Récupère le snapshot complet des permissions et hydrate Room.
|
||||
* Récupère le snapshot des permissions et hydrate Room + le cache.
|
||||
*
|
||||
* Pour chaque permission non-owner :
|
||||
* Pour chaque permission non-owner non expirée :
|
||||
* - Folders : upsert cloud-only (uri=null, name, parentId, ownerId)
|
||||
* - Files : upsert cloud-only (uri=null, name, folderResourceId, ownerId, processed=true)
|
||||
*
|
||||
* Convergence : les lignes cloud-only absentes du snapshot complet sont
|
||||
* marquées `exists = 0`.
|
||||
* Convergence (pull complet uniquement) : les lignes cloud-only absentes
|
||||
* du snapshot complet sont marquées `exists = 0`, et les grants du cache
|
||||
* absents sont oubliés.
|
||||
*/
|
||||
suspend fun syncSnapshot() {
|
||||
suspend fun syncSnapshot(forceFull: Boolean = false) {
|
||||
// `ownerId` serveur = user_id : comparer au compte actif, jamais au device.
|
||||
val currentUserId = activeUserStore.get()
|
||||
val permissions = apiClient.syncPermissions()
|
||||
|
||||
val prefs = appDatabase.userPreferenceDao()
|
||||
val permDao = appDatabase.resourcePermissionDao()
|
||||
val now = System.currentTimeMillis()
|
||||
val cachedAt = prefs.getValue(PrefKeys.PERMISSIONS_CACHED_AT)?.toLongOrNull()
|
||||
val full = forceFull || cachedAt == null || now - cachedAt > PERMISSION_TTL_MS
|
||||
val permissions = apiClient.syncPermissions(if (full) null else cachedAt)
|
||||
|
||||
val folderDao = appDatabase.folderDao()
|
||||
val fileDao = appDatabase.fileDao()
|
||||
|
||||
val snapshotFolderIds = mutableSetOf<String>()
|
||||
val snapshotFileIds = mutableSetOf<String>()
|
||||
val snapshotPermIds = mutableSetOf<String>()
|
||||
|
||||
appDatabase.withTransaction {
|
||||
for (perm in permissions) {
|
||||
if (perm.effectiveAccess == "owner") continue
|
||||
snapshotPermIds += perm.resourceId
|
||||
permDao.upsertAll(
|
||||
listOf(
|
||||
ResourcePermissionEntity(
|
||||
resourceId = perm.resourceId,
|
||||
resourceType = perm.resourceType,
|
||||
effectiveAccess = perm.effectiveAccess,
|
||||
ownerId = perm.ownerId,
|
||||
sharedById = perm.sharedById,
|
||||
expiresAt = perm.expiresAt,
|
||||
// Fraîcheur = heure locale du pull (M27) : le TTL
|
||||
// mesure « 24h sans reseed », pas l'horloge serveur
|
||||
// (skew). `perm.cachedAt` sert au delta `after`.
|
||||
cachedAt = now,
|
||||
updatedAt = perm.updatedAt,
|
||||
),
|
||||
),
|
||||
)
|
||||
if (isExpired(perm.expiresAt, now)) {
|
||||
// Grant expiré : masquer la ligne locale au lieu d'hydrater.
|
||||
markSharedMissing(perm.resourceId, perm.resourceType, currentUserId, now, folderDao, fileDao)
|
||||
continue
|
||||
}
|
||||
when {
|
||||
perm.effectiveAccess == "owner" -> Unit
|
||||
perm.resourceType == "folder" -> {
|
||||
snapshotFolderIds += perm.resourceId
|
||||
upsertSharedFolder(perm, now, folderDao)
|
||||
@@ -68,36 +110,118 @@ class ShareRepository @Inject constructor(
|
||||
}
|
||||
}
|
||||
|
||||
// Convergence : marquer les lignes cloud-only d'autrui absentes du
|
||||
// snapshot comme disparues (révocation / expiration côté serveur).
|
||||
// Sans compte actif, impossible d'attribuer : ne rien masquer. Le
|
||||
// snapshot exclut les ressources possédées → une ligne cloud-only
|
||||
// au vrai ownerId=user ne doit jamais être markMissing.
|
||||
for (folder in folderDao.getAll()) {
|
||||
if (currentUserId != null &&
|
||||
isCloudOnlyForOtherUser(folder.uri, folder.ownerId, currentUserId, folder.exists) &&
|
||||
folder.resourceId !in snapshotFolderIds
|
||||
) {
|
||||
folderDao.markMissing(folder.resourceId, now)
|
||||
if (full) {
|
||||
// Convergence : marquer les lignes cloud-only d'autrui absentes du
|
||||
// snapshot comme disparues (révocation / expiration côté serveur).
|
||||
// Sans compte actif, impossible d'attribuer : ne rien masquer. Le
|
||||
// snapshot exclut les ressources possédées → une ligne cloud-only
|
||||
// au vrai ownerId=user ne doit jamais être markMissing.
|
||||
for (folder in folderDao.getAll()) {
|
||||
if (currentUserId != null &&
|
||||
isCloudOnlyForOtherUser(folder.uri, folder.ownerId, currentUserId, folder.exists) &&
|
||||
folder.resourceId !in snapshotFolderIds
|
||||
) {
|
||||
folderDao.markMissing(folder.resourceId, now)
|
||||
}
|
||||
}
|
||||
for (file in fileDao.getAll()) {
|
||||
if (currentUserId != null &&
|
||||
isCloudOnlyForOtherUser(file.uri, file.ownerId, currentUserId, file.exists) &&
|
||||
file.resourceId !in snapshotFileIds
|
||||
) {
|
||||
fileDao.markMissing(file.resourceId, now)
|
||||
}
|
||||
}
|
||||
// Oublie les grants du cache absents du snapshot complet.
|
||||
if (snapshotPermIds.isEmpty()) {
|
||||
permDao.clear()
|
||||
} else {
|
||||
permDao.deleteNotIn(snapshotPermIds.toList())
|
||||
}
|
||||
}
|
||||
for (file in fileDao.getAll()) {
|
||||
if (currentUserId != null &&
|
||||
isCloudOnlyForOtherUser(file.uri, file.ownerId, currentUserId, file.exists) &&
|
||||
file.resourceId !in snapshotFileIds
|
||||
) {
|
||||
fileDao.markMissing(file.resourceId, now)
|
||||
}
|
||||
|
||||
// Grants périmés connus du cache (delta ou TTL) : masquer localement.
|
||||
for (expired in permDao.getExpired(now)) {
|
||||
markSharedMissing(expired.resourceId, expired.resourceType, currentUserId, now, folderDao, fileDao)
|
||||
}
|
||||
|
||||
prefs.upsert(
|
||||
UserPreferenceEntity(
|
||||
PrefKeys.PERMISSIONS_CACHED_AT,
|
||||
now.toString(),
|
||||
now,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
Timber.d(
|
||||
"syncSnapshot: hydrated %d folders, %d files",
|
||||
"syncSnapshot: hydrated %d folders, %d files (full=%s)",
|
||||
snapshotFolderIds.size,
|
||||
snapshotFileIds.size,
|
||||
full,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Droit offline sur une ressource (docs/api-v1.md §6.2) : ownership local
|
||||
* d'abord (`owner` implique tout), sinon rang persisté du snapshot.
|
||||
* Grant expiré → refusé ; snapshot périmé (TTL 24h sans reseed) →
|
||||
* downgrade lecture seule (`viewer` exigé au plus).
|
||||
*/
|
||||
suspend fun canAccess(resourceId: String, required: String = AccessRank.VIEWER): Boolean {
|
||||
val requiredRank = AccessRank.rank(required)
|
||||
if (requiredRank <= 0) return false
|
||||
val currentUserId = activeUserStore.get()
|
||||
val now = System.currentTimeMillis()
|
||||
if (currentUserId != null) {
|
||||
val folderOwner = appDatabase.folderDao().getByResourceId(resourceId)?.ownerId
|
||||
val fileOwner = if (folderOwner == null) {
|
||||
appDatabase.fileDao().getByResourceId(resourceId)?.ownerId
|
||||
} else {
|
||||
null
|
||||
}
|
||||
if (folderOwner == currentUserId || fileOwner == currentUserId) return true
|
||||
}
|
||||
val perm = appDatabase.resourcePermissionDao().getByResourceId(resourceId) ?: return false
|
||||
if (isExpired(perm.expiresAt, now)) return false
|
||||
val effective = if (now - perm.cachedAt > PERMISSION_TTL_MS) {
|
||||
// Stale : downgrade lecture seule.
|
||||
minOf(AccessRank.rank(perm.effectiveAccess), AccessRank.rank(AccessRank.VIEWER))
|
||||
} else {
|
||||
AccessRank.rank(perm.effectiveAccess)
|
||||
}
|
||||
return effective >= requiredRank
|
||||
}
|
||||
|
||||
private fun isExpired(expiresAt: Long?, now: Long): Boolean =
|
||||
expiresAt != null && expiresAt <= now
|
||||
|
||||
/**
|
||||
* Masque une ligne partagée cloud-only d'autrui (`exists = 0`) — jamais
|
||||
* une copie physique locale ni une ressource possédée.
|
||||
*/
|
||||
private suspend fun markSharedMissing(
|
||||
resourceId: String,
|
||||
resourceType: String,
|
||||
currentUserId: String?,
|
||||
now: Long,
|
||||
folderDao: FolderDao,
|
||||
fileDao: FileDao,
|
||||
) {
|
||||
if (currentUserId == null) return
|
||||
if (resourceType == "folder") {
|
||||
val folder = folderDao.getByResourceId(resourceId) ?: return
|
||||
if (isCloudOnlyForOtherUser(folder.uri, folder.ownerId, currentUserId, folder.exists)) {
|
||||
folderDao.markMissing(resourceId, now)
|
||||
}
|
||||
} else {
|
||||
val file = fileDao.getByResourceId(resourceId) ?: return
|
||||
if (isCloudOnlyForOtherUser(file.uri, file.ownerId, currentUserId, file.exists)) {
|
||||
fileDao.markMissing(resourceId, now)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ligne hébergée cloud (uri NULL), non possédée localement, encore visible.
|
||||
* Absente du snapshot → ressource partagée révoquée/expirée → marquer disparue.
|
||||
@@ -164,4 +288,9 @@ class ShareRepository @Inject constructor(
|
||||
)
|
||||
fileDao.upsert(entity)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** TTL du snapshot permissions (docs/api-v1.md §6.2) : 24h. */
|
||||
const val PERMISSION_TTL_MS = 24 * 60 * 60 * 1000L
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import com.kazier.mobile.data.local.AppDatabase
|
||||
import com.kazier.mobile.data.local.dao.FileDao
|
||||
import com.kazier.mobile.data.local.dao.FolderDao
|
||||
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||
import com.kazier.mobile.data.local.dao.ResourcePermissionDao
|
||||
import com.kazier.mobile.data.local.dao.ScanDao
|
||||
import com.kazier.mobile.data.local.dao.UserPreferenceDao
|
||||
import com.kazier.mobile.data.local.migration.Migrations
|
||||
@@ -25,6 +26,13 @@ object DatabaseModule {
|
||||
fun provideDatabase(@ApplicationContext context: Context): AppDatabase =
|
||||
Room.databaseBuilder(context, AppDatabase::class.java, "dot.db")
|
||||
.addMigrations(*Migrations.ALL)
|
||||
// m15 : un APK plus ancien que la DB (downgrade) ne doit plus
|
||||
// crasher en `IllegalStateException` brut — reconstruction
|
||||
// destructive documentée : le miroir SAF se reconstruit au walk
|
||||
// suivant, les données serveur restent la source de vérité.
|
||||
// Perte acceptée : l'outbox non poussée (mutations locales) —
|
||||
// cas rare (rollback d'APK), préféré au crash au démarrage.
|
||||
.fallbackToDestructiveMigrationOnDowngrade()
|
||||
.build()
|
||||
|
||||
@Provides
|
||||
@@ -41,4 +49,7 @@ object DatabaseModule {
|
||||
|
||||
@Provides
|
||||
fun provideScanDao(db: AppDatabase): ScanDao = db.scanDao()
|
||||
|
||||
@Provides
|
||||
fun provideResourcePermissionDao(db: AppDatabase): ResourcePermissionDao = db.resourcePermissionDao()
|
||||
}
|
||||
@@ -8,4 +8,6 @@ object PrefKeys {
|
||||
const val SYNC_MODE = "sync_mode"
|
||||
const val THEME = "theme"
|
||||
const val SERVER_URL = "server_url"
|
||||
/** Dernier pull `GET /sync/permissions` réussi, ms epoch (M27 : delta + TTL 24h). */
|
||||
const val PERMISSIONS_CACHED_AT = "permissions_cached_at"
|
||||
}
|
||||
@@ -81,19 +81,26 @@ class FileDeleter @Inject constructor(
|
||||
}
|
||||
|
||||
/**
|
||||
* Suppression cloud uniquement (outbox `delete_resource`).
|
||||
* Le fichier local n\'est pas touché. N\'a de sens que si la ressource a
|
||||
* déjà été poussée (gate « processed » : un fichier jamais envoyé est no-op).
|
||||
* Suppression cloud uniquement (outbox `delete_resource` + tombstone locale).
|
||||
* Le fichier physique local n'est pas touché, mais la ligne Room passe
|
||||
* `exists = 0` dans la MÊME transaction (M5) : sans ça la ressource restait
|
||||
* affichée, le walk la revoyait et `refreshFromServer` ne supprime jamais
|
||||
* de lignes → fantôme local vs serveur supprimé. N'a de sens que si la
|
||||
* ressource a déjà été poussée (gate « processed »).
|
||||
*/
|
||||
private suspend fun deleteInCloud(file: FileEntity): Boolean {
|
||||
var ok = false
|
||||
runCatching {
|
||||
// Jamais poussé (create encore pending) : annulation (M19), pas
|
||||
// de delete — le serveur n'a rien à oublier. Poussé (synced) :
|
||||
// `delete_resource`, le serveur connaît la ressource.
|
||||
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||
if (outboxRepository.hasSyncedCreateOperation(file.resourceId)) {
|
||||
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
||||
val now = System.currentTimeMillis()
|
||||
appDatabase.withTransaction {
|
||||
// Jamais poussé (create encore pending) : annulation (M19), pas
|
||||
// de delete — le serveur n'a rien à oublier. Poussé (synced) :
|
||||
// `delete_resource`, le serveur connaît la ressource.
|
||||
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||
if (outboxRepository.hasSyncedCreateOperation(file.resourceId)) {
|
||||
outboxRepository.enqueueDeleteResource(file.resourceId, "file")
|
||||
}
|
||||
fileRepository.markMissing(file.resourceId, now)
|
||||
}
|
||||
ok = true
|
||||
Timber.d("enqueued cloud delete for %s", file.resourceId)
|
||||
|
||||
@@ -87,13 +87,19 @@ class FolderDeleter @Inject constructor(
|
||||
return false
|
||||
}
|
||||
|
||||
/** Suppression cloud uniquement (outbox `delete_resource`), physique intact. */
|
||||
/**
|
||||
* Suppression cloud uniquement (outbox `delete_resource` + tombstone locale,
|
||||
* M5) : le dossier et toute sa descendance Room passent `exists = 0` dans
|
||||
* la MÊME transaction — le physique reste intact mais l'arbre disparaît de
|
||||
* l'UI et le walk ne le ressuscite plus (garde `hasPendingDeleteOperation`).
|
||||
*/
|
||||
private suspend fun deleteInCloud(folder: FolderEntity): Boolean {
|
||||
var ok = false
|
||||
runCatching {
|
||||
outboxRepository.cancelPendingCreates(folder.resourceId)
|
||||
if (outboxRepository.hasSyncedCreateOperationAnyType(folder.resourceId)) {
|
||||
outboxRepository.enqueueDeleteResource(folder.resourceId, "folder")
|
||||
val tree = collectDescendants(folder.resourceId)
|
||||
val now = System.currentTimeMillis()
|
||||
appDatabase.withTransaction {
|
||||
treeMarkMissing(folder, tree, now)
|
||||
}
|
||||
ok = true
|
||||
Timber.d("enqueued cloud delete for folder %s", folder.resourceId)
|
||||
|
||||
@@ -29,6 +29,12 @@ import javax.inject.Singleton
|
||||
*
|
||||
* L'ordre outbox est garanti par l'insertion séquentielle : `create_resource`
|
||||
* du dossier fusionné avant les `move_resource`, avant les `delete_resource`.
|
||||
*
|
||||
* M9 — reprise après crash : chaque étape est transactionnelle et idempotente
|
||||
* (dossier réutilisé, contenus déjà déplacés naturellement ignorés), et une
|
||||
* source n'est supprimée que si elle est réellement vide après déplacement
|
||||
* (gate de vidage) — jamais de suppression d'un dossier dont le contenu n'a
|
||||
* pas pu être déplacé, jamais de doublon serveur à la relance.
|
||||
*/
|
||||
@Singleton
|
||||
class FolderMerger @Inject constructor(
|
||||
@@ -68,7 +74,10 @@ class FolderMerger @Inject constructor(
|
||||
val files = fileRepository.getFilesInFolder(src.resourceId)
|
||||
if (files.isNotEmpty()) {
|
||||
fileMover.moveFiles(files.map { it.resourceId }, merged.resourceId)
|
||||
movedFiles += files.size
|
||||
// Ne compte que les fichiers réellement partis (relecture :
|
||||
// `moveFiles` ignore silencieusement les refus SAF, et une
|
||||
// relance après crash ne doit pas recompter les déjà-déplacés).
|
||||
movedFiles += files.size - fileRepository.getFilesInFolder(src.resourceId).size
|
||||
}
|
||||
val subFolders = folderRepository.getChildren(src.resourceId)
|
||||
if (subFolders.isNotEmpty()) {
|
||||
@@ -80,6 +89,14 @@ class FolderMerger @Inject constructor(
|
||||
folderRepository.reparentSubFolders(movable.map { it.resourceId }, merged.resourceId)
|
||||
}
|
||||
}
|
||||
// Gate de vidage (M9) : ne supprimer que les sources
|
||||
// réellement vidées — un refus SAF silencieux ne doit jamais
|
||||
// mener à la suppression d'un contenu non déplacé.
|
||||
val filesLeft = fileRepository.getFilesInFolder(src.resourceId).size
|
||||
val foldersLeft = folderRepository.getChildren(src.resourceId).size
|
||||
if (filesLeft > 0 || foldersLeft > 0) {
|
||||
error("source non vidée : $filesLeft fichier(s), $foldersLeft dossier(s) restants")
|
||||
}
|
||||
}.isSuccess
|
||||
if (ok) {
|
||||
readyToDelete += src
|
||||
|
||||
@@ -72,43 +72,54 @@ class DeviceSync @Inject constructor(
|
||||
// Phase 1 — listing SAF (I/O disque, HORS transaction).
|
||||
val folders = scanner.scanTree(Uri.parse(rootUri))
|
||||
|
||||
// Phase 2 — écritures Room (transaction courte, SQL pur).
|
||||
return appDatabase.withTransaction {
|
||||
val seen = HashSet<String>()
|
||||
val resourceIdByUri = HashMap<String, String>()
|
||||
var fileCount = 0
|
||||
// Phase 2 — écritures Room par lots (m5) : chaque lot est sa propre
|
||||
// transaction courte au lieu d'une transaction géante (N upserts +
|
||||
// full-table scans sous verrou écriture → lecteurs Room bloqués,
|
||||
// jank/ANR). L'ordre parent-avant-enfant est préservé (itération
|
||||
// séquentielle, seules les frontières de commit changent).
|
||||
val seen = HashSet<String>()
|
||||
val resourceIdByUri = HashMap<String, String>()
|
||||
var fileCount = 0
|
||||
|
||||
for (folder in folders) {
|
||||
seen += folder.uri
|
||||
val parentResourceId = if (folder.parentUri == null) {
|
||||
null
|
||||
} else {
|
||||
resourceIdByUri[folder.parentUri]
|
||||
}
|
||||
if (folder.parentUri != null && parentResourceId == null) {
|
||||
// Violation parent-avant-enfant (snapshot incohérent) : on
|
||||
// n'attache JAMAIS à la racine par défaut — le dossier est
|
||||
// ignoré et journalisé, le prochain walk convergera.
|
||||
Timber.w(
|
||||
"walk: parent SAF inconnu, dossier ignoré (uri=%s parent=%s)",
|
||||
folder.uri,
|
||||
folder.parentUri,
|
||||
for (chunk in folders.chunked(SYNC_BATCH)) {
|
||||
appDatabase.withTransaction {
|
||||
for (folder in chunk) {
|
||||
seen += folder.uri
|
||||
val parentResourceId = if (folder.parentUri == null) {
|
||||
null
|
||||
} else {
|
||||
resourceIdByUri[folder.parentUri]
|
||||
}
|
||||
if (folder.parentUri != null && parentResourceId == null) {
|
||||
// Violation parent-avant-enfant (snapshot incohérent) : on
|
||||
// n'attache JAMAIS à la racine par défaut — le dossier est
|
||||
// ignoré et journalisé, le prochain walk convergera.
|
||||
Timber.w(
|
||||
"walk: parent SAF inconnu, dossier ignoré (uri=%s parent=%s)",
|
||||
folder.uri,
|
||||
folder.parentUri,
|
||||
)
|
||||
continue
|
||||
}
|
||||
val saved = folderRepository.saveFolder(
|
||||
SaveFolderInput(uri = folder.uri, name = folder.name, exists = true),
|
||||
parentResourceId = parentResourceId,
|
||||
ownerId = ownerId,
|
||||
)
|
||||
continue
|
||||
resourceIdByUri[folder.uri] = saved.resourceId
|
||||
}
|
||||
val saved = folderRepository.saveFolder(
|
||||
SaveFolderInput(uri = folder.uri, name = folder.name, exists = true),
|
||||
parentResourceId = parentResourceId,
|
||||
ownerId = ownerId,
|
||||
)
|
||||
resourceIdByUri[folder.uri] = saved.resourceId
|
||||
}
|
||||
}
|
||||
|
||||
for (folder in folders) {
|
||||
// Dossier ignoré plus haut (parent manquant) : ses fichiers ne
|
||||
// sont pas rattachés à la racine, ils attendent le walk suivant.
|
||||
val folderResourceId = resourceIdByUri[folder.uri] ?: continue
|
||||
for (file in folder.files) {
|
||||
val fileWrites = folders.flatMap { folder ->
|
||||
// Dossier ignoré plus haut (parent manquant) : ses fichiers ne
|
||||
// sont pas rattachés à la racine, ils attendent le walk suivant.
|
||||
val folderResourceId = resourceIdByUri[folder.uri] ?: return@flatMap emptyList()
|
||||
folder.files.map { file -> folderResourceId to file }
|
||||
}
|
||||
for (chunk in fileWrites.chunked(SYNC_BATCH)) {
|
||||
appDatabase.withTransaction {
|
||||
for ((folderResourceId, file) in chunk) {
|
||||
seen += file.uri
|
||||
fileRepository.saveLocalFile(
|
||||
input = SaveFileInput(
|
||||
@@ -125,45 +136,49 @@ class DeviceSync @Inject constructor(
|
||||
fileCount++
|
||||
}
|
||||
}
|
||||
|
||||
var missing = 0
|
||||
val now = System.currentTimeMillis()
|
||||
for (folder in folderRepository.getAll()) {
|
||||
val folderUri = folder.uri
|
||||
if (folder.exists != 0 && folderUri != null && isChildOf(folderUri, rootUri) && folderUri !in seen &&
|
||||
!outboxRepository.hasPendingMoveOperation(folder.resourceId)
|
||||
) {
|
||||
folderRepository.markMissing(folder.resourceId, now)
|
||||
// Disparu avant push : annule le create pending (M19) —
|
||||
// le serveur ne doit ni le créer ni l'oublier.
|
||||
outboxRepository.cancelPendingCreates(folder.resourceId)
|
||||
missing++
|
||||
}
|
||||
}
|
||||
for (file in fileRepository.getAll()) {
|
||||
val fileUri = file.uri
|
||||
// Un `move_resource` encore `pending` fait de l'outbox la
|
||||
// source de vérité du placement : on ne masque jamais une ligne
|
||||
// en transition vers une autre arborescence physique (le
|
||||
// snapshot peut être périmé par rapport au move en cours).
|
||||
// Un move déjà `synced` ne protège plus : si le fichier a
|
||||
// ensuite disparu du disque, c'est une vraie suppression
|
||||
// (sinon fantôme `exists = 1` éternel, M4).
|
||||
if (file.exists != 0 && fileUri != null && isChildOf(fileUri, rootUri) && fileUri !in seen &&
|
||||
!outboxRepository.hasPendingMoveOperation(file.resourceId)
|
||||
) {
|
||||
fileRepository.markMissing(file.resourceId, now)
|
||||
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||
missing++
|
||||
}
|
||||
}
|
||||
|
||||
SyncResult(rootUri = rootUri, folders = folders.size, files = fileCount, missing = missing)
|
||||
}
|
||||
|
||||
var missing = 0
|
||||
val now = System.currentTimeMillis()
|
||||
// Réconciliation scopée à la racine (m5) : fini les `getAll()`
|
||||
// O(racines×DB) — le SQL filtre par préfixe d'uri (échappé).
|
||||
for (folder in folderRepository.getUnderRoot(rootUri)) {
|
||||
val folderUri = folder.uri
|
||||
if (folder.exists != 0 && folderUri != null && folderUri !in seen &&
|
||||
!outboxRepository.hasPendingMoveOperation(folder.resourceId)
|
||||
) {
|
||||
folderRepository.markMissing(folder.resourceId, now)
|
||||
// Disparu avant push : annule le create pending (M19) —
|
||||
// le serveur ne doit ni le créer ni l'oublier.
|
||||
outboxRepository.cancelPendingCreates(folder.resourceId)
|
||||
missing++
|
||||
}
|
||||
}
|
||||
for (file in fileRepository.getUnderRoot(rootUri)) {
|
||||
val fileUri = file.uri
|
||||
// Un `move_resource` encore `pending` fait de l'outbox la
|
||||
// source de vérité du placement : on ne masque jamais une ligne
|
||||
// en transition vers une autre arborescence physique (le
|
||||
// snapshot peut être périmé par rapport au move en cours).
|
||||
// Un move déjà `synced` ne protège plus : si le fichier a
|
||||
// ensuite disparu du disque, c'est une vraie suppression
|
||||
// (sinon fantôme `exists = 1` éternel, M4).
|
||||
if (file.exists != 0 && fileUri != null && fileUri !in seen &&
|
||||
!outboxRepository.hasPendingMoveOperation(file.resourceId)
|
||||
) {
|
||||
fileRepository.markMissing(file.resourceId, now)
|
||||
outboxRepository.cancelPendingCreates(file.resourceId)
|
||||
missing++
|
||||
}
|
||||
}
|
||||
|
||||
return SyncResult(rootUri = rootUri, folders = folders.size, files = fileCount, missing = missing)
|
||||
}
|
||||
|
||||
private fun isChildOf(uri: String, rootUri: String): Boolean =
|
||||
uri == rootUri || uri.startsWith("$rootUri/")
|
||||
companion object {
|
||||
/** Taille des lots d'upserts Room du walk (m5 : transactions courtes). */
|
||||
private const val SYNC_BATCH = 200
|
||||
}
|
||||
}
|
||||
|
||||
private fun String.extensionOrNull(): String? {
|
||||
|
||||
@@ -106,31 +106,52 @@ class SyncViewModel @Inject constructor(
|
||||
delay(FIRST_DELAY_MS)
|
||||
while (isActive) {
|
||||
_walkInProgress.value = true
|
||||
runCatching { deviceSync.syncAll() }
|
||||
.onSuccess { results ->
|
||||
if (results.isNotEmpty()) Timber.d("syncAll: %s", results)
|
||||
// Les nouvelles ressources découvertes sont dans l'outbox
|
||||
// → drainer vers POST /sync/ops (single-flight via KEEP).
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
// OCR auto : uploader les octets des fichiers récemment promus (local-cloud).
|
||||
OcrAutoWorker.enqueue(appContext)
|
||||
// Repasse C4 : les suppressions journalisées dont les
|
||||
// octets ont survécu (crash entre journal et SAF).
|
||||
runCatching {
|
||||
fileDeleter.sweepPendingPhysicalDeletes() +
|
||||
folderDeleter.sweepPendingPhysicalDeletes()
|
||||
}.onSuccess { swept ->
|
||||
if (swept > 0) Timber.d("sweep: %d suppressions physiques rattrapées", swept)
|
||||
}.onFailure { e ->
|
||||
Timber.w(e, "sweep failed, retrying later")
|
||||
try {
|
||||
var changed = false
|
||||
runCatching { deviceSync.syncAll() }
|
||||
.onSuccess { results ->
|
||||
if (results.isNotEmpty()) Timber.d("syncAll: %s", results)
|
||||
changed = results.any { it.folders > 0 || it.files > 0 || it.missing > 0 }
|
||||
// Repasse C4 : les suppressions journalisées dont les
|
||||
// octets ont survécu (crash entre journal et SAF).
|
||||
runCatching {
|
||||
fileDeleter.sweepPendingPhysicalDeletes() +
|
||||
folderDeleter.sweepPendingPhysicalDeletes()
|
||||
}.onSuccess { swept ->
|
||||
if (swept > 0) {
|
||||
Timber.d("sweep: %d suppressions physiques rattrapées", swept)
|
||||
changed = true
|
||||
}
|
||||
}.onFailure { e ->
|
||||
Timber.w(e, "sweep failed, retrying later")
|
||||
}
|
||||
}
|
||||
.onFailure { e ->
|
||||
if (e is CancellationException) throw e
|
||||
Timber.w(e, "syncAll failed, retrying later")
|
||||
}
|
||||
// Hydrate les ressources partagées depuis le snapshot serveur.
|
||||
// Échec réseau toléré : le prochain tick réessaiera.
|
||||
runCatching { shareRepository.syncSnapshot() }
|
||||
.onFailure { e ->
|
||||
if (e is CancellationException) throw e
|
||||
Timber.d("syncSnapshot failed, retrying later: %s", e.message)
|
||||
}
|
||||
// m2 : ne réveiller WorkManager que si le tick a produit
|
||||
// quelque chose (walk/sweep) ou si l'outbox attend un drain
|
||||
// (op partagée depuis l'UI, drain précédent interrompu…).
|
||||
// Les nouvelles ressources découvertes sont dans l'outbox
|
||||
// → drainer vers POST /sync/ops (single-flight via KEEP) ;
|
||||
// OCR auto : octets des fichiers récemment promus.
|
||||
if (changed || pendingOperationDao.countPending() > 0) {
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
OcrAutoWorker.enqueue(appContext)
|
||||
}
|
||||
.onFailure { e -> Timber.w(e, "syncAll failed, retrying later") }
|
||||
// Hydrate les ressources partagées depuis le snapshot serveur.
|
||||
// Échec réseau toléré : le prochain tick réessaiera.
|
||||
runCatching { shareRepository.syncSnapshot() }
|
||||
.onFailure { e -> Timber.d("syncSnapshot failed, retrying later: %s", e.message) }
|
||||
_walkInProgress.value = false
|
||||
} finally {
|
||||
// m1 : le badge « syncing » retombe même si le scope est
|
||||
// annulé ou si le snapshot réseau a échoué.
|
||||
_walkInProgress.value = false
|
||||
}
|
||||
delay(INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,8 +50,8 @@ class AuthViewModel @Inject constructor(
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
OcrAutoWorker.enqueue(appContext)
|
||||
if (session != null) {
|
||||
// Snapshot complet des permissions partagées (convergence).
|
||||
runCatching { shareRepository.syncSnapshot() }
|
||||
// Snapshot complet des permissions partagées (convergence, M27).
|
||||
runCatching { shareRepository.syncSnapshot(forceFull = true) }
|
||||
.onFailure { e -> Timber.d("syncSnapshot on restore failed: %s", e.message) }
|
||||
}
|
||||
}
|
||||
@@ -72,8 +72,8 @@ class AuthViewModel @Inject constructor(
|
||||
// Connexion réussie → pousser les mutations locales en attente.
|
||||
OutboxSyncWorker.enqueue(appContext)
|
||||
OcrAutoWorker.enqueue(appContext)
|
||||
// Snapshot complet des permissions partagées (convergence).
|
||||
runCatching { shareRepository.syncSnapshot() }
|
||||
// Snapshot complet des permissions partagées (convergence, M27).
|
||||
runCatching { shareRepository.syncSnapshot(forceFull = true) }
|
||||
.onFailure { e -> Timber.d("syncSnapshot on login failed: %s", e.message) }
|
||||
}
|
||||
.onFailure { e ->
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.kazier.mobile.ui.auth
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material.icons.filled.VisibilityOff
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.kazier.mobile.R
|
||||
|
||||
/**
|
||||
* Formulaire d'authentification partagé (Login + Réglages) : validation
|
||||
* inline (champs non vides), touche Done = submit, œil voir/masquer le mot
|
||||
* de passe, erreur centrée sous le bouton.
|
||||
*/
|
||||
@Composable
|
||||
fun LoginForm(
|
||||
username: String,
|
||||
onUsernameChange: (String) -> Unit,
|
||||
password: String,
|
||||
onPasswordChange: (String) -> Unit,
|
||||
submitting: Boolean,
|
||||
errorRes: Int?,
|
||||
submitLabel: String,
|
||||
onSubmit: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var passwordVisible by rememberSaveable { mutableStateOf(false) }
|
||||
// Pas d'appel réseau pour des champs vides — validation pure UI.
|
||||
val canSubmit = !submitting && username.isNotBlank() && password.isNotBlank()
|
||||
val submitIfValid = { if (canSubmit) onSubmit() }
|
||||
|
||||
Column(
|
||||
modifier = modifier,
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = username,
|
||||
onValueChange = onUsernameChange,
|
||||
label = { Text(stringResource(R.string.login_username)) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Text,
|
||||
imeAction = ImeAction.Next,
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = onPasswordChange,
|
||||
label = { Text(stringResource(R.string.login_password)) },
|
||||
singleLine = true,
|
||||
visualTransformation = if (passwordVisible) {
|
||||
VisualTransformation.None
|
||||
} else {
|
||||
PasswordVisualTransformation()
|
||||
},
|
||||
trailingIcon = {
|
||||
IconButton(onClick = { passwordVisible = !passwordVisible }) {
|
||||
Icon(
|
||||
imageVector = if (passwordVisible) {
|
||||
Icons.Filled.VisibilityOff
|
||||
} else {
|
||||
Icons.Filled.Visibility
|
||||
},
|
||||
contentDescription = stringResource(
|
||||
if (passwordVisible) {
|
||||
R.string.login_hide_password
|
||||
} else {
|
||||
R.string.login_show_password
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
keyboardActions = KeyboardActions(onDone = { submitIfValid() }),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Button(
|
||||
onClick = submitIfValid,
|
||||
enabled = canSubmit,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
if (submitting) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(20.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
} else {
|
||||
Text(submitLabel)
|
||||
}
|
||||
}
|
||||
if (errorRes != null) {
|
||||
Text(
|
||||
text = stringResource(errorRes),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,34 +8,32 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.kazier.mobile.R
|
||||
|
||||
/**
|
||||
* Premier écran : choix explicite entre compte serveur et mode local, puis
|
||||
* formulaire de connexion. Le mode local est expliqué avant d'être choisi
|
||||
* (pas un petit lien d'esquive sous le formulaire).
|
||||
*/
|
||||
@Composable
|
||||
fun LoginScreen(
|
||||
viewModel: AuthViewModel = hiltViewModel(),
|
||||
@@ -44,6 +42,7 @@ fun LoginScreen(
|
||||
|
||||
var username by rememberSaveable { mutableStateOf("") }
|
||||
var password by rememberSaveable { mutableStateOf("") }
|
||||
var showForm by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
@@ -60,70 +59,59 @@ fun LoginScreen(
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.login_subtitle),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(32.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = username,
|
||||
onValueChange = { username = it },
|
||||
label = { Text(stringResource(R.string.login_username)) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = { password = it },
|
||||
label = { Text(stringResource(R.string.login_password)) },
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
|
||||
Button(
|
||||
onClick = { viewModel.signIn(username, password) },
|
||||
enabled = !loginUi.isSubmitting,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
if (loginUi.isSubmitting) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(20.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
} else {
|
||||
Text(stringResource(R.string.login_submit))
|
||||
}
|
||||
}
|
||||
|
||||
loginUi.error?.let { error ->
|
||||
Spacer(Modifier.height(12.dp))
|
||||
if (!showForm) {
|
||||
Text(
|
||||
text = stringResource(authErrorResFor(error)),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
text = stringResource(R.string.login_choice_subtitle),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(32.dp))
|
||||
Button(
|
||||
onClick = { showForm = true },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(stringResource(R.string.login_submit))
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
OutlinedButton(
|
||||
onClick = viewModel::continueWithoutAccount,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(stringResource(R.string.login_skip))
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.skip_message),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
} else {
|
||||
Text(
|
||||
text = stringResource(R.string.login_subtitle),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(32.dp))
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
TextButton(onClick = viewModel::continueWithoutAccount) {
|
||||
Text(stringResource(R.string.login_skip))
|
||||
LoginForm(
|
||||
username = username,
|
||||
onUsernameChange = { username = it },
|
||||
password = password,
|
||||
onPasswordChange = { password = it },
|
||||
submitting = loginUi.isSubmitting,
|
||||
errorRes = loginUi.error?.let(::authErrorResFor),
|
||||
submitLabel = stringResource(R.string.login_submit),
|
||||
onSubmit = { viewModel.signIn(username, password) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
TextButton(onClick = { showForm = false }) {
|
||||
Text(stringResource(R.string.back))
|
||||
}
|
||||
}
|
||||
Text(
|
||||
text = stringResource(R.string.skip_message),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
+13
-9
@@ -17,25 +17,27 @@ import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.data.local.entity.FileStatus
|
||||
import com.kazier.mobile.features.saf.FileDeleter
|
||||
import com.kazier.mobile.ui.theme.NavItemShape
|
||||
import java.io.Serializable
|
||||
|
||||
/** Résultat de l\'analyse de compatibilité entre les fichiers et le mode choisi. */
|
||||
/** Résultat de l'analyse de compatibilité entre les fichiers et le mode choisi. */
|
||||
data class DeleteReview(
|
||||
val mode: FileDeleter.DeleteMode,
|
||||
val total: Int,
|
||||
val incompatibleCount: Int,
|
||||
) {
|
||||
) : Serializable {
|
||||
val hasWarning: Boolean get() = incompatibleCount > 0
|
||||
}
|
||||
|
||||
@@ -61,15 +63,16 @@ fun DeleteDropdownButton(
|
||||
onModeSelected: (FileDeleter.DeleteMode) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
var expanded by rememberSaveable { mutableStateOf(false) }
|
||||
val tint = if (enabled) MaterialTheme.colorScheme.error
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant
|
||||
val deleteLabel = stringResource(R.string.delete)
|
||||
|
||||
Box(modifier = modifier) {
|
||||
Surface(
|
||||
onClick = { if (enabled) expanded = true },
|
||||
enabled = enabled,
|
||||
shape = androidx.compose.foundation.shape.RoundedCornerShape(20.dp),
|
||||
shape = NavItemShape,
|
||||
color = if (enabled) MaterialTheme.colorScheme.errorContainer
|
||||
else MaterialTheme.colorScheme.surfaceVariant,
|
||||
modifier = modifier,
|
||||
@@ -84,15 +87,16 @@ fun DeleteDropdownButton(
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Delete,
|
||||
contentDescription = null,
|
||||
contentDescription = deleteLabel,
|
||||
tint = tint,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.delete),
|
||||
text = deleteLabel,
|
||||
color = tint,
|
||||
fontSize = 11.sp,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
Icon(
|
||||
|
||||
+31
-13
@@ -9,12 +9,15 @@ import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.MusicNote
|
||||
import androidx.compose.material.icons.filled.PictureAsPdf
|
||||
import androidx.compose.material.icons.filled.TextSnippet
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.domain.FileCategory
|
||||
import com.kazier.mobile.domain.computeCategory
|
||||
@@ -31,17 +34,32 @@ val FileCategory.icon: ImageVector
|
||||
FileCategory.OTHER -> Icons.Filled.InsertDriveFile
|
||||
}
|
||||
|
||||
/** Teinte dédiée à chaque catégorie de document. */
|
||||
val FileCategory.color: Color
|
||||
get() = when (this) {
|
||||
FileCategory.PDF -> Color(0xFFD32F2F)
|
||||
FileCategory.OFFICE -> Color(0xFF1565C0)
|
||||
FileCategory.IMAGE -> Color(0xFF2E7D32)
|
||||
FileCategory.TEXT -> Color(0xFF546E7A)
|
||||
FileCategory.VIDEO -> Color(0xFF6A1B9A)
|
||||
FileCategory.AUDIO -> Color(0xFFAD1457)
|
||||
FileCategory.OTHER -> Color(0xFF757575)
|
||||
/** Teinte dédiée à chaque catégorie — déclinaison light/dark lisible sur les deux thèmes. */
|
||||
@Composable
|
||||
fun FileCategory.color(): androidx.compose.ui.graphics.Color {
|
||||
val dark = isSystemInDarkTheme()
|
||||
return when (this) {
|
||||
FileCategory.PDF -> if (dark) androidx.compose.ui.graphics.Color(0xFFE57373) else androidx.compose.ui.graphics.Color(0xFFD32F2F)
|
||||
FileCategory.OFFICE -> if (dark) androidx.compose.ui.graphics.Color(0xFF90CAF9) else androidx.compose.ui.graphics.Color(0xFF1565C0)
|
||||
FileCategory.IMAGE -> if (dark) androidx.compose.ui.graphics.Color(0xFF81C784) else androidx.compose.ui.graphics.Color(0xFF2E7D32)
|
||||
FileCategory.TEXT -> if (dark) androidx.compose.ui.graphics.Color(0xFFB0BEC5) else androidx.compose.ui.graphics.Color(0xFF546E7A)
|
||||
FileCategory.VIDEO -> if (dark) androidx.compose.ui.graphics.Color(0xFFCE93D8) else androidx.compose.ui.graphics.Color(0xFF6A1B9A)
|
||||
FileCategory.AUDIO -> if (dark) androidx.compose.ui.graphics.Color(0xFFF48FB1) else androidx.compose.ui.graphics.Color(0xFFAD1457)
|
||||
FileCategory.OTHER -> if (dark) androidx.compose.ui.graphics.Color(0xFFBDBDBD) else androidx.compose.ui.graphics.Color(0xFF757575)
|
||||
}
|
||||
}
|
||||
|
||||
/** Libellé i18n de la catégorie — utilisé comme contentDescription. */
|
||||
@Composable
|
||||
fun FileCategory.label(): String = when (this) {
|
||||
FileCategory.PDF -> stringResource(R.string.category_pdf)
|
||||
FileCategory.OFFICE -> stringResource(R.string.category_office)
|
||||
FileCategory.IMAGE -> stringResource(R.string.category_image)
|
||||
FileCategory.TEXT -> stringResource(R.string.category_text)
|
||||
FileCategory.VIDEO -> stringResource(R.string.category_video)
|
||||
FileCategory.AUDIO -> stringResource(R.string.category_audio)
|
||||
FileCategory.OTHER -> stringResource(R.string.category_other)
|
||||
}
|
||||
|
||||
/**
|
||||
* Catégorie d'un fichier : valeur stockée (`category`, colonne ajoutée en v4)
|
||||
@@ -63,8 +81,8 @@ fun FileCategoryIcon(
|
||||
val category = file.categoryValue()
|
||||
Icon(
|
||||
imageVector = category.icon,
|
||||
contentDescription = null,
|
||||
tint = category.color,
|
||||
contentDescription = category.label(),
|
||||
tint = category.color(),
|
||||
modifier = modifier.size(size),
|
||||
)
|
||||
}
|
||||
+2
-2
@@ -7,7 +7,6 @@ import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
@@ -19,6 +18,7 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.ui.theme.ThumbShape
|
||||
|
||||
/**
|
||||
* Un fichier est « à traiter » s'il est présent physiquement et jamais encore
|
||||
@@ -41,7 +41,7 @@ fun FilePendingReviewBadge(
|
||||
) {
|
||||
if (!file.isPendingReview()) return
|
||||
Surface(
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
shape = ThumbShape,
|
||||
color = MaterialTheme.colorScheme.tertiaryContainer,
|
||||
modifier = modifier,
|
||||
) {
|
||||
|
||||
+21
-9
@@ -5,12 +5,14 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Cloud
|
||||
import androidx.compose.material.icons.filled.CloudDone
|
||||
import androidx.compose.material.icons.filled.CloudOff
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.data.local.entity.FileStatus
|
||||
|
||||
@@ -35,13 +37,23 @@ private val FileSyncPlacement.icon: ImageVector
|
||||
FileSyncPlacement.LOCAL_CLOUD -> Icons.Filled.CloudDone
|
||||
}
|
||||
|
||||
/** Teinte dédiée à chaque placement. */
|
||||
private val FileSyncPlacement.color: Color
|
||||
get() = when (this) {
|
||||
FileSyncPlacement.LOCAL -> Color(0xFFF57F17)
|
||||
FileSyncPlacement.CLOUD -> Color(0xFF1565C0)
|
||||
FileSyncPlacement.LOCAL_CLOUD -> Color(0xFF2E7D32)
|
||||
/** Teinte dédiée à chaque placement — déclinaison light/dark. */
|
||||
@Composable
|
||||
private fun FileSyncPlacement.color(): androidx.compose.ui.graphics.Color {
|
||||
val dark = isSystemInDarkTheme()
|
||||
return when (this) {
|
||||
FileSyncPlacement.LOCAL -> if (dark) androidx.compose.ui.graphics.Color(0xFFFFB74D) else androidx.compose.ui.graphics.Color(0xFFB26A00)
|
||||
FileSyncPlacement.CLOUD -> if (dark) androidx.compose.ui.graphics.Color(0xFF90CAF9) else androidx.compose.ui.graphics.Color(0xFF1565C0)
|
||||
FileSyncPlacement.LOCAL_CLOUD -> if (dark) androidx.compose.ui.graphics.Color(0xFF81C784) else androidx.compose.ui.graphics.Color(0xFF2E7D32)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FileSyncPlacement.label(): String = when (this) {
|
||||
FileSyncPlacement.LOCAL -> stringResource(R.string.sync_placement_local)
|
||||
FileSyncPlacement.CLOUD -> stringResource(R.string.sync_placement_cloud)
|
||||
FileSyncPlacement.LOCAL_CLOUD -> stringResource(R.string.sync_placement_local_cloud)
|
||||
}
|
||||
|
||||
/** Statut de sync d'un fichier — présence device / serveur distant. */
|
||||
@Composable
|
||||
@@ -53,8 +65,8 @@ fun FileSyncStatusIcon(
|
||||
val placement = file.syncPlacement()
|
||||
Icon(
|
||||
imageVector = placement.icon,
|
||||
contentDescription = null,
|
||||
tint = placement.color,
|
||||
contentDescription = placement.label(),
|
||||
tint = placement.color(),
|
||||
modifier = modifier.size(size),
|
||||
)
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package com.kazier.mobile.ui.components
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.produceState
|
||||
@@ -13,12 +12,12 @@ import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import coil.compose.AsyncImage
|
||||
import coil.request.ImageRequest
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.domain.FileCategory
|
||||
import com.kazier.mobile.features.thumbnails.ThumbnailStore
|
||||
import com.kazier.mobile.ui.theme.ThumbShape
|
||||
import dagger.hilt.EntryPoint
|
||||
import dagger.hilt.InstallIn
|
||||
import dagger.hilt.android.EntryPointAccessors
|
||||
@@ -41,7 +40,7 @@ fun FileThumbnail(
|
||||
file: FileEntity,
|
||||
size: Dp,
|
||||
modifier: Modifier = Modifier,
|
||||
shape: Shape = RoundedCornerShape(8.dp),
|
||||
shape: Shape = ThumbShape,
|
||||
) {
|
||||
val category = file.categoryValue()
|
||||
if (category != FileCategory.IMAGE && category != FileCategory.PDF) {
|
||||
|
||||
@@ -8,7 +8,7 @@ import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -20,7 +20,7 @@ fun FolderNameDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: (String) -> Unit,
|
||||
) {
|
||||
var name by remember { mutableStateOf("") }
|
||||
var name by rememberSaveable { mutableStateOf("") }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.new_folder_name_title)) },
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.kazier.mobile.ui.components
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.kazier.mobile.R
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Formattage de taille centralisé (Phase 0) : remplace les 5 copies
|
||||
* (`FolderList`, `FolderDetail`, `Search`, `Document`, `SwipeCardDeck`,
|
||||
* `PdfBuilder`) dont 2 en français en dur (`o/ko/Mo`).
|
||||
* Utilise les strings i18n `unit_bytes / unit_kilobytes / unit_megabytes`.
|
||||
*/
|
||||
@Composable
|
||||
fun formatFileSize(bytes: Long): String {
|
||||
val safe = bytes.coerceAtLeast(0)
|
||||
if (safe < 1_024) {
|
||||
return "$safe ${stringResource(R.string.unit_bytes)}"
|
||||
}
|
||||
if (safe < 1_024 * 1_024) {
|
||||
val kb = safe / 1_024f
|
||||
return String.format(
|
||||
Locale.getDefault(),
|
||||
"%.1f %s",
|
||||
kb,
|
||||
stringResource(R.string.unit_kilobytes),
|
||||
)
|
||||
}
|
||||
val mb = safe / (1_024f * 1_024f)
|
||||
return String.format(
|
||||
Locale.getDefault(),
|
||||
"%.1f %s",
|
||||
mb,
|
||||
stringResource(R.string.unit_megabytes),
|
||||
)
|
||||
}
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
package com.kazier.mobile.ui.components
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
||||
import com.kazier.mobile.features.connection.ServerConnectionStatus
|
||||
import com.kazier.mobile.features.sync.SyncViewModel
|
||||
import com.kazier.mobile.ui.theme.PendingDark
|
||||
import com.kazier.mobile.ui.theme.PendingLight
|
||||
import com.kazier.mobile.ui.theme.PillShape
|
||||
import com.kazier.mobile.ui.theme.SuccessDark
|
||||
import com.kazier.mobile.ui.theme.SuccessLight
|
||||
import com.kazier.mobile.ui.theme.SyncingDark
|
||||
import com.kazier.mobile.ui.theme.SyncingLight
|
||||
|
||||
/**
|
||||
* Pastille de statut unique du header : un point coloré (ou spinner pendant
|
||||
* une synchro) + un libellé. Un appui ouvre le bottom-sheet « état » :
|
||||
* statut serveur, bouton de test, résumé de la file d'envoi et accès à son
|
||||
* détail.
|
||||
*
|
||||
* En mode local il n'y a rien à pousser : la pastille affiche « Mode local »
|
||||
* et le sheet l'explique sans proposer de test (le tap-à-vérifier serait
|
||||
* une impasse).
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun HeaderStatusAction(
|
||||
syncViewModel: SyncViewModel,
|
||||
connectionStatusViewModel: ConnectionStatusViewModel,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
||||
val syncStatus by syncViewModel.syncStatus.collectAsStateWithLifecycle()
|
||||
var showSheet by rememberSaveable { mutableStateOf(false) }
|
||||
var showQueue by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
val isLocal = connectionStatus == ServerConnectionStatus.Local
|
||||
val dark = isSystemInDarkTheme()
|
||||
val onlineGreen = if (dark) SuccessDark else SuccessLight
|
||||
val pendingAmber = if (dark) PendingDark else PendingLight
|
||||
val syncingAccent = if (dark) SyncingDark else SyncingLight
|
||||
|
||||
val (dotColor, label, showSpinner) = when {
|
||||
isLocal -> Triple(
|
||||
MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
stringResource(R.string.status_local),
|
||||
false,
|
||||
)
|
||||
connectionStatus == ServerConnectionStatus.Checking -> Triple(
|
||||
pendingAmber,
|
||||
stringResource(R.string.status_checking),
|
||||
false,
|
||||
)
|
||||
syncStatus.syncing -> Triple(
|
||||
syncingAccent,
|
||||
stringResource(R.string.sync_syncing),
|
||||
true,
|
||||
)
|
||||
syncStatus.pending > 0 -> {
|
||||
val text = if (syncStatus.pending == 1) {
|
||||
stringResource(R.string.sync_pending_count_one)
|
||||
} else {
|
||||
stringResource(R.string.sync_pending_count, syncStatus.pending)
|
||||
}
|
||||
val color = if (connectionStatus == ServerConnectionStatus.Offline) {
|
||||
MaterialTheme.colorScheme.error
|
||||
} else {
|
||||
pendingAmber
|
||||
}
|
||||
Triple(color, text, false)
|
||||
}
|
||||
syncStatus.failed > 0 -> Triple(
|
||||
MaterialTheme.colorScheme.error,
|
||||
stringResource(R.string.sync_summary_failed, syncStatus.failed),
|
||||
false,
|
||||
)
|
||||
connectionStatus == ServerConnectionStatus.Offline -> Triple(
|
||||
MaterialTheme.colorScheme.error,
|
||||
stringResource(R.string.status_offline),
|
||||
false,
|
||||
)
|
||||
else -> Triple(
|
||||
onlineGreen,
|
||||
stringResource(R.string.status_online),
|
||||
false,
|
||||
)
|
||||
}
|
||||
val tapLabel = stringResource(R.string.sync_tap_to_view)
|
||||
|
||||
Row(
|
||||
modifier = modifier
|
||||
.clip(PillShape)
|
||||
.clickable(
|
||||
role = Role.Button,
|
||||
onClickLabel = tapLabel,
|
||||
onClick = { showSheet = true },
|
||||
)
|
||||
.padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
if (showSpinner) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(12.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = dotColor,
|
||||
)
|
||||
} else {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(8.dp)
|
||||
.background(dotColor, CircleShape),
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
if (showSheet) {
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = { showSheet = false },
|
||||
sheetState = rememberModalBottomSheetState(),
|
||||
) {
|
||||
StatusSheetContent(
|
||||
connectionStatus = connectionStatus,
|
||||
syncStatus = syncStatus,
|
||||
onTest = connectionStatusViewModel::checkNow,
|
||||
onViewQueue = {
|
||||
showSheet = false
|
||||
showQueue = true
|
||||
},
|
||||
onDismiss = { showSheet = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (showQueue) {
|
||||
SyncOperationsDialog(
|
||||
status = syncStatus,
|
||||
onDismiss = { showQueue = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusSheetContent(
|
||||
connectionStatus: ServerConnectionStatus,
|
||||
syncStatus: SyncViewModel.SyncStatus,
|
||||
onTest: () -> Unit,
|
||||
onViewQueue: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val isLocal = connectionStatus == ServerConnectionStatus.Local
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp)
|
||||
.padding(bottom = 32.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.status_sheet_title),
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
StatusServerRow(
|
||||
status = connectionStatus,
|
||||
onTest = onTest,
|
||||
)
|
||||
if (isLocal) {
|
||||
Text(
|
||||
text = stringResource(R.string.skip_message),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
} else {
|
||||
HorizontalDivider()
|
||||
StatusSyncSection(
|
||||
status = syncStatus,
|
||||
onViewQueue = onViewQueue,
|
||||
)
|
||||
}
|
||||
TextButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.align(Alignment.End),
|
||||
) {
|
||||
Text(stringResource(R.string.settings_close))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusServerRow(
|
||||
status: ServerConnectionStatus,
|
||||
onTest: () -> Unit,
|
||||
) {
|
||||
val dark = isSystemInDarkTheme()
|
||||
val dotColor = when (status) {
|
||||
ServerConnectionStatus.Checking -> if (dark) PendingDark else PendingLight
|
||||
ServerConnectionStatus.Online -> if (dark) SuccessDark else SuccessLight
|
||||
ServerConnectionStatus.Offline -> MaterialTheme.colorScheme.error
|
||||
ServerConnectionStatus.Local -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
val label = stringResource(
|
||||
when (status) {
|
||||
ServerConnectionStatus.Checking -> R.string.status_checking
|
||||
ServerConnectionStatus.Online -> R.string.status_online
|
||||
ServerConnectionStatus.Offline -> R.string.status_offline
|
||||
ServerConnectionStatus.Local -> R.string.status_local
|
||||
},
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(12.dp)
|
||||
.background(dotColor, CircleShape),
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = stringResource(R.string.settings_server),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
}
|
||||
if (status != ServerConnectionStatus.Local) {
|
||||
OutlinedButton(
|
||||
onClick = onTest,
|
||||
enabled = status != ServerConnectionStatus.Checking,
|
||||
) {
|
||||
Text(stringResource(R.string.settings_test_connection))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusSyncSection(
|
||||
status: SyncViewModel.SyncStatus,
|
||||
onViewQueue: () -> Unit,
|
||||
) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(
|
||||
text = stringResource(R.string.dashboard_sync_title),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
when {
|
||||
status.syncing -> {
|
||||
Text(
|
||||
text = stringResource(R.string.sync_syncing),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
}
|
||||
status.pending > 0 -> {
|
||||
Text(
|
||||
text = if (status.pending == 1) {
|
||||
stringResource(R.string.sync_pending_count_one)
|
||||
} else {
|
||||
stringResource(R.string.sync_pending_count, status.pending)
|
||||
},
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
}
|
||||
status.failed > 0 -> {
|
||||
Text(
|
||||
text = stringResource(R.string.sync_summary_failed, status.failed),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
else -> {
|
||||
Text(
|
||||
text = stringResource(R.string.sync_idle),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
}
|
||||
}
|
||||
OutlinedButton(onClick = onViewQueue) {
|
||||
Text(stringResource(R.string.status_sheet_view_queue))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.kazier.mobile.ui.components
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import com.kazier.mobile.ui.theme.KazierDimens
|
||||
import com.kazier.mobile.ui.theme.ListCardShape
|
||||
|
||||
/**
|
||||
* Carte de liste unifiée (Phase 0) : remplace les 3 recettes dispersées
|
||||
* (`surfaceVariant+elev 1dp`, `surface+elev 1dp`, `#F7F8FA + border #EAEAEA`).
|
||||
* Couleurs 100% thème → lisible en dark mode.
|
||||
*
|
||||
* Le clic (simple ou combiné long) se gère via `modifier` pour préserver
|
||||
* les `combinedClickable` de sélection — pas de `onClick` M3 ici.
|
||||
*/
|
||||
@Composable
|
||||
fun KazierCard(
|
||||
modifier: Modifier = Modifier,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
Card(
|
||||
modifier = modifier,
|
||||
shape = ListCardShape,
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
contentColor = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
border = BorderStroke(
|
||||
KazierDimens.CardBorderWidth,
|
||||
MaterialTheme.colorScheme.outlineVariant,
|
||||
),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = KazierDimens.CardElevation),
|
||||
content = { content() },
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.kazier.mobile.ui.components
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.kazier.mobile.R
|
||||
|
||||
/**
|
||||
* CTA « documents à traiter » partagé (dashboard + écran Fichiers) : la
|
||||
* file review reste joignable même sans passer par le dashboard.
|
||||
*/
|
||||
@Composable
|
||||
fun ReviewCtaCard(
|
||||
count: Int,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val label = stringResource(R.string.dashboard_review_title, count)
|
||||
KazierCard(
|
||||
modifier = modifier.clickable(
|
||||
role = Role.Button,
|
||||
onClickLabel = label,
|
||||
onClick = onClick,
|
||||
),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(20.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.dashboard_review_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,11 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.selected
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.kazier.mobile.R
|
||||
|
||||
/**
|
||||
* État du mode multi-sélection (long-press pour entrer, tap pour cocher).
|
||||
@@ -50,12 +54,16 @@ fun rememberSelectionState(): SelectionState = remember { SelectionState() }
|
||||
fun SelectionStatusIcon(selected: Boolean, modifier: Modifier = Modifier) {
|
||||
Icon(
|
||||
imageVector = if (selected) Icons.Filled.CheckCircle else Icons.Filled.RadioButtonUnchecked,
|
||||
contentDescription = null,
|
||||
contentDescription = stringResource(
|
||||
if (selected) R.string.selection_selected else R.string.selection_unselected,
|
||||
),
|
||||
tint = if (selected) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
modifier = modifier.size(24.dp),
|
||||
modifier = modifier
|
||||
.size(24.dp)
|
||||
.semantics { this.selected = selected },
|
||||
)
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package com.kazier.mobile.ui.components
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.features.connection.ServerConnectionStatus
|
||||
import com.kazier.mobile.ui.theme.InactiveGray
|
||||
|
||||
private val OnlineGreen = Color(0xFF2E7D32)
|
||||
private val CheckingAmber = Color(0xFFF9A825)
|
||||
|
||||
/**
|
||||
* Pilule de statut serveur affichée dans le header : cercle coloré + libellé.
|
||||
* Un appui relance une vérification immédiate du serveur.
|
||||
*/
|
||||
@Composable
|
||||
fun ServerStatusBadge(
|
||||
status: ServerConnectionStatus,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val (dotColor, labelRes) = when (status) {
|
||||
ServerConnectionStatus.Checking -> CheckingAmber to R.string.status_checking
|
||||
ServerConnectionStatus.Online -> OnlineGreen to R.string.status_online
|
||||
ServerConnectionStatus.Offline -> MaterialTheme.colorScheme.error to R.string.status_offline
|
||||
ServerConnectionStatus.Local -> InactiveGray to R.string.status_local
|
||||
}
|
||||
val label = stringResource(labelRes)
|
||||
val tapLabel = stringResource(R.string.status_tap_to_recheck)
|
||||
val shape = RoundedCornerShape(percent = 50)
|
||||
|
||||
Row(
|
||||
modifier = modifier
|
||||
.clip(shape)
|
||||
.clickable(
|
||||
role = Role.Button,
|
||||
onClickLabel = tapLabel,
|
||||
onClick = onClick,
|
||||
)
|
||||
.padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(8.dp)
|
||||
.background(dotColor, CircleShape),
|
||||
)
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
+13
-9
@@ -2,6 +2,7 @@ package com.kazier.mobile.ui.components
|
||||
|
||||
import android.text.format.DateUtils
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
@@ -20,7 +21,6 @@ import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -28,10 +28,13 @@ import com.kazier.mobile.R
|
||||
import com.kazier.mobile.data.local.entity.PendingOpStatus
|
||||
import com.kazier.mobile.data.local.entity.PendingOperationEntity
|
||||
import com.kazier.mobile.features.sync.SyncViewModel
|
||||
|
||||
private val StatusPending = Color(0xFF1E88E5)
|
||||
private val StatusSynced = Color(0xFF2E7D32)
|
||||
private val StatusFailed = Color(0xFFC62828)
|
||||
import com.kazier.mobile.ui.theme.ErrorDark
|
||||
import com.kazier.mobile.ui.theme.ErrorLight
|
||||
import com.kazier.mobile.ui.theme.KazierDimens
|
||||
import com.kazier.mobile.ui.theme.SuccessDark
|
||||
import com.kazier.mobile.ui.theme.SuccessLight
|
||||
import com.kazier.mobile.ui.theme.SyncingDark
|
||||
import com.kazier.mobile.ui.theme.SyncingLight
|
||||
|
||||
/**
|
||||
* Dialogue « liste des sync » : dernières opérations de l'outbox (tous statuts),
|
||||
@@ -58,7 +61,7 @@ internal fun SyncOperationsDialog(
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(max = 360.dp),
|
||||
.heightIn(max = KazierDimens.DialogListMaxHeight),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
items(status.operations, key = { it.id }) { op ->
|
||||
@@ -99,10 +102,11 @@ private fun SyncListSummary(status: SyncViewModel.SyncStatus) {
|
||||
|
||||
@Composable
|
||||
private fun SyncOperationRow(op: PendingOperationEntity) {
|
||||
val dark = isSystemInDarkTheme()
|
||||
val (dotColor, statusLabel) = when (op.status) {
|
||||
PendingOpStatus.PENDING -> StatusPending to stringResource(R.string.sync_status_pending)
|
||||
PendingOpStatus.SYNCED -> StatusSynced to stringResource(R.string.sync_status_synced)
|
||||
else -> StatusFailed to stringResource(R.string.sync_status_failed)
|
||||
PendingOpStatus.PENDING -> (if (dark) SyncingDark else SyncingLight) to stringResource(R.string.sync_status_pending)
|
||||
PendingOpStatus.SYNCED -> (if (dark) SuccessDark else SuccessLight) to stringResource(R.string.sync_status_synced)
|
||||
else -> (if (dark) ErrorDark else ErrorLight) to stringResource(R.string.sync_status_failed)
|
||||
}
|
||||
val opLabel = operationLabel(op.operation)
|
||||
val time = DateUtils.getRelativeTimeSpanString(op.createdAt).toString()
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
package com.kazier.mobile.ui.components
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.features.sync.SyncViewModel
|
||||
|
||||
private val SyncingAccent = Color(0xFF1E88E5)
|
||||
private val PendingAmber = Color(0xFFF9A825)
|
||||
|
||||
/**
|
||||
* Pilule de statut de synchro affichée dans le header : spinner quand une marche
|
||||
* SAF ou un drain outbox est en cours, compteur d'ops en attente sinon, coche
|
||||
* quand tout est poussé. Un appui ouvre la « liste des sync » (dernières ops).
|
||||
*/
|
||||
@Composable
|
||||
fun SyncStatusBadge(
|
||||
status: SyncViewModel.SyncStatus,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val (accent, label, showSpinner) = when {
|
||||
status.syncing -> {
|
||||
Triple(SyncingAccent, stringResource(R.string.sync_syncing), true)
|
||||
}
|
||||
status.pending > 0 -> {
|
||||
val label = if (status.pending == 1) {
|
||||
stringResource(R.string.sync_pending_count_one)
|
||||
} else {
|
||||
stringResource(R.string.sync_pending_count, status.pending)
|
||||
}
|
||||
Triple(PendingAmber, label, false)
|
||||
}
|
||||
else -> Triple(
|
||||
MaterialTheme.colorScheme.primary,
|
||||
stringResource(R.string.sync_idle),
|
||||
false,
|
||||
)
|
||||
}
|
||||
val shape = RoundedCornerShape(percent = 50)
|
||||
val tapLabel = stringResource(R.string.sync_tap_to_view)
|
||||
|
||||
Row(
|
||||
modifier = modifier
|
||||
.clip(shape)
|
||||
.clickable(
|
||||
role = Role.Button,
|
||||
onClickLabel = tapLabel,
|
||||
onClick = onClick,
|
||||
)
|
||||
.padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
if (showSpinner) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(12.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = accent,
|
||||
)
|
||||
} else if (status.pending > 0) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(14.dp)
|
||||
.background(accent, CircleShape),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = status.pending.coerceAtMost(99).toString(),
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = Color.White,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Check,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(12.dp),
|
||||
tint = accent,
|
||||
)
|
||||
}
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Composable prêt-à-poser dans un header : badge + dialogue « liste des sync ».
|
||||
* Le dialogue est géré localement (état `showList`), aucun wiring externe.
|
||||
*/
|
||||
@Composable
|
||||
fun SyncStatusAction(
|
||||
syncViewModel: SyncViewModel,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val status by syncViewModel.syncStatus.collectAsStateWithLifecycle()
|
||||
var showList by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
SyncStatusBadge(
|
||||
status = status,
|
||||
onClick = { showList = true },
|
||||
modifier = modifier,
|
||||
)
|
||||
|
||||
if (showList) {
|
||||
SyncOperationsDialog(
|
||||
status = status,
|
||||
onDismiss = { showList = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.kazier.mobile.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.kazier.mobile.ui.theme.KazierDimens
|
||||
|
||||
/**
|
||||
* Bouton d'action vertical (icône + libellé `labelSmall` ellipsé) : tient
|
||||
* sur 360dp là où des boutons horizontaux icône+texte seraient tronqués
|
||||
* (exports du scan, ajouts du PdfBuilder).
|
||||
*/
|
||||
@Composable
|
||||
fun VerticalActionButton(
|
||||
icon: ImageVector,
|
||||
label: String,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true,
|
||||
outlined: Boolean = true,
|
||||
) {
|
||||
val content: @Composable () -> Unit = {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (outlined) {
|
||||
OutlinedButton(
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
modifier = modifier.heightIn(min = KazierDimens.MinTouchTarget),
|
||||
content = { content() },
|
||||
)
|
||||
} else {
|
||||
Button(
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
modifier = modifier.heightIn(min = KazierDimens.MinTouchTarget),
|
||||
content = { content() },
|
||||
)
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -5,7 +5,6 @@ import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -23,6 +22,7 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.ui.theme.PillShape
|
||||
import com.kazier.mobile.ui.watchedfolders.WatchedFoldersViewModel
|
||||
|
||||
/** Seuil au-delà duquel le badge affiche « 99+ » au lieu du compte exact. */
|
||||
@@ -47,7 +47,7 @@ fun WatchedFoldersBadge(
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.clip(RoundedCornerShape(percent = 50))
|
||||
.clip(PillShape)
|
||||
.clickable(
|
||||
role = Role.Button,
|
||||
onClickLabel = contentDescription,
|
||||
|
||||
+132
-57
@@ -9,20 +9,27 @@ import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.DocumentScanner
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material.icons.filled.Sync
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FloatingActionButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SmallFloatingActionButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshDefaults
|
||||
import androidx.compose.material3.pulltorefresh.pullToRefresh
|
||||
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -32,9 +39,11 @@ import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
||||
import com.kazier.mobile.features.connection.ServerConnectionStatus
|
||||
import com.kazier.mobile.features.sync.SyncViewModel
|
||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
||||
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||
import com.kazier.mobile.ui.components.KazierCard
|
||||
import com.kazier.mobile.ui.components.ReviewCtaCard
|
||||
import com.kazier.mobile.ui.navigation.FloatingNavBar
|
||||
import com.kazier.mobile.ui.navigation.NavTab
|
||||
|
||||
@@ -51,16 +60,27 @@ fun DashboardScreen(
|
||||
) {
|
||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
||||
val unprocessed by viewModel.unprocessedCount.collectAsStateWithLifecycle()
|
||||
val syncStatus by syncViewModel.syncStatus.collectAsStateWithLifecycle()
|
||||
// Mode local : rien n'est poussé vers le serveur, la carte sync est inutile.
|
||||
val isLocal = connectionStatus == ServerConnectionStatus.Local
|
||||
val showSyncCard = !isLocal && (syncStatus.syncing || syncStatus.pending > 0 || syncStatus.failed > 0)
|
||||
|
||||
// Tirer-pour-actualiser = revérifier le serveur (review + file sont déjà
|
||||
// temps réel via les flows, il n'y a rien d'autre à recharger ici).
|
||||
var userRefresh by rememberSaveable { mutableStateOf(false) }
|
||||
val isRefreshing = userRefresh && connectionStatus == ServerConnectionStatus.Checking
|
||||
LaunchedEffect(connectionStatus) {
|
||||
if (connectionStatus != ServerConnectionStatus.Checking) userRefresh = false
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.dashboard)) },
|
||||
actions = {
|
||||
SyncStatusAction(syncViewModel = syncViewModel)
|
||||
ServerStatusBadge(
|
||||
status = connectionStatus,
|
||||
onClick = connectionStatusViewModel::checkNow,
|
||||
HeaderStatusAction(
|
||||
syncViewModel = syncViewModel,
|
||||
connectionStatusViewModel = connectionStatusViewModel,
|
||||
)
|
||||
},
|
||||
)
|
||||
@@ -81,76 +101,131 @@ fun DashboardScreen(
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
val pullState = rememberPullToRefreshState()
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
.pullToRefresh(
|
||||
state = pullState,
|
||||
// Mode local : rien à revérifier — geste désactivé, sinon
|
||||
// l'indicateur resterait coincé (jamais de cycle vrai→faux).
|
||||
enabled = !isLocal,
|
||||
isRefreshing = isRefreshing,
|
||||
onRefresh = {
|
||||
userRefresh = true
|
||||
connectionStatusViewModel.checkNow()
|
||||
},
|
||||
),
|
||||
) {
|
||||
if (unprocessed > 0) {
|
||||
ReviewCard(
|
||||
count = unprocessed,
|
||||
onClick = onOpenReview,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
} else {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = 16.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.CheckCircle,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(48.dp),
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.dashboard_all_processed),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(top = 12.dp),
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
if (unprocessed > 0) {
|
||||
ReviewCtaCard(
|
||||
count = unprocessed,
|
||||
onClick = onOpenReview,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
if (showSyncCard) {
|
||||
SyncSummaryCard(
|
||||
status = syncStatus,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
if (unprocessed == 0 && !showSyncCard) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = 16.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.CheckCircle,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(48.dp),
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.dashboard_all_processed),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(top = 12.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
PullToRefreshDefaults.Indicator(
|
||||
state = pullState,
|
||||
isRefreshing = isRefreshing,
|
||||
modifier = Modifier.align(Alignment.TopCenter),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Résumé de la file de synchro (état déjà exposé par [SyncViewModel]) :
|
||||
* marche en cours, opérations en attente, échecs — sans nouveau ViewModel.
|
||||
*/
|
||||
@Composable
|
||||
private fun ReviewCard(
|
||||
count: Int,
|
||||
onClick: () -> Unit,
|
||||
private fun SyncSummaryCard(
|
||||
status: SyncViewModel.SyncStatus,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Card(onClick = onClick, modifier = modifier) {
|
||||
KazierCard(modifier = modifier) {
|
||||
Row(
|
||||
modifier = Modifier.padding(20.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = stringResource(R.string.dashboard_review_title, count),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.dashboard_review_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
if (status.syncing) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(28.dp))
|
||||
} else {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Sync,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(28.dp),
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = stringResource(R.string.dashboard_sync_title),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
if (status.syncing) {
|
||||
Text(
|
||||
text = stringResource(R.string.sync_syncing),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
if (status.pending > 0) {
|
||||
Text(
|
||||
text = stringResource(R.string.sync_pending_count, status.pending),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
if (status.failed > 0) {
|
||||
Text(
|
||||
text = stringResource(R.string.sync_summary_failed, status.failed),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+106
-113
@@ -18,7 +18,6 @@ import androidx.compose.foundation.pager.HorizontalPager
|
||||
import androidx.compose.foundation.pager.rememberPagerState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
@@ -29,12 +28,12 @@ import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.DocumentScanner
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.FloatingActionButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
@@ -70,7 +69,6 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.core.view.WindowCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.core.view.WindowInsetsControllerCompat
|
||||
@@ -86,14 +84,17 @@ import com.kazier.mobile.features.ocr.OcrViewModel
|
||||
import com.kazier.mobile.features.saf.FileDeleter
|
||||
import com.kazier.mobile.features.sync.SyncViewModel
|
||||
import com.kazier.mobile.ui.components.DeleteConfirmDialog
|
||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
||||
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||
import com.kazier.mobile.ui.components.KazierCard
|
||||
import com.kazier.mobile.ui.components.categoryValue
|
||||
import com.kazier.mobile.ui.components.formatFileSize
|
||||
import com.kazier.mobile.ui.document.content.DocumentContentViewer
|
||||
import com.kazier.mobile.ui.document.content.ImageViewer
|
||||
import com.kazier.mobile.ui.document.content.PdfFocusViewer
|
||||
import com.kazier.mobile.ui.document.content.TextFocusViewer
|
||||
import com.kazier.mobile.ui.document.content.ZoomableContent
|
||||
import com.kazier.mobile.ui.theme.PillShape
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import java.time.Instant
|
||||
import java.time.ZoneId
|
||||
@@ -123,7 +124,6 @@ fun DocumentViewerScreen(
|
||||
val documents by viewModel.documents.collectAsStateWithLifecycle()
|
||||
val viewerState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
val ocrState by ocrViewModel.uiState.collectAsStateWithLifecycle()
|
||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
||||
val pagerState = rememberPagerState(pageCount = { documents.size })
|
||||
|
||||
// M30 : survit à la rotation (`rememberSaveable`) — `savedPage` mémorise
|
||||
@@ -197,7 +197,7 @@ fun DocumentViewerScreen(
|
||||
}
|
||||
|
||||
// Confirmation avant suppression d'un document déjà traité.
|
||||
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||
var pendingDeleteMode by rememberSaveable { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
var fullscreen by rememberSaveable { mutableStateOf(false) }
|
||||
@@ -252,10 +252,9 @@ fun DocumentViewerScreen(
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
SyncStatusAction(syncViewModel = syncViewModel)
|
||||
ServerStatusBadge(
|
||||
status = connectionStatus,
|
||||
onClick = connectionStatusViewModel::checkNow,
|
||||
HeaderStatusAction(
|
||||
syncViewModel = syncViewModel,
|
||||
connectionStatusViewModel = connectionStatusViewModel,
|
||||
)
|
||||
},
|
||||
)
|
||||
@@ -276,21 +275,33 @@ fun DocumentViewerScreen(
|
||||
.fillMaxSize()
|
||||
.padding(padding),
|
||||
) {
|
||||
HorizontalPager(
|
||||
state = pagerState,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f),
|
||||
) { page ->
|
||||
val file = documents.getOrNull(page)
|
||||
if (file != null) {
|
||||
DocumentViewerPage(
|
||||
file = file,
|
||||
onOpenExternalFailed = onOpenExternalFailed,
|
||||
onEnterFullscreen = file.canFocus()
|
||||
.takeIf { it }
|
||||
?.let { { fullscreen = true } },
|
||||
)
|
||||
if (documents.isEmpty()) {
|
||||
// Chargement initial : le pager serait vide sans repère.
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
} else {
|
||||
HorizontalPager(
|
||||
state = pagerState,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f),
|
||||
) { page ->
|
||||
val file = documents.getOrNull(page)
|
||||
if (file != null) {
|
||||
DocumentViewerPage(
|
||||
file = file,
|
||||
onOpenExternalFailed = onOpenExternalFailed,
|
||||
onEnterFullscreen = file.canFocus()
|
||||
.takeIf { it }
|
||||
?.let { { fullscreen = true } },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Barre d'action fixe pilotée par le document affiché : garder
|
||||
@@ -388,7 +399,8 @@ private fun FocusDocumentReader(
|
||||
|
||||
/**
|
||||
* Cadre commun du mode focus : fond noir plein écran, un tap (l'indicatrice de
|
||||
* position est optionnelle) quitte le mode.
|
||||
* position est optionnelle) quitte le mode. Un hint discret « toucher pour
|
||||
* quitter » s'affiche 3 s à l'entrée pour lever l'ambiguïté tap / pinch.
|
||||
*/
|
||||
@Composable
|
||||
private fun FocusScaffold(
|
||||
@@ -398,6 +410,11 @@ private fun FocusScaffold(
|
||||
position: String? = null,
|
||||
content: @Composable () -> Unit,
|
||||
) {
|
||||
var showHint by remember(file.resourceId) { mutableStateOf(true) }
|
||||
LaunchedEffect(file.resourceId) {
|
||||
delay(3_000)
|
||||
showHint = false
|
||||
}
|
||||
Box(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
@@ -407,12 +424,28 @@ private fun FocusScaffold(
|
||||
},
|
||||
) {
|
||||
content()
|
||||
if (showHint) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopCenter)
|
||||
.padding(top = 16.dp),
|
||||
shape = PillShape,
|
||||
color = MaterialTheme.colorScheme.inverseSurface.copy(alpha = 0.85f),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.focus_tap_to_exit),
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.inverseOnSurface,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (position != null) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomCenter)
|
||||
.padding(bottom = 16.dp),
|
||||
shape = RoundedCornerShape(percent = 50),
|
||||
shape = PillShape,
|
||||
color = MaterialTheme.colorScheme.inverseSurface.copy(alpha = 0.85f),
|
||||
) {
|
||||
Text(
|
||||
@@ -549,14 +582,11 @@ private fun DocumentViewerPage(
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
|
||||
) {
|
||||
KazierCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp)) {
|
||||
MetadataRow(stringResource(R.string.document_size), formatSize(file.size))
|
||||
MetadataRow(stringResource(R.string.document_size), formatFileSize(file.size))
|
||||
MetadataRow(stringResource(R.string.document_type), fileTypeLabel(file))
|
||||
MetadataRow(stringResource(R.string.document_added_at), formatDateTime(file.addedAt))
|
||||
file.lastModified?.let { lastModified ->
|
||||
@@ -599,7 +629,7 @@ private fun DocumentActionBar(
|
||||
) {
|
||||
if (pendingReview) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(percent = 50),
|
||||
shape = PillShape,
|
||||
color = MaterialTheme.colorScheme.secondaryContainer,
|
||||
) {
|
||||
Text(
|
||||
@@ -610,7 +640,10 @@ private fun DocumentActionBar(
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(48.dp)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterHorizontally),
|
||||
) {
|
||||
DocumentActionButton(
|
||||
icon = Icons.Filled.Close,
|
||||
contentDescription = stringResource(R.string.review_delete),
|
||||
@@ -653,7 +686,7 @@ private fun DocumentActionBar(
|
||||
}
|
||||
}
|
||||
|
||||
/** Bouton « OCR » — même gabarit que le menu Supprimer (Surface 88×48). */
|
||||
/** Bouton « OCR » M3 — gabarit adaptatif (plus de Surface 88×48 fixe). */
|
||||
@Composable
|
||||
private fun DocumentOcrButton(
|
||||
label: Int,
|
||||
@@ -661,37 +694,22 @@ private fun DocumentOcrButton(
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val tint = if (enabled) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant
|
||||
|
||||
Surface(
|
||||
onClick = { if (enabled) onClick() },
|
||||
val labelText = stringResource(label)
|
||||
FilledTonalButton(
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = if (enabled) MaterialTheme.colorScheme.primaryContainer
|
||||
else MaterialTheme.colorScheme.surfaceVariant,
|
||||
modifier = modifier,
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.size(width = 88.dp, height = 48.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.DocumentScanner,
|
||||
contentDescription = null,
|
||||
tint = tint,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Text(
|
||||
text = stringResource(label),
|
||||
color = tint,
|
||||
fontSize = 11.sp,
|
||||
maxLines = 1,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
}
|
||||
}
|
||||
Icon(
|
||||
imageVector = Icons.Filled.DocumentScanner,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.size(ButtonDefaults.IconSpacing))
|
||||
Text(
|
||||
text = labelText,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -815,44 +833,33 @@ private fun DocumentDeleteMenu(
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val modes = deleteModesFor(file)
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
val tint = if (enabled) MaterialTheme.colorScheme.error
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant
|
||||
var expanded by rememberSaveable { mutableStateOf(false) }
|
||||
val deleteLabel = stringResource(R.string.delete)
|
||||
|
||||
Box(modifier = modifier) {
|
||||
Surface(
|
||||
onClick = { if (enabled) expanded = true },
|
||||
FilledTonalButton(
|
||||
onClick = { expanded = true },
|
||||
enabled = enabled,
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = if (enabled) MaterialTheme.colorScheme.errorContainer
|
||||
else MaterialTheme.colorScheme.surfaceVariant,
|
||||
colors = ButtonDefaults.filledTonalButtonColors(
|
||||
containerColor = MaterialTheme.colorScheme.errorContainer,
|
||||
contentColor = MaterialTheme.colorScheme.onErrorContainer,
|
||||
),
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.size(width = 88.dp, height = 48.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Delete,
|
||||
contentDescription = null,
|
||||
tint = tint,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.delete),
|
||||
color = tint,
|
||||
fontSize = 11.sp,
|
||||
maxLines = 1,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
Icon(
|
||||
imageVector = Icons.Filled.ArrowDropDown,
|
||||
contentDescription = null,
|
||||
tint = tint,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Delete,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
Spacer(Modifier.size(ButtonDefaults.IconSpacing))
|
||||
Text(
|
||||
text = deleteLabel,
|
||||
maxLines = 1,
|
||||
)
|
||||
Icon(
|
||||
imageVector = Icons.Filled.ArrowDropDown,
|
||||
contentDescription = deleteLabel,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
}
|
||||
|
||||
DropdownMenu(
|
||||
@@ -964,17 +971,3 @@ private fun formatDateTime(millis: Long): String {
|
||||
val time = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(locale).format(dateTime)
|
||||
return "$day $time"
|
||||
}
|
||||
|
||||
/** Miroir de `formatSize` (app/index.tsx). */
|
||||
@Composable
|
||||
private fun formatSize(bytes: Long): String {
|
||||
if (bytes < 1_024) {
|
||||
return "$bytes ${stringResource(R.string.unit_bytes)}"
|
||||
}
|
||||
if (bytes < 1_024 * 1_024) {
|
||||
val kb = bytes / 1_024f
|
||||
return String.format(Locale.getDefault(), "%.1f %s", kb, stringResource(R.string.unit_kilobytes))
|
||||
}
|
||||
val mb = bytes / (1_024f * 1_024f)
|
||||
return String.format(Locale.getDefault(), "%.1f %s", mb, stringResource(R.string.unit_megabytes))
|
||||
}
|
||||
+41
-50
@@ -2,6 +2,7 @@ package com.kazier.mobile.ui.folderdetail
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -20,14 +21,12 @@ import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.CreateNewFolder
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
@@ -44,6 +43,7 @@ import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -58,11 +58,12 @@ import com.kazier.mobile.ui.components.FilePendingReviewBadge
|
||||
import com.kazier.mobile.ui.components.FileSyncStatusIcon
|
||||
import com.kazier.mobile.ui.components.FileThumbnail
|
||||
import com.kazier.mobile.ui.components.FolderNameDialog
|
||||
import com.kazier.mobile.ui.components.KazierCard
|
||||
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||
import com.kazier.mobile.ui.components.MoveFolderPickerDialog
|
||||
import com.kazier.mobile.ui.components.SelectionState
|
||||
import com.kazier.mobile.ui.components.SelectionStatusIcon
|
||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
||||
import com.kazier.mobile.ui.components.formatFileSize
|
||||
import com.kazier.mobile.ui.components.rememberSelectionState
|
||||
import com.kazier.mobile.features.saf.FileDeleter
|
||||
import com.kazier.mobile.ui.components.DeleteConfirmDialog
|
||||
@@ -74,7 +75,6 @@ import com.kazier.mobile.ui.auth.AuthState
|
||||
import com.kazier.mobile.ui.auth.AuthViewModel
|
||||
import com.kazier.mobile.ui.share.ShareBottomSheet
|
||||
import com.kazier.mobile.ui.share.ShareViewModel
|
||||
import java.util.Locale
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
@@ -92,7 +92,6 @@ fun FolderDetailScreen(
|
||||
) {
|
||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
||||
val shareState by shareViewModel.uiState.collectAsStateWithLifecycle()
|
||||
val selection = rememberSelectionState()
|
||||
var showCreateDialog by rememberSaveable { mutableStateOf(false) }
|
||||
@@ -101,10 +100,10 @@ fun FolderDetailScreen(
|
||||
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
||||
var showShareSheet by rememberSaveable { mutableStateOf(false) }
|
||||
var showMoreMenu by rememberSaveable { mutableStateOf(false) }
|
||||
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||
var pendingDeleteReview by remember { mutableStateOf<DeleteReview?>(null) }
|
||||
var pendingDeleteMode by rememberSaveable { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||
var pendingDeleteReview by rememberSaveable { mutableStateOf<DeleteReview?>(null) }
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
val deletedLabel = stringResource(R.string.delete)
|
||||
val deletedLabel = stringResource(R.string.delete_success)
|
||||
|
||||
// M33 : le gate `canShare` dépend du token — recalculé au login/logout.
|
||||
LaunchedEffect(authState) {
|
||||
@@ -187,10 +186,9 @@ fun FolderDetailScreen(
|
||||
contentDescription = stringResource(R.string.create_folder),
|
||||
)
|
||||
}
|
||||
SyncStatusAction(syncViewModel = syncViewModel)
|
||||
ServerStatusBadge(
|
||||
status = connectionStatus,
|
||||
onClick = connectionStatusViewModel::checkNow,
|
||||
HeaderStatusAction(
|
||||
syncViewModel = syncViewModel,
|
||||
connectionStatusViewModel = connectionStatusViewModel,
|
||||
)
|
||||
Box {
|
||||
IconButton(onClick = { showMoreMenu = true }) {
|
||||
@@ -364,6 +362,24 @@ private fun FolderDetailContent(
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
if (isRefreshing) {
|
||||
item(key = "refreshing") {
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
}
|
||||
if (error != null) {
|
||||
item(key = "error") {
|
||||
Text(
|
||||
text = error,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
items(subFolders, key = { it.resourceId }) { folder ->
|
||||
FolderRow(folder, onClick = { onOpenFolder(folder.resourceId) })
|
||||
}
|
||||
@@ -389,28 +405,19 @@ private fun FolderDetailContent(
|
||||
}
|
||||
}
|
||||
}
|
||||
if (error != null) {
|
||||
item(key = "error") {
|
||||
Text(
|
||||
text = error,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FolderRow(folder: FolderEntity, onClick: () -> Unit) {
|
||||
Card(
|
||||
onClick = onClick,
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
|
||||
KazierCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(
|
||||
role = Role.Button,
|
||||
onClickLabel = folder.name,
|
||||
onClick = onClick,
|
||||
),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
@@ -421,7 +428,7 @@ private fun FolderRow(folder: FolderEntity, onClick: () -> Unit) {
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Folder,
|
||||
contentDescription = null,
|
||||
contentDescription = folder.name,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(28.dp),
|
||||
)
|
||||
@@ -450,9 +457,7 @@ private fun FileRow(
|
||||
onOpenDocument: () -> Unit,
|
||||
) {
|
||||
val selected = file.resourceId in selection.ids
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
|
||||
KazierCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.combinedClickable(
|
||||
@@ -479,7 +484,7 @@ private fun FileRow(
|
||||
maxLines = 1,
|
||||
)
|
||||
Text(
|
||||
text = formatSize(file.size),
|
||||
text = formatFileSize(file.size),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -498,17 +503,3 @@ private fun FileRow(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Miroir de `formatSize` (app/folder/[id].tsx). */
|
||||
@Composable
|
||||
private fun formatSize(bytes: Long): String {
|
||||
if (bytes < 1_024) {
|
||||
return "$bytes ${stringResource(R.string.unit_bytes)}"
|
||||
}
|
||||
if (bytes < 1_024 * 1_024) {
|
||||
val kb = bytes / 1_024f
|
||||
return String.format(Locale.getDefault(), "%.1f %s", kb, stringResource(R.string.unit_kilobytes))
|
||||
}
|
||||
val mb = bytes / (1_024f * 1_024f)
|
||||
return String.format(Locale.getDefault(), "%.1f %s", mb, stringResource(R.string.unit_megabytes))
|
||||
}
|
||||
+60
-61
@@ -5,7 +5,6 @@ import android.net.Uri
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -23,7 +22,6 @@ import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.ArrowUpward
|
||||
@@ -34,12 +32,9 @@ import androidx.compose.material.icons.filled.DocumentScanner
|
||||
import androidx.compose.material.icons.filled.EditNote
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
@@ -57,6 +52,9 @@ import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.pulltorefresh.PullToRefreshDefaults
|
||||
import androidx.compose.material3.pulltorefresh.pullToRefresh
|
||||
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -66,7 +64,6 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
@@ -74,7 +71,6 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.kazier.mobile.R
|
||||
@@ -94,11 +90,12 @@ import com.kazier.mobile.ui.components.FilePendingReviewBadge
|
||||
import com.kazier.mobile.ui.components.FileSyncStatusIcon
|
||||
import com.kazier.mobile.ui.components.FileThumbnail
|
||||
import com.kazier.mobile.ui.components.FolderNameDialog
|
||||
|
||||
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||
import com.kazier.mobile.ui.components.KazierCard
|
||||
import com.kazier.mobile.ui.components.ReviewCtaCard
|
||||
import com.kazier.mobile.ui.components.SelectionState
|
||||
import com.kazier.mobile.ui.components.SelectionStatusIcon
|
||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
||||
import com.kazier.mobile.ui.components.formatFileSize
|
||||
import com.kazier.mobile.ui.components.rememberSelectionState
|
||||
import com.kazier.mobile.ui.components.reviewDelete
|
||||
import com.kazier.mobile.ui.navigation.FloatingNavBar
|
||||
@@ -110,15 +107,16 @@ import com.kazier.mobile.ui.auth.AuthState
|
||||
import com.kazier.mobile.ui.auth.AuthViewModel
|
||||
import com.kazier.mobile.ui.share.ShareBottomSheet
|
||||
import com.kazier.mobile.ui.share.ShareViewModel
|
||||
import com.kazier.mobile.ui.theme.NavItemShape
|
||||
import com.kazier.mobile.ui.theme.NavPillShape
|
||||
import kotlinx.coroutines.delay
|
||||
import timber.log.Timber
|
||||
import java.util.Locale
|
||||
|
||||
/** Dossier cible du partage : id + nom affiché dans le sheet. */
|
||||
private data class ShareTarget(
|
||||
val resourceId: String,
|
||||
val name: String,
|
||||
)
|
||||
) : java.io.Serializable
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
@@ -128,12 +126,14 @@ fun FolderListScreen(
|
||||
onOpenDocument: (String) -> Unit,
|
||||
onBuildPdf: (List<String>) -> Unit,
|
||||
onOpenScan: () -> Unit,
|
||||
onOpenReview: () -> Unit,
|
||||
syncViewModel: SyncViewModel,
|
||||
connectionStatusViewModel: ConnectionStatusViewModel,
|
||||
authViewModel: AuthViewModel,
|
||||
viewModel: FolderListViewModel = hiltViewModel(),
|
||||
) {
|
||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
val unprocessed by viewModel.unprocessedCount.collectAsStateWithLifecycle()
|
||||
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
||||
val shareViewModel: ShareViewModel = hiltViewModel()
|
||||
val shareState by shareViewModel.uiState.collectAsStateWithLifecycle()
|
||||
@@ -145,13 +145,13 @@ fun FolderListScreen(
|
||||
var showCreateDialog by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeleteWarning by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
||||
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||
var pendingDeleteReview by remember { mutableStateOf<DeleteReview?>(null) }
|
||||
var pendingFolderIds by remember { mutableStateOf<List<String>>(emptyList()) }
|
||||
var pendingFileIds by remember { mutableStateOf<List<String>>(emptyList()) }
|
||||
var shareTarget by remember { mutableStateOf<ShareTarget?>(null) }
|
||||
var pendingDeleteMode by rememberSaveable { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||
var pendingDeleteReview by rememberSaveable { mutableStateOf<DeleteReview?>(null) }
|
||||
var pendingFolderIds by rememberSaveable { mutableStateOf<List<String>>(emptyList()) }
|
||||
var pendingFileIds by rememberSaveable { mutableStateOf<List<String>>(emptyList()) }
|
||||
var shareTarget by rememberSaveable { mutableStateOf<ShareTarget?>(null) }
|
||||
var showShareMenu by rememberSaveable { mutableStateOf(false) }
|
||||
var shareEnabled by remember { mutableStateOf(false) }
|
||||
var shareEnabled by rememberSaveable { mutableStateOf(false) }
|
||||
var showCreateMenu by rememberSaveable { mutableStateOf(false) }
|
||||
var showNoteDialog by rememberSaveable { mutableStateOf(false) }
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
@@ -203,7 +203,7 @@ fun FolderListScreen(
|
||||
|
||||
LaunchedEffect(uiState.deleteSuccess) {
|
||||
if (uiState.deleteSuccess) {
|
||||
snackbarHostState.showSnackbar(context.getString(R.string.delete))
|
||||
snackbarHostState.showSnackbar(context.getString(R.string.delete_success))
|
||||
viewModel.clearDeleteSuccess()
|
||||
}
|
||||
}
|
||||
@@ -294,14 +294,10 @@ fun FolderListScreen(
|
||||
},
|
||||
actions = {
|
||||
if (!uiState.moveMode && !selection.active) {
|
||||
SyncStatusAction(syncViewModel = syncViewModel)
|
||||
ServerStatusBadge(
|
||||
status = connectionStatus,
|
||||
onClick = connectionStatusViewModel::checkNow,
|
||||
HeaderStatusAction(
|
||||
syncViewModel = syncViewModel,
|
||||
connectionStatusViewModel = connectionStatusViewModel,
|
||||
)
|
||||
IconButton(onClick = viewModel::refresh) {
|
||||
Icon(Icons.Filled.Refresh, contentDescription = stringResource(R.string.refresh))
|
||||
}
|
||||
if (uiState.view == HomeView.FOLDERS && connectionStatus != ServerConnectionStatus.Local) {
|
||||
Box {
|
||||
IconButton(onClick = { showShareMenu = true }) {
|
||||
@@ -460,11 +456,30 @@ fun FolderListScreen(
|
||||
},
|
||||
snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
|
||||
) { padding ->
|
||||
Column(
|
||||
// Mode local : le refresh serveur est no-op — geste désactivé, sinon
|
||||
// l'indicateur resterait coincé (jamais de cycle vrai→faux).
|
||||
val pullState = rememberPullToRefreshState()
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.padding(padding)
|
||||
.fillMaxSize(),
|
||||
.fillMaxSize()
|
||||
.pullToRefresh(
|
||||
state = pullState,
|
||||
enabled = connectionStatus != ServerConnectionStatus.Local,
|
||||
isRefreshing = uiState.isRefreshing,
|
||||
onRefresh = viewModel::refresh,
|
||||
),
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
if (unprocessed > 0 && !selection.active && !uiState.moveMode) {
|
||||
ReviewCtaCard(
|
||||
count = unprocessed,
|
||||
onClick = onOpenReview,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 16.dp, end = 16.dp, top = 12.dp),
|
||||
)
|
||||
}
|
||||
if (!selection.active) {
|
||||
HomeViewSelector(
|
||||
selected = uiState.view,
|
||||
@@ -495,6 +510,12 @@ fun FolderListScreen(
|
||||
onOpenDocument = onOpenDocument,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
PullToRefreshDefaults.Indicator(
|
||||
state = pullState,
|
||||
isRefreshing = uiState.isRefreshing,
|
||||
modifier = Modifier.align(Alignment.TopCenter),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -595,7 +616,7 @@ private fun HomeViewSelector(
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(30.dp),
|
||||
shape = NavPillShape,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
shadowElevation = 8.dp,
|
||||
modifier = Modifier
|
||||
@@ -642,7 +663,7 @@ private fun ViewSegment(
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
shape = NavItemShape,
|
||||
color = if (selected) MaterialTheme.colorScheme.primaryContainer
|
||||
else MaterialTheme.colorScheme.surface,
|
||||
modifier = modifier,
|
||||
@@ -656,14 +677,14 @@ private fun ViewSegment(
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
contentDescription = label,
|
||||
tint = tint,
|
||||
modifier = Modifier.size(22.dp),
|
||||
)
|
||||
Text(
|
||||
text = label,
|
||||
color = tint,
|
||||
fontSize = 11.sp,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium,
|
||||
@@ -866,7 +887,7 @@ private fun FolderBrowserContent(
|
||||
.fillMaxWidth()
|
||||
.padding(top = 8.dp, bottom = 4.dp),
|
||||
) {
|
||||
Icon(Icons.Filled.CreateNewFolder, contentDescription = null)
|
||||
Icon(Icons.Filled.CreateNewFolder, contentDescription = stringResource(R.string.create_folder))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(stringResource(R.string.create_folder))
|
||||
}
|
||||
@@ -1006,9 +1027,7 @@ private fun FolderRow(
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val selected = folder.resourceId in selection.ids
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
|
||||
KazierCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(bottom = 8.dp)
|
||||
@@ -1030,7 +1049,7 @@ private fun FolderRow(
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Folder,
|
||||
contentDescription = null,
|
||||
contentDescription = folder.name,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(28.dp),
|
||||
)
|
||||
@@ -1064,11 +1083,7 @@ private fun FileCard(
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val selected = file.resourceId in selection.ids
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = Color(0xFFF7F8FA)),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
|
||||
border = BorderStroke(1.dp, Color(0xFFEAEAEA)),
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
KazierCard(
|
||||
modifier = modifier.combinedClickable(
|
||||
onClick = {
|
||||
if (selection.active) selection.toggle(file.resourceId) else onClick()
|
||||
@@ -1104,7 +1119,7 @@ private fun FileCard(
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
text = formatSize(file.size),
|
||||
text = formatFileSize(file.size),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -1121,9 +1136,7 @@ private fun BrowseFileRow(
|
||||
onOpenDocument: () -> Unit,
|
||||
) {
|
||||
val selected = file.resourceId in selection.ids
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 1.dp),
|
||||
KazierCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(bottom = 6.dp)
|
||||
@@ -1153,7 +1166,7 @@ private fun BrowseFileRow(
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
Text(
|
||||
text = formatSize(file.size),
|
||||
text = formatFileSize(file.size),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -1173,20 +1186,6 @@ private fun BrowseFileRow(
|
||||
}
|
||||
}
|
||||
|
||||
/** Miroir de `formatSize` (app/index.tsx). */
|
||||
@Composable
|
||||
private fun formatSize(bytes: Long): String {
|
||||
if (bytes < 1_024) {
|
||||
return "$bytes ${stringResource(R.string.unit_bytes)}"
|
||||
}
|
||||
if (bytes < 1_024 * 1_024) {
|
||||
val kb = bytes / 1_024f
|
||||
return String.format(Locale.getDefault(), "%.1f %s", kb, stringResource(R.string.unit_kilobytes))
|
||||
}
|
||||
val mb = bytes / (1_024f * 1_024f)
|
||||
return String.format(Locale.getDefault(), "%.1f %s", mb, stringResource(R.string.unit_megabytes))
|
||||
}
|
||||
|
||||
/** Création d'une note : titre requis, corps de texte libre. */
|
||||
@Composable
|
||||
private fun NoteDialog(
|
||||
|
||||
@@ -23,11 +23,13 @@ import com.kazier.mobile.features.saf.SafFolderCreator
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import timber.log.Timber
|
||||
@@ -60,6 +62,10 @@ class FolderListViewModel @Inject constructor(
|
||||
private val _defaultRootId = MutableStateFlow(defaultRootStore.get())
|
||||
val defaultRootId: StateFlow<String?> = _defaultRootId.asStateFlow()
|
||||
|
||||
/** Documents locaux restant à traiter — CTA review persistant (même source que le dashboard). */
|
||||
val unprocessedCount: StateFlow<Int> = fileRepository.observeUnprocessedCount()
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initialValue = 0)
|
||||
|
||||
/** Dossier courant de l'explorateur Dossiers (null = racine par défaut). */
|
||||
private val _browseFolderId = MutableStateFlow<String?>(null)
|
||||
|
||||
|
||||
+148
-150
@@ -6,17 +6,20 @@ import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Dashboard
|
||||
import androidx.compose.material.icons.filled.DriveFileMove
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.MergeType
|
||||
import androidx.compose.material.icons.filled.PictureAsPdf
|
||||
import androidx.compose.material.icons.filled.Save
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
@@ -38,10 +41,12 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.ui.components.DeleteDropdownButton
|
||||
import com.kazier.mobile.features.saf.FileDeleter
|
||||
import com.kazier.mobile.ui.components.DeleteDropdownButton
|
||||
import com.kazier.mobile.ui.theme.KazierDimens
|
||||
import com.kazier.mobile.ui.theme.NavItemShape
|
||||
import com.kazier.mobile.ui.theme.NavPillShape
|
||||
|
||||
enum class NavTab(val route: String) {
|
||||
FILES(Routes.FILES),
|
||||
@@ -64,11 +69,11 @@ private val TAB_ITEMS = listOf(
|
||||
TabItem(NavTab.SETTINGS, Icons.Filled.Settings, Icons.Outlined.Settings, R.string.nav_settings),
|
||||
)
|
||||
|
||||
/** Conteneur pill commun aux 4 barres flottantes (nav + sélection + déplacement). */
|
||||
@Composable
|
||||
fun FloatingNavBar(
|
||||
selected: NavTab,
|
||||
onSelect: (NavTab) -> Unit,
|
||||
private fun FloatingPillContainer(
|
||||
modifier: Modifier = Modifier,
|
||||
content: @Composable RowScope.() -> Unit,
|
||||
) {
|
||||
Box(
|
||||
modifier = modifier
|
||||
@@ -77,53 +82,64 @@ fun FloatingNavBar(
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(30.dp),
|
||||
shape = NavPillShape,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
shadowElevation = 8.dp,
|
||||
modifier = Modifier.widthIn(max = 400.dp).fillMaxWidth(),
|
||||
shadowElevation = KazierDimens.NavElevation,
|
||||
modifier = Modifier.widthIn(max = KazierDimens.ListMaxWidth).fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(vertical = 8.dp, horizontal = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TAB_ITEMS.forEach { item ->
|
||||
val isActive = item.tab == selected
|
||||
val icon = if (isActive) item.filled else item.outlined
|
||||
val tint = if (isActive) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Surface(
|
||||
onClick = { onSelect(item.tab) },
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
color = if (isActive) MaterialTheme.colorScheme.primaryContainer
|
||||
else MaterialTheme.colorScheme.surface,
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 6.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
tint = tint,
|
||||
modifier = Modifier.size(22.dp),
|
||||
)
|
||||
Text(
|
||||
text = stringResource(item.labelRes),
|
||||
color = tint,
|
||||
fontSize = 11.sp,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
fontWeight = if (isActive) FontWeight.Bold else FontWeight.Medium,
|
||||
modifier = Modifier.padding(top = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
@Composable
|
||||
fun FloatingNavBar(
|
||||
selected: NavTab,
|
||||
onSelect: (NavTab) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
FloatingPillContainer(modifier = modifier) {
|
||||
TAB_ITEMS.forEach { item ->
|
||||
val isActive = item.tab == selected
|
||||
val icon = if (isActive) item.filled else item.outlined
|
||||
val tint = if (isActive) MaterialTheme.colorScheme.primary
|
||||
else MaterialTheme.colorScheme.onSurfaceVariant
|
||||
val label = stringResource(item.labelRes)
|
||||
|
||||
Surface(
|
||||
onClick = { onSelect(item.tab) },
|
||||
shape = NavItemShape,
|
||||
color = if (isActive) MaterialTheme.colorScheme.primaryContainer
|
||||
else MaterialTheme.colorScheme.surface,
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 6.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = label,
|
||||
tint = tint,
|
||||
modifier = Modifier.size(22.dp),
|
||||
)
|
||||
Text(
|
||||
text = label,
|
||||
color = tint,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
fontWeight = if (isActive) FontWeight.Bold else FontWeight.Medium,
|
||||
modifier = Modifier.padding(top = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -140,44 +156,26 @@ fun SelectionNavBar(
|
||||
enabled: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Box(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 20.dp, end = 20.dp, bottom = 16.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(30.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
shadowElevation = 8.dp,
|
||||
modifier = Modifier.widthIn(max = 400.dp).fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(vertical = 8.dp, horizontal = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
SelectionAction(
|
||||
label = stringResource(R.string.move_files),
|
||||
icon = Icons.Filled.DriveFileMove,
|
||||
enabled = enabled,
|
||||
onClick = onMove,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
SelectionAction(
|
||||
label = stringResource(R.string.selection_assemble),
|
||||
icon = Icons.Filled.MergeType,
|
||||
enabled = enabled,
|
||||
onClick = onBuildPdf,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
DeleteDropdownButton(
|
||||
enabled = enabled,
|
||||
onModeSelected = onDeleteModeSelected,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
FloatingPillContainer(modifier = modifier) {
|
||||
SelectionAction(
|
||||
label = stringResource(R.string.move_files),
|
||||
icon = Icons.Filled.DriveFileMove,
|
||||
enabled = enabled,
|
||||
onClick = onMove,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
SelectionAction(
|
||||
label = stringResource(R.string.selection_assemble),
|
||||
icon = Icons.Filled.MergeType,
|
||||
enabled = enabled,
|
||||
onClick = onBuildPdf,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
DeleteDropdownButton(
|
||||
enabled = enabled,
|
||||
onModeSelected = onDeleteModeSelected,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,37 +188,54 @@ fun FolderSelectionNavBar(
|
||||
deleteEnabled: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Box(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 20.dp, end = 20.dp, bottom = 16.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(30.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
shadowElevation = 8.dp,
|
||||
modifier = Modifier.widthIn(max = 400.dp).fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(vertical = 8.dp, horizontal = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
SelectionAction(
|
||||
label = stringResource(R.string.share_action),
|
||||
icon = Icons.Filled.Share,
|
||||
enabled = shareEnabled,
|
||||
onClick = onShare,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
DeleteDropdownButton(
|
||||
enabled = deleteEnabled,
|
||||
onModeSelected = onDeleteModeSelected,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
FloatingPillContainer(modifier = modifier) {
|
||||
SelectionAction(
|
||||
label = stringResource(R.string.share_action),
|
||||
icon = Icons.Filled.Share,
|
||||
enabled = shareEnabled,
|
||||
onClick = onShare,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
DeleteDropdownButton(
|
||||
enabled = deleteEnabled,
|
||||
onModeSelected = onDeleteModeSelected,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Barre d'actions de l'étape « pages scannées » : même pilule flottante que le reste de l'app. */
|
||||
@Composable
|
||||
fun ScanSessionNavBar(
|
||||
onAddPage: () -> Unit,
|
||||
onExportPdf: () -> Unit,
|
||||
onExport: () -> Unit,
|
||||
canExport: Boolean,
|
||||
actionsEnabled: Boolean = true,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
FloatingPillContainer(modifier = modifier) {
|
||||
SelectionAction(
|
||||
label = stringResource(R.string.scan_add_page),
|
||||
icon = Icons.Filled.Add,
|
||||
enabled = actionsEnabled,
|
||||
onClick = onAddPage,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
SelectionAction(
|
||||
label = stringResource(R.string.scan_export_pdf),
|
||||
icon = Icons.Filled.PictureAsPdf,
|
||||
enabled = actionsEnabled && canExport,
|
||||
onClick = onExportPdf,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
SelectionAction(
|
||||
label = stringResource(R.string.scan_export),
|
||||
icon = Icons.Filled.Save,
|
||||
enabled = actionsEnabled && canExport,
|
||||
onClick = onExport,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,39 +246,22 @@ fun MoveTargetBar(
|
||||
onMoveHere: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Box(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 20.dp, end = 20.dp, bottom = 16.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(30.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
shadowElevation = 8.dp,
|
||||
modifier = Modifier.widthIn(max = 400.dp).fillMaxWidth(),
|
||||
FloatingPillContainer(modifier = modifier) {
|
||||
val label = stringResource(R.string.move_here_count, fileCount)
|
||||
Button(
|
||||
onClick = onMoveHere,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.heightIn(min = 52.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Button(
|
||||
onClick = onMoveHere,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.heightIn(min = 52.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.DriveFileMove,
|
||||
contentDescription = null,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.move_here_count, fileCount),
|
||||
modifier = Modifier.padding(start = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
Icon(
|
||||
imageVector = Icons.Filled.DriveFileMove,
|
||||
contentDescription = label,
|
||||
)
|
||||
Text(
|
||||
text = label,
|
||||
modifier = Modifier.padding(start = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -281,7 +279,7 @@ private fun SelectionAction(
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
shape = NavItemShape,
|
||||
color = if (enabled) MaterialTheme.colorScheme.primaryContainer
|
||||
else MaterialTheme.colorScheme.surfaceVariant,
|
||||
modifier = modifier,
|
||||
@@ -295,14 +293,14 @@ private fun SelectionAction(
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Icon(
|
||||
imageVector = icon,
|
||||
contentDescription = null,
|
||||
contentDescription = label,
|
||||
tint = tint,
|
||||
modifier = Modifier.size(22.dp),
|
||||
)
|
||||
Text(
|
||||
text = label,
|
||||
color = tint,
|
||||
fontSize = 11.sp,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
fontWeight = FontWeight.Bold,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.kazier.mobile.ui.navigation
|
||||
|
||||
import androidx.compose.animation.EnterTransition
|
||||
import androidx.compose.animation.ExitTransition
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.runtime.Composable
|
||||
@@ -103,7 +105,12 @@ fun NavGraph(
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
NavHost(
|
||||
navController = navController,
|
||||
startDestination = Routes.FILES,
|
||||
startDestination = Routes.DASHBOARD,
|
||||
// Pas de transition animée entre les vues : changement instantané.
|
||||
enterTransition = { EnterTransition.None },
|
||||
exitTransition = { ExitTransition.None },
|
||||
popEnterTransition = { EnterTransition.None },
|
||||
popExitTransition = { ExitTransition.None },
|
||||
) {
|
||||
composable(Routes.FILES) {
|
||||
FolderListScreen(
|
||||
@@ -112,6 +119,7 @@ fun NavGraph(
|
||||
onOpenDocument = { id -> navController.navigate(Routes.document(id)) },
|
||||
onBuildPdf = { ids -> navController.navigate(Routes.pdfBuilder(ids)) },
|
||||
onOpenScan = { navController.navigate(Routes.SCAN) },
|
||||
onOpenReview = { navController.navigate(Routes.REVIEW) },
|
||||
syncViewModel = syncViewModel,
|
||||
connectionStatusViewModel = connectionStatusViewModel,
|
||||
authViewModel = authViewModel,
|
||||
|
||||
+72
-50
@@ -18,29 +18,29 @@ import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.MergeType
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material.icons.filled.TextSnippet
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.SnackbarDuration
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.SnackbarResult
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
@@ -57,6 +57,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
@@ -68,11 +69,13 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.ui.components.FileCategoryIcon
|
||||
import com.kazier.mobile.ui.components.KazierCard
|
||||
import com.kazier.mobile.ui.components.VerticalActionButton
|
||||
import com.kazier.mobile.ui.components.formatFileSize
|
||||
import com.kazier.mobile.ui.document.content.DocumentContentViewer
|
||||
import kotlinx.coroutines.launch
|
||||
import java.time.LocalDate
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
@@ -111,8 +114,22 @@ fun PdfBuilderScreen(
|
||||
LaunchedEffect(isReady) {
|
||||
if (isReady) showNameDialog = true
|
||||
}
|
||||
// Plus d'auto-navigation à la sauvegarde : un Snackbar « PDF créé / Voir »
|
||||
// laisse l'utilisateur dans le panier ; l'ouverture est explicite.
|
||||
// `savedAnnouncedFor` (UI seule) évite le re-snackbar à la rotation.
|
||||
val savedLabel = stringResource(R.string.pdf_builder_saved)
|
||||
val viewLabel = stringResource(R.string.pdf_builder_view)
|
||||
var savedAnnouncedFor by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
LaunchedEffect(savedResourceId) {
|
||||
if (savedResourceId != null) onOpenDocument(savedResourceId)
|
||||
if (savedResourceId != null && savedAnnouncedFor != savedResourceId) {
|
||||
savedAnnouncedFor = savedResourceId
|
||||
val result = snackbarHostState.showSnackbar(
|
||||
message = savedLabel,
|
||||
actionLabel = viewLabel,
|
||||
duration = SnackbarDuration.Long,
|
||||
)
|
||||
if (result == SnackbarResult.ActionPerformed) onOpenDocument(savedResourceId)
|
||||
}
|
||||
}
|
||||
LaunchedEffect(failureMessage) {
|
||||
if (failureMessage != null) {
|
||||
@@ -257,7 +274,12 @@ private fun SelectFilesSheet(
|
||||
// `remember(files)`, chaque update Room recréait la sélection et effaçait
|
||||
// les cases cochées en cours.
|
||||
var selected by remember(existingIds) { mutableStateOf(existingIds.toMutableSet()) }
|
||||
var searchQuery by rememberSaveable { mutableStateOf("") }
|
||||
val sheetState = rememberModalBottomSheetState()
|
||||
val visibleFiles = remember(files, searchQuery) {
|
||||
if (searchQuery.isBlank()) files
|
||||
else files.filter { it.name.contains(searchQuery, ignoreCase = true) }
|
||||
}
|
||||
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = onDismiss,
|
||||
@@ -269,18 +291,33 @@ private fun SelectFilesSheet(
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.padding(horizontal = 16.dp),
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = searchQuery,
|
||||
onValueChange = { searchQuery = it },
|
||||
leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
|
||||
placeholder = { Text(stringResource(R.string.pdf_builder_search_files)) },
|
||||
singleLine = true,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
LazyColumn(
|
||||
contentPadding = PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
items(files, key = { it.resourceId }) { file ->
|
||||
items(visibleFiles, key = { it.resourceId }) { file ->
|
||||
val checked = file.resourceId in selected
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
if (file.resourceId in selected) selected.remove(file.resourceId)
|
||||
else selected.add(file.resourceId)
|
||||
}
|
||||
.clickable(
|
||||
role = Role.Checkbox,
|
||||
onClickLabel = file.name,
|
||||
onClick = {
|
||||
if (checked) selected.remove(file.resourceId)
|
||||
else selected.add(file.resourceId)
|
||||
},
|
||||
)
|
||||
.padding(vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
@@ -294,19 +331,17 @@ private fun SelectFilesSheet(
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
text = formatSize(file.size),
|
||||
text = formatFileSize(file.size),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Check,
|
||||
contentDescription = null,
|
||||
tint = if (file.resourceId in selected) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f)
|
||||
Checkbox(
|
||||
checked = checked,
|
||||
onCheckedChange = {
|
||||
if (checked) selected.remove(file.resourceId)
|
||||
else selected.add(file.resourceId)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -332,7 +367,7 @@ private fun NamePdfDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: (String) -> Unit,
|
||||
) {
|
||||
var name by remember { mutableStateOf(defaultName) }
|
||||
var name by rememberSaveable { mutableStateOf(defaultName) }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.pdf_builder_name_title)) },
|
||||
@@ -366,7 +401,7 @@ private fun AddNoteDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: (String) -> Unit,
|
||||
) {
|
||||
var body by remember { mutableStateOf("") }
|
||||
var body by rememberSaveable { mutableStateOf("") }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.pdf_builder_add_note)) },
|
||||
@@ -404,10 +439,7 @@ private fun BuilderItemRow(
|
||||
onPreview: (() -> Unit)?,
|
||||
) {
|
||||
val previewModifier = if (onPreview != null) Modifier.clickable(onClick = onPreview) else Modifier
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
|
||||
) {
|
||||
KazierCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -419,13 +451,13 @@ private fun BuilderItemRow(
|
||||
is PdfBuilderItem.FileItem -> FileCategoryIcon(file = item.file, size = 24.dp)
|
||||
is PdfBuilderItem.NoteItem -> Icon(
|
||||
imageVector = Icons.Filled.TextSnippet,
|
||||
contentDescription = null,
|
||||
contentDescription = stringResource(R.string.pdf_builder_note),
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(24.dp),
|
||||
)
|
||||
is PdfBuilderItem.FilePathItem -> Icon(
|
||||
imageVector = Icons.Filled.Image,
|
||||
contentDescription = null,
|
||||
contentDescription = item.file.name,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(24.dp),
|
||||
)
|
||||
@@ -450,14 +482,14 @@ private fun BuilderItemRow(
|
||||
is PdfBuilderItem.FileItem -> if (isFailed) {
|
||||
stringResource(R.string.pdf_builder_unreadable)
|
||||
} else {
|
||||
formatSize(item.file.size)
|
||||
formatFileSize(item.file.size)
|
||||
}
|
||||
|
||||
is PdfBuilderItem.NoteItem -> item.body
|
||||
.replace('\n', ' ')
|
||||
.take(80)
|
||||
|
||||
is PdfBuilderItem.FilePathItem -> formatSize(item.file.length())
|
||||
is PdfBuilderItem.FilePathItem -> formatFileSize(item.file.length())
|
||||
},
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = if (isFailed) MaterialTheme.colorScheme.error
|
||||
@@ -547,24 +579,22 @@ private fun BuilderActions(
|
||||
) {
|
||||
Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(
|
||||
VerticalActionButton(
|
||||
icon = Icons.Filled.Add,
|
||||
label = stringResource(R.string.pdf_builder_add_files),
|
||||
onClick = onAddFile,
|
||||
enabled = !building,
|
||||
outlined = true,
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Icon(Icons.Filled.Add, contentDescription = null)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(stringResource(R.string.pdf_builder_add_files))
|
||||
}
|
||||
OutlinedButton(
|
||||
)
|
||||
VerticalActionButton(
|
||||
icon = Icons.Filled.TextSnippet,
|
||||
label = stringResource(R.string.pdf_builder_add_note),
|
||||
onClick = onAddNote,
|
||||
enabled = !building,
|
||||
outlined = true,
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Icon(Icons.Filled.TextSnippet, contentDescription = null)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(stringResource(R.string.pdf_builder_add_note))
|
||||
}
|
||||
)
|
||||
}
|
||||
Button(
|
||||
onClick = onAssemble,
|
||||
@@ -580,11 +610,3 @@ private fun BuilderActions(
|
||||
|
||||
private val DEFAULT_DATE_FORMAT: DateTimeFormatter =
|
||||
DateTimeFormatter.ofPattern("dd-MM-yyyy")
|
||||
|
||||
private fun formatSize(bytes: Long): String {
|
||||
if (bytes < 1_024) return "$bytes o"
|
||||
if (bytes < 1_024 * 1_024) {
|
||||
return String.format(Locale.getDefault(), "%.1f ko", bytes / 1_024f)
|
||||
}
|
||||
return String.format(Locale.getDefault(), "%.1f Mo", bytes / (1_024f * 1_024f))
|
||||
}
|
||||
@@ -1,5 +1,11 @@
|
||||
package com.kazier.mobile.ui.review
|
||||
|
||||
import androidx.compose.animation.AnimatedContent
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.animation.togetherWith
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -27,7 +33,9 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.ui.components.FileCategoryIcon
|
||||
import com.kazier.mobile.ui.components.formatFileSize
|
||||
import com.kazier.mobile.ui.document.content.DocumentContentViewer
|
||||
import com.kazier.mobile.ui.theme.SheetShape
|
||||
import java.time.Instant
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
@@ -49,22 +57,40 @@ fun SwipeCardDeck(
|
||||
) {
|
||||
Box(modifier = modifier) {
|
||||
val visible = cards.take(MAX_STACK)
|
||||
val top = visible.firstOrNull()
|
||||
|
||||
visible.asReversed().forEach { file ->
|
||||
val depth = visible.indexOf(file)
|
||||
// Cartes d'arrière-plan : profondeur = distance au dessus (0 = dessus).
|
||||
visible.asReversed().forEachIndexed { reversedIndex, file ->
|
||||
val depth = visible.size - 1 - reversedIndex
|
||||
if (depth == 0) return@forEachIndexed
|
||||
key(file.resourceId) {
|
||||
if (depth == 0) {
|
||||
StackedCard(
|
||||
file = file,
|
||||
depth = depth,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Carte du dessus : transition fondu + échelle à chaque document —
|
||||
// fini la disparition brutale au garder/supprimer.
|
||||
AnimatedContent(
|
||||
targetState = top?.resourceId,
|
||||
transitionSpec = {
|
||||
(fadeIn() + scaleIn(initialScale = 0.96f)) togetherWith
|
||||
(fadeOut() + scaleOut(targetScale = 0.96f))
|
||||
},
|
||||
label = "review-top-card",
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
) { topId ->
|
||||
val file = visible.firstOrNull { it.resourceId == topId }
|
||||
if (file != null) {
|
||||
key(file.resourceId) {
|
||||
TopCard(
|
||||
file = file,
|
||||
onOpenExternalFailed = onOpenExternalFailed,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
} else {
|
||||
StackedCard(
|
||||
file = file,
|
||||
depth = depth,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -155,7 +181,7 @@ private fun ReviewCardMetaBar(file: FileEntity, modifier: Modifier = Modifier) {
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
text = "${formatSize(file.size)} • ${formatDate(file)}",
|
||||
text = "${formatFileSize(file.size)} • ${formatDate(file)}",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
@@ -163,16 +189,6 @@ private fun ReviewCardMetaBar(file: FileEntity, modifier: Modifier = Modifier) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatSize(bytes: Long): String {
|
||||
val kb = 1024.0
|
||||
val mb = kb * 1024
|
||||
return when {
|
||||
bytes >= mb -> String.format(Locale.getDefault(), "%.1f Mo", bytes / mb)
|
||||
bytes >= kb -> String.format(Locale.getDefault(), "%.1f ko", bytes / kb)
|
||||
else -> "$bytes o"
|
||||
}
|
||||
}
|
||||
|
||||
private fun formatDate(file: FileEntity): String {
|
||||
val millis = file.lastModified ?: file.addedAt
|
||||
return DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
|
||||
@@ -180,7 +196,7 @@ private fun formatDate(file: FileEntity): String {
|
||||
.format(Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDate())
|
||||
}
|
||||
|
||||
private val CardShape = RoundedCornerShape(20.dp)
|
||||
private val CardShape = SheetShape
|
||||
private const val MAX_STACK = 3
|
||||
private const val STACK_SHRINK = 0.045f
|
||||
private const val STACK_OFFSET_DP = 18f
|
||||
@@ -13,6 +13,7 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FloatingActionButton
|
||||
@@ -28,8 +29,10 @@ import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -38,14 +41,12 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
||||
import com.kazier.mobile.features.sync.SyncViewModel
|
||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
||||
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@@ -57,11 +58,10 @@ fun SwipeReviewScreen(
|
||||
viewModel: SwipeReviewViewModel = hiltViewModel(),
|
||||
) {
|
||||
val state by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
val scope = rememberCoroutineScope()
|
||||
val openExternalErrorMsg = stringResource(R.string.document_open_error)
|
||||
var confirmMarkAll by remember { androidx.compose.runtime.mutableStateOf(false) }
|
||||
var confirmMarkAll by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(state.error) {
|
||||
state.error?.let {
|
||||
@@ -91,10 +91,9 @@ fun SwipeReviewScreen(
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
SyncStatusAction(syncViewModel = syncViewModel)
|
||||
ServerStatusBadge(
|
||||
status = connectionStatus,
|
||||
onClick = connectionStatusViewModel::checkNow,
|
||||
HeaderStatusAction(
|
||||
syncViewModel = syncViewModel,
|
||||
connectionStatusViewModel = connectionStatusViewModel,
|
||||
)
|
||||
},
|
||||
)
|
||||
@@ -156,43 +155,26 @@ fun SwipeReviewScreen(
|
||||
}
|
||||
|
||||
if (confirmMarkAll) {
|
||||
Dialog(onDismissRequest = { confirmMarkAll = false }) {
|
||||
androidx.compose.material3.Surface(
|
||||
shape = MaterialTheme.shapes.medium,
|
||||
tonalElevation = 3.dp,
|
||||
) {
|
||||
Column(modifier = Modifier.padding(24.dp)) {
|
||||
Text(
|
||||
text = stringResource(R.string.review_mark_all_title),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
Text(
|
||||
text = stringResource(R.string.review_mark_all_message),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 8.dp),
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 16.dp),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
) {
|
||||
TextButton(onClick = { confirmMarkAll = false }) {
|
||||
Text(stringResource(R.string.pdf_builder_cancel))
|
||||
}
|
||||
TextButton(
|
||||
onClick = {
|
||||
confirmMarkAll = false
|
||||
viewModel.markAllProcessed()
|
||||
},
|
||||
) {
|
||||
Text(stringResource(R.string.review_mark_all))
|
||||
}
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = { confirmMarkAll = false },
|
||||
title = { Text(stringResource(R.string.review_mark_all_title)) },
|
||||
text = { Text(stringResource(R.string.review_mark_all_message)) },
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
confirmMarkAll = false
|
||||
viewModel.markAllProcessed()
|
||||
},
|
||||
) {
|
||||
Text(stringResource(R.string.review_mark_all))
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { confirmMarkAll = false }) {
|
||||
Text(stringResource(R.string.pdf_builder_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,7 +187,7 @@ private fun ReviewActions(
|
||||
) {
|
||||
Row(
|
||||
modifier = modifier,
|
||||
horizontalArrangement = Arrangement.spacedBy(48.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(24.dp, Alignment.CenterHorizontally),
|
||||
verticalAlignment = Alignment.Top,
|
||||
) {
|
||||
ReviewAction(
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
package com.kazier.mobile.ui.scan
|
||||
|
||||
import android.Manifest.permission.CAMERA
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.provider.Settings
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Scaffold
|
||||
@@ -26,6 +34,7 @@ import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -34,10 +43,12 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.app.ActivityCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.ui.navigation.ScanSessionNavBar
|
||||
|
||||
/**
|
||||
* Route unique du scanner — gère la permission caméra, le basculement entre
|
||||
@@ -59,11 +70,18 @@ fun ScanFlowScreen(
|
||||
val pages by viewModel.pages.collectAsStateWithLifecycle()
|
||||
|
||||
val context = LocalContext.current
|
||||
val activity = context as? Activity
|
||||
var hasCameraPermission by remember {
|
||||
mutableStateOf(ContextCompat.checkSelfPermission(context, CAMERA) == PackageManager.PERMISSION_GRANTED)
|
||||
}
|
||||
// Refus définitif (« ne plus demander ») : la demande système ne
|
||||
// réapparaîtra plus — on propose les Réglages au lieu d'un cul-de-sac.
|
||||
var permanentlyDenied by rememberSaveable { mutableStateOf(false) }
|
||||
val launcher = rememberLauncherForActivityResult(RequestPermission()) { granted ->
|
||||
hasCameraPermission = granted
|
||||
permanentlyDenied = !granted && activity?.let {
|
||||
!ActivityCompat.shouldShowRequestPermissionRationale(it, CAMERA)
|
||||
} ?: false
|
||||
}
|
||||
|
||||
// Retour écran précédent à l'export (observé une seule fois).
|
||||
@@ -85,7 +103,7 @@ fun ScanFlowScreen(
|
||||
// Confirmation avant de quitter le scanner quand des pages sont en cours :
|
||||
// la flèche CAMERA et le back système feront tous deux valider par un
|
||||
// dialogue (sinon abandon = suppression des pages capturées).
|
||||
var showExitConfirm by remember { mutableStateOf(false) }
|
||||
var showExitConfirm by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
val requestExit: () -> Unit = {
|
||||
if (pages.isNotEmpty()) {
|
||||
@@ -140,6 +158,19 @@ fun ScanFlowScreen(
|
||||
)
|
||||
},
|
||||
snackbarHost = { SnackbarHost(snackbarHostState) },
|
||||
bottomBar = {
|
||||
if (stage == ScanStage.SESSION) {
|
||||
ScanSessionNavBar(
|
||||
onAddPage = viewModel::openCamera,
|
||||
onExportPdf = viewModel::exportPdf,
|
||||
onExport = viewModel::export,
|
||||
canExport = pages.isNotEmpty(),
|
||||
// Le voile `busy` ne couvre que le contenu : sans ça la
|
||||
// barre resterait cliquable pendant l'export.
|
||||
actionsEnabled = !busy,
|
||||
)
|
||||
}
|
||||
},
|
||||
) { padding ->
|
||||
Box(
|
||||
modifier = Modifier
|
||||
@@ -156,7 +187,15 @@ fun ScanFlowScreen(
|
||||
)
|
||||
} else {
|
||||
CameraRationale(
|
||||
permanentlyDenied = permanentlyDenied,
|
||||
onGrant = { launcher.launch(CAMERA) },
|
||||
onOpenSettings = {
|
||||
val intent = Intent(
|
||||
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||
Uri.fromParts("package", context.packageName, null),
|
||||
)
|
||||
context.startActivity(intent)
|
||||
},
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
)
|
||||
}
|
||||
@@ -172,9 +211,15 @@ fun ScanFlowScreen(
|
||||
)
|
||||
}
|
||||
if (busy) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.align(Alignment.Center),
|
||||
)
|
||||
// Voile + spinner : bloque les interactions derrière le loader.
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.scrim.copy(alpha = 0.32f)),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (showExitConfirm) {
|
||||
@@ -199,19 +244,33 @@ fun ScanFlowScreen(
|
||||
|
||||
@Composable
|
||||
private fun CameraRationale(
|
||||
permanentlyDenied: Boolean,
|
||||
onGrant: () -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Box(modifier = modifier, contentAlignment = Alignment.Center) {
|
||||
androidx.compose.foundation.layout.Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.scan_permission_rationale),
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.padding(horizontal = 32.dp),
|
||||
)
|
||||
TextButton(onClick = onGrant, modifier = Modifier.padding(top = 16.dp)) {
|
||||
Text(stringResource(R.string.scan_permission_grant))
|
||||
if (permanentlyDenied) {
|
||||
Button(onClick = onOpenSettings) {
|
||||
Text(stringResource(R.string.scan_permission_open_settings))
|
||||
}
|
||||
TextButton(onClick = onGrant) {
|
||||
Text(stringResource(R.string.scan_permission_grant))
|
||||
}
|
||||
} else {
|
||||
Button(onClick = onGrant) {
|
||||
Text(stringResource(R.string.scan_permission_grant))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,40 +10,33 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.itemsIndexed
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||
import androidx.compose.material.icons.filled.PictureAsPdf
|
||||
import androidx.compose.material.icons.filled.Save
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import coil.compose.AsyncImage
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.data.local.entity.ScanPageEntity
|
||||
import com.kazier.mobile.ui.components.KazierCard
|
||||
import com.kazier.mobile.ui.theme.ThumbShape
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Étape « session » : pages capturées (miniatures), réordonnancement,
|
||||
* suppression, ajout d'une page et export vers le dossier Kazier
|
||||
* (1 fichier JPEG = 1 `create_resource` outbox).
|
||||
* Étape « session » : pages capturées (miniatures), réordonnancement et
|
||||
* suppression. Les actions (ajouter, exporter PDF, exporter) vivent dans la
|
||||
* pilule flottante du [ScanFlowScreen] (même style que Fichiers/Dashboard).
|
||||
*/
|
||||
@Composable
|
||||
fun SessionStage(
|
||||
@@ -87,37 +80,6 @@ fun SessionStage(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(16.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = viewModel::openCamera,
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Icon(imageVector = Icons.Filled.Add, contentDescription = null)
|
||||
Text(stringResource(R.string.scan_add_page), modifier = Modifier.padding(start = 4.dp))
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = viewModel::exportPdf,
|
||||
modifier = Modifier.weight(1f),
|
||||
enabled = pages.isNotEmpty(),
|
||||
) {
|
||||
Icon(imageVector = Icons.Filled.PictureAsPdf, contentDescription = null)
|
||||
Text(stringResource(R.string.scan_export_pdf), modifier = Modifier.padding(start = 4.dp))
|
||||
}
|
||||
Button(
|
||||
onClick = viewModel::export,
|
||||
modifier = Modifier.weight(1f),
|
||||
enabled = pages.isNotEmpty(),
|
||||
) {
|
||||
Icon(imageVector = Icons.Filled.Save, contentDescription = null)
|
||||
Text(stringResource(R.string.scan_export), modifier = Modifier.padding(start = 4.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,18 +93,18 @@ private fun PageCard(
|
||||
onMoveDown: () -> Unit,
|
||||
onDelete: () -> Unit,
|
||||
) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
KazierCard(modifier = Modifier.fillMaxWidth()) {
|
||||
Row(
|
||||
modifier = Modifier.padding(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
AsyncImage(
|
||||
model = File(page.tempUri),
|
||||
contentDescription = null,
|
||||
contentDescription = stringResource(R.string.scan_pages_count, index + 1),
|
||||
contentScale = ContentScale.Crop,
|
||||
modifier = Modifier
|
||||
.size(64.dp)
|
||||
.clip(RoundedCornerShape(8.dp)),
|
||||
.clip(ThumbShape),
|
||||
)
|
||||
Column(
|
||||
modifier = Modifier
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.kazier.mobile.ui.search
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
@@ -18,15 +17,14 @@ import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.LazyRow
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Clear
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.FilterChipDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
@@ -45,9 +43,10 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
@@ -65,13 +64,15 @@ import com.kazier.mobile.ui.components.DeleteWarningDialog
|
||||
import com.kazier.mobile.ui.components.FileCategoryIcon
|
||||
import com.kazier.mobile.ui.components.FilePendingReviewBadge
|
||||
import com.kazier.mobile.ui.components.FileSyncStatusIcon
|
||||
import com.kazier.mobile.ui.components.KazierCard
|
||||
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||
import com.kazier.mobile.ui.components.MoveFolderPickerDialog
|
||||
import com.kazier.mobile.ui.components.SelectionState
|
||||
import com.kazier.mobile.ui.components.SelectionStatusIcon
|
||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
||||
import com.kazier.mobile.ui.components.color
|
||||
import com.kazier.mobile.ui.components.formatFileSize
|
||||
import com.kazier.mobile.ui.components.label
|
||||
import com.kazier.mobile.ui.components.icon
|
||||
import com.kazier.mobile.ui.components.color
|
||||
import com.kazier.mobile.ui.components.rememberSelectionState
|
||||
import com.kazier.mobile.ui.components.reviewDelete
|
||||
import com.kazier.mobile.ui.navigation.FloatingNavBar
|
||||
@@ -91,7 +92,6 @@ fun SearchScreen(
|
||||
viewModel: SearchViewModel = hiltViewModel(),
|
||||
) {
|
||||
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
|
||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
||||
val moveFolders by viewModel.moveFolders.collectAsStateWithLifecycle()
|
||||
val moveError by viewModel.moveError.collectAsStateWithLifecycle()
|
||||
val deleteError by viewModel.deleteError.collectAsStateWithLifecycle()
|
||||
@@ -100,10 +100,10 @@ fun SearchScreen(
|
||||
var showMoveDialog by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeleteWarning by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeleteConfirm by rememberSaveable { mutableStateOf(false) }
|
||||
var pendingDeleteMode by remember { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||
var pendingDeleteReview by remember { mutableStateOf<DeleteReview?>(null) }
|
||||
var pendingDeleteMode by rememberSaveable { mutableStateOf<FileDeleter.DeleteMode?>(null) }
|
||||
var pendingDeleteReview by rememberSaveable { mutableStateOf<DeleteReview?>(null) }
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
val deletedLabel = stringResource(R.string.delete)
|
||||
val deletedLabel = stringResource(R.string.delete_success)
|
||||
|
||||
LaunchedEffect(moveError) {
|
||||
val message = moveError
|
||||
@@ -156,10 +156,9 @@ fun SearchScreen(
|
||||
},
|
||||
actions = {
|
||||
if (!selection.active) {
|
||||
SyncStatusAction(syncViewModel = syncViewModel)
|
||||
ServerStatusBadge(
|
||||
status = connectionStatus,
|
||||
onClick = connectionStatusViewModel::checkNow,
|
||||
HeaderStatusAction(
|
||||
syncViewModel = syncViewModel,
|
||||
connectionStatusViewModel = connectionStatusViewModel,
|
||||
)
|
||||
}
|
||||
},
|
||||
@@ -274,6 +273,7 @@ private fun SearchContent(
|
||||
onOpenDocument: (String) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val keyboardController = LocalSoftwareKeyboardController.current
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
@@ -286,9 +286,23 @@ private fun SearchContent(
|
||||
onValueChange = onQueryChange,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
|
||||
trailingIcon = {
|
||||
if (uiState.query.isNotBlank() && !selection.active) {
|
||||
IconButton(onClick = { onQueryChange("") }) {
|
||||
Icon(
|
||||
Icons.Filled.Clear,
|
||||
contentDescription = stringResource(R.string.search_clear),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
placeholder = { Text(stringResource(R.string.search_hint)) },
|
||||
singleLine = true,
|
||||
enabled = !selection.active,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||
keyboardActions = KeyboardActions(
|
||||
onSearch = { keyboardController?.hide() },
|
||||
),
|
||||
)
|
||||
|
||||
LazyRow(
|
||||
@@ -307,7 +321,7 @@ private fun SearchContent(
|
||||
}
|
||||
items(FileCategory.entries, key = { it.name }) { category ->
|
||||
CategoryChip(
|
||||
label = categoryLabel(category),
|
||||
label = category.label(),
|
||||
selected = uiState.selectedCategory == category.dbValue,
|
||||
enabled = !selection.active,
|
||||
onClick = { onCategorySelect(category.dbValue) },
|
||||
@@ -342,29 +356,14 @@ private fun CategoryChip(
|
||||
{
|
||||
Icon(
|
||||
imageVector = cat.icon,
|
||||
contentDescription = null,
|
||||
tint = cat.color,
|
||||
contentDescription = cat.label(),
|
||||
tint = cat.color(),
|
||||
)
|
||||
}
|
||||
},
|
||||
colors = FilterChipDefaults.filterChipColors(
|
||||
containerColor = Color(0xFFF7F8FA),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** Libellé français de la catégorie (store = enum.name, affichage = label localisé). */
|
||||
@Composable
|
||||
private fun categoryLabel(category: FileCategory): String = when (category) {
|
||||
FileCategory.PDF -> stringResource(R.string.category_pdf)
|
||||
FileCategory.OFFICE -> stringResource(R.string.category_office)
|
||||
FileCategory.IMAGE -> stringResource(R.string.category_image)
|
||||
FileCategory.TEXT -> stringResource(R.string.category_text)
|
||||
FileCategory.VIDEO -> stringResource(R.string.category_video)
|
||||
FileCategory.AUDIO -> stringResource(R.string.category_audio)
|
||||
FileCategory.OTHER -> stringResource(R.string.category_other)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SearchResults(
|
||||
uiState: SearchUiState,
|
||||
@@ -413,6 +412,15 @@ private fun SearchResults(
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
item(key = "results-count") {
|
||||
Text(
|
||||
text = stringResource(R.string.search_results_count, uiState.results.size),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
items(uiState.results, key = { it.resourceId }) { file ->
|
||||
SearchResultCard(
|
||||
@@ -434,11 +442,7 @@ private fun SearchResultCard(
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val selected = file.resourceId in selection.ids
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = Color(0xFFF7F8FA)),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
|
||||
border = BorderStroke(1.dp, Color(0xFFEAEAEA)),
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
KazierCard(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.combinedClickable(
|
||||
@@ -466,9 +470,11 @@ private fun SearchResultCard(
|
||||
)
|
||||
Spacer(Modifier.height(2.dp))
|
||||
Text(
|
||||
text = file.extension?.let { it.uppercase(Locale.getDefault()) } ?: formatSize(file.size),
|
||||
text = resultSubtitle(file),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
@@ -480,11 +486,6 @@ private fun SearchResultCard(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
FilePendingReviewBadge(file = file)
|
||||
Text(
|
||||
text = formatSize(file.size),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
FileSyncStatusIcon(file = file, size = 18.dp)
|
||||
}
|
||||
}
|
||||
@@ -492,15 +493,10 @@ private fun SearchResultCard(
|
||||
}
|
||||
}
|
||||
|
||||
/** Sous-titre résultat : `EXT · taille` si l'extension existe, sinon la taille seule. */
|
||||
@Composable
|
||||
private fun formatSize(bytes: Long): String {
|
||||
if (bytes < 1_024) {
|
||||
return "$bytes ${stringResource(R.string.unit_bytes)}"
|
||||
}
|
||||
if (bytes < 1_024 * 1_024) {
|
||||
val kb = bytes / 1_024f
|
||||
return String.format(Locale.getDefault(), "%.1f %s", kb, stringResource(R.string.unit_kilobytes))
|
||||
}
|
||||
val mb = bytes / (1_024f * 1_024f)
|
||||
return String.format(Locale.getDefault(), "%.1f %s", mb, stringResource(R.string.unit_megabytes))
|
||||
private fun resultSubtitle(file: FileEntity): String {
|
||||
val size = formatFileSize(file.size)
|
||||
val ext = file.extension?.takeIf { it.isNotBlank() }?.uppercase(Locale.getDefault())
|
||||
return if (ext != null) "$ext · $size" else size
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
package com.kazier.mobile.ui.settings
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.imePadding
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
@@ -14,22 +16,24 @@ import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.DarkMode
|
||||
import androidx.compose.material.icons.filled.Dns
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.Person
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.RadioButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
@@ -40,8 +44,6 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
@@ -51,9 +53,9 @@ import com.kazier.mobile.features.connection.ConnectionStatusViewModel
|
||||
import com.kazier.mobile.features.sync.SyncViewModel
|
||||
import com.kazier.mobile.ui.auth.AuthState
|
||||
import com.kazier.mobile.ui.auth.AuthViewModel
|
||||
import com.kazier.mobile.ui.auth.LoginForm
|
||||
import com.kazier.mobile.ui.auth.authErrorResFor
|
||||
import com.kazier.mobile.ui.components.ServerStatusBadge
|
||||
import com.kazier.mobile.ui.components.SyncStatusAction
|
||||
import com.kazier.mobile.ui.components.HeaderStatusAction
|
||||
import com.kazier.mobile.ui.components.WatchedFoldersBadge
|
||||
import com.kazier.mobile.ui.navigation.FloatingNavBar
|
||||
import com.kazier.mobile.ui.navigation.NavTab
|
||||
@@ -72,22 +74,31 @@ fun SettingsScreen(
|
||||
val theme by viewModel.theme.collectAsStateWithLifecycle()
|
||||
val serverUrl by viewModel.serverUrl.collectAsStateWithLifecycle()
|
||||
val testUiState by viewModel.testUiState.collectAsStateWithLifecycle()
|
||||
val connectionStatus by connectionStatusViewModel.status.collectAsStateWithLifecycle()
|
||||
val authState by authViewModel.authState.collectAsStateWithLifecycle()
|
||||
val loginUi by authViewModel.loginUiState.collectAsStateWithLifecycle()
|
||||
|
||||
var username by rememberSaveable { mutableStateOf("") }
|
||||
var password by rememberSaveable { mutableStateOf("") }
|
||||
var showThemeDialog by rememberSaveable { mutableStateOf(false) }
|
||||
var showServerDialog by rememberSaveable { mutableStateOf(false) }
|
||||
var showAuthDialog by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
// Login réussi → refermer le dialogue et purger le mot de passe.
|
||||
LaunchedEffect(authState) {
|
||||
if (authState is AuthState.SignedIn) {
|
||||
showAuthDialog = false
|
||||
password = ""
|
||||
}
|
||||
}
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text(stringResource(R.string.settings)) },
|
||||
actions = {
|
||||
SyncStatusAction(syncViewModel = syncViewModel)
|
||||
ServerStatusBadge(
|
||||
status = connectionStatus,
|
||||
onClick = connectionStatusViewModel::checkNow,
|
||||
HeaderStatusAction(
|
||||
syncViewModel = syncViewModel,
|
||||
connectionStatusViewModel = connectionStatusViewModel,
|
||||
)
|
||||
},
|
||||
)
|
||||
@@ -100,11 +111,12 @@ fun SettingsScreen(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.imePadding()
|
||||
.verticalScroll(rememberScrollState()),
|
||||
) {
|
||||
HorizontalDivider()
|
||||
// M36 : 3 états (Système/Clair/Sombre) — le Switch DARK/LIGHT
|
||||
// rendait SYSTEM inatteignable alors que le store le supporte.
|
||||
// Une ligne par section — le détail vit dans un dialogue,
|
||||
// comme les dossiers système surveillés.
|
||||
SettingsRow(
|
||||
icon = { Icon(Icons.Filled.DarkMode, contentDescription = null) },
|
||||
title = stringResource(R.string.settings_theme),
|
||||
@@ -115,12 +127,7 @@ fun SettingsScreen(
|
||||
ThemePreference.SYSTEM -> R.string.settings_theme_system
|
||||
},
|
||||
),
|
||||
trailing = {
|
||||
ThemeSelector(
|
||||
selected = theme,
|
||||
onSelect = viewModel::setTheme,
|
||||
)
|
||||
},
|
||||
onClick = { showThemeDialog = true },
|
||||
)
|
||||
|
||||
HorizontalDivider()
|
||||
@@ -135,168 +142,224 @@ fun SettingsScreen(
|
||||
)
|
||||
|
||||
HorizontalDivider()
|
||||
SettingsSectionTitle(stringResource(R.string.settings_server))
|
||||
|
||||
OutlinedTextField(
|
||||
value = serverUrl,
|
||||
onValueChange = viewModel::onServerUrlChange,
|
||||
label = { Text(stringResource(R.string.settings_server_url)) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Uri,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp),
|
||||
SettingsRow(
|
||||
icon = { Icon(Icons.Filled.Dns, contentDescription = null) },
|
||||
title = stringResource(R.string.settings_server),
|
||||
subtitle = serverUrl.ifBlank {
|
||||
stringResource(R.string.settings_server_hint)
|
||||
},
|
||||
onClick = { showServerDialog = true },
|
||||
)
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = viewModel::testConnection,
|
||||
enabled = !testUiState.isTesting,
|
||||
) {
|
||||
if (testUiState.isTesting) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(18.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
} else {
|
||||
Text(stringResource(R.string.settings_test_connection))
|
||||
}
|
||||
}
|
||||
testUiState.success?.let { success ->
|
||||
Spacer(Modifier.size(16.dp))
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (success) R.string.settings_test_success
|
||||
else R.string.settings_test_failure,
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (success) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.error
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
when (val state = authState) {
|
||||
is AuthState.SignedIn -> {
|
||||
SettingsRow(
|
||||
icon = { Icon(Icons.Filled.Person, contentDescription = null) },
|
||||
title = stringResource(R.string.settings_connected_as, state.user.username),
|
||||
subtitle = stringResource(R.string.settings),
|
||||
trailing = {
|
||||
TextButton(onClick = authViewModel::signOutToLocal) {
|
||||
Text(stringResource(R.string.settings_disconnect))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
AuthState.Loading -> Unit
|
||||
else -> {
|
||||
SettingsSectionTitle(stringResource(R.string.settings_connect))
|
||||
OutlinedTextField(
|
||||
value = username,
|
||||
onValueChange = { username = it },
|
||||
label = { Text(stringResource(R.string.login_username)) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = { password = it },
|
||||
label = { Text(stringResource(R.string.login_password)) },
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Password,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Button(
|
||||
onClick = { authViewModel.signIn(username, password) },
|
||||
enabled = !loginUi.isSubmitting,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp),
|
||||
) {
|
||||
if (loginUi.isSubmitting) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(20.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
} else {
|
||||
Text(stringResource(R.string.settings_connect))
|
||||
}
|
||||
}
|
||||
loginUi.error?.let { error ->
|
||||
Text(
|
||||
text = stringResource(authErrorResFor(error)),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
val signedIn = authState as? AuthState.SignedIn
|
||||
SettingsRow(
|
||||
icon = { Icon(Icons.Filled.Person, contentDescription = null) },
|
||||
title = stringResource(
|
||||
if (signedIn != null) R.string.settings_disconnect
|
||||
else R.string.settings_connect,
|
||||
),
|
||||
subtitle = when (val state = authState) {
|
||||
is AuthState.SignedIn ->
|
||||
stringResource(R.string.settings_connected_as, state.user.username)
|
||||
AuthState.Local -> stringResource(R.string.status_local)
|
||||
AuthState.Loading -> stringResource(R.string.status_checking)
|
||||
else -> stringResource(R.string.settings_sign_in_hint)
|
||||
},
|
||||
onClick = { showAuthDialog = true },
|
||||
)
|
||||
|
||||
HorizontalDivider()
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ThemeSelector(
|
||||
selected: ThemePreference,
|
||||
onSelect: (ThemePreference) -> Unit,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
ThemeChip(
|
||||
label = stringResource(R.string.settings_theme_system),
|
||||
selected = selected == ThemePreference.SYSTEM,
|
||||
onClick = { onSelect(ThemePreference.SYSTEM) },
|
||||
if (showThemeDialog) {
|
||||
ThemeDialog(
|
||||
selected = theme,
|
||||
onSelect = viewModel::setTheme,
|
||||
onDismiss = { showThemeDialog = false },
|
||||
)
|
||||
ThemeChip(
|
||||
label = stringResource(R.string.settings_theme_light),
|
||||
selected = selected == ThemePreference.LIGHT,
|
||||
onClick = { onSelect(ThemePreference.LIGHT) },
|
||||
)
|
||||
ThemeChip(
|
||||
label = stringResource(R.string.settings_theme_dark),
|
||||
selected = selected == ThemePreference.DARK,
|
||||
onClick = { onSelect(ThemePreference.DARK) },
|
||||
}
|
||||
|
||||
if (showServerDialog) {
|
||||
ServerDialog(
|
||||
serverUrl = serverUrl,
|
||||
onServerUrlChange = viewModel::onServerUrlChange,
|
||||
isTesting = testUiState.isTesting,
|
||||
success = testUiState.success,
|
||||
onTest = viewModel::testConnection,
|
||||
onDismiss = { showServerDialog = false },
|
||||
)
|
||||
}
|
||||
|
||||
if (showAuthDialog) {
|
||||
when (val state = authState) {
|
||||
is AuthState.SignedIn -> {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showAuthDialog = false },
|
||||
title = { Text(stringResource(R.string.settings_disconnect)) },
|
||||
text = {
|
||||
Text(stringResource(R.string.settings_disconnect_confirm, state.user.username))
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(
|
||||
onClick = {
|
||||
authViewModel.signOutToLocal()
|
||||
showAuthDialog = false
|
||||
},
|
||||
) {
|
||||
Text(stringResource(R.string.settings_disconnect))
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = { showAuthDialog = false }) {
|
||||
Text(stringResource(R.string.settings_cancel))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
AuthState.Loading -> Unit
|
||||
else -> {
|
||||
AlertDialog(
|
||||
onDismissRequest = { showAuthDialog = false },
|
||||
title = { Text(stringResource(R.string.settings_connect)) },
|
||||
text = {
|
||||
LoginForm(
|
||||
username = username,
|
||||
onUsernameChange = { username = it },
|
||||
password = password,
|
||||
onPasswordChange = { password = it },
|
||||
submitting = loginUi.isSubmitting,
|
||||
errorRes = loginUi.error?.let(::authErrorResFor),
|
||||
submitLabel = stringResource(R.string.settings_connect),
|
||||
onSubmit = { authViewModel.signIn(username, password) },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
},
|
||||
confirmButton = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ThemeChip(
|
||||
label: String,
|
||||
selected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
private fun ThemeDialog(
|
||||
selected: ThemePreference,
|
||||
onSelect: (ThemePreference) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
FilterChip(
|
||||
selected = selected,
|
||||
onClick = onClick,
|
||||
label = { Text(label) },
|
||||
val options = listOf(
|
||||
ThemePreference.SYSTEM to R.string.settings_theme_system,
|
||||
ThemePreference.LIGHT to R.string.settings_theme_light,
|
||||
ThemePreference.DARK to R.string.settings_theme_dark,
|
||||
)
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.settings_theme_choose)) },
|
||||
text = {
|
||||
Column {
|
||||
options.forEach { (preference, labelRes) ->
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable {
|
||||
onSelect(preference)
|
||||
onDismiss()
|
||||
}
|
||||
.padding(vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
RadioButton(
|
||||
selected = selected == preference,
|
||||
onClick = {
|
||||
onSelect(preference)
|
||||
onDismiss()
|
||||
},
|
||||
)
|
||||
Text(
|
||||
text = stringResource(labelRes),
|
||||
modifier = Modifier.padding(start = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = onDismiss) {
|
||||
Text(stringResource(R.string.settings_close))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ServerDialog(
|
||||
serverUrl: String,
|
||||
onServerUrlChange: (String) -> Unit,
|
||||
isTesting: Boolean,
|
||||
success: Boolean?,
|
||||
onTest: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text(stringResource(R.string.settings_server)) },
|
||||
text = {
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = serverUrl,
|
||||
onValueChange = onServerUrlChange,
|
||||
label = { Text(stringResource(R.string.settings_server_url)) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(
|
||||
keyboardType = KeyboardType.Uri,
|
||||
imeAction = ImeAction.Done,
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = onTest,
|
||||
enabled = !isTesting,
|
||||
) {
|
||||
if (isTesting) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(18.dp),
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
} else {
|
||||
Text(stringResource(R.string.settings_test_connection))
|
||||
}
|
||||
}
|
||||
success?.let {
|
||||
Spacer(Modifier.size(16.dp))
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (it) R.string.settings_test_success
|
||||
else R.string.settings_test_failure,
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (it) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.error
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = onDismiss) {
|
||||
Text(stringResource(R.string.settings_close))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -335,14 +398,3 @@ private fun SettingsRow(
|
||||
trailing()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SettingsSectionTitle(title: String) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleSmall,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
)
|
||||
}
|
||||
@@ -1,23 +1,25 @@
|
||||
package com.kazier.mobile.ui.share
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.ExposedDropdownMenuBox
|
||||
import androidx.compose.material3.ExposedDropdownMenuDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.MenuAnchorType
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
@@ -27,14 +29,16 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.kazier.mobile.R
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
/** Niveau d'accès sélectionnable — miroir de `ShareAccessLevel`. */
|
||||
private data class AccessOption(
|
||||
@@ -58,12 +62,18 @@ fun ShareBottomSheet(
|
||||
error: String?,
|
||||
enqueued: Boolean,
|
||||
) {
|
||||
var username by remember { mutableStateOf("") }
|
||||
var access by remember { mutableStateOf(ShareAccessLevel.VIEWER) }
|
||||
var username by rememberSaveable { mutableStateOf("") }
|
||||
var access by rememberSaveable { mutableStateOf(ShareAccessLevel.VIEWER) }
|
||||
// Confirmation visible avant fermeture : fini l'auto-dismiss silencieux.
|
||||
var justShared by rememberSaveable { mutableStateOf(false) }
|
||||
val sheetState = rememberModalBottomSheetState()
|
||||
|
||||
LaunchedEffect(enqueued) {
|
||||
if (enqueued) onDismiss()
|
||||
if (enqueued && !justShared) {
|
||||
justShared = true
|
||||
delay(1_200)
|
||||
onDismiss()
|
||||
}
|
||||
}
|
||||
|
||||
ModalBottomSheet(
|
||||
@@ -94,6 +104,7 @@ fun ShareBottomSheet(
|
||||
onValueChange = { username = it },
|
||||
label = { Text(stringResource(R.string.share_username_hint)) },
|
||||
singleLine = true,
|
||||
enabled = !justShared,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
@@ -105,6 +116,7 @@ fun ShareBottomSheet(
|
||||
AccessDropdown(
|
||||
selected = access,
|
||||
onSelect = { access = it },
|
||||
enabled = !justShared,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
@@ -118,9 +130,29 @@ fun ShareBottomSheet(
|
||||
)
|
||||
}
|
||||
|
||||
if (justShared) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Check,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.share_enqueued),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = { onShare(username.trim(), access) },
|
||||
enabled = username.isNotBlank() && !sharing,
|
||||
enabled = username.isNotBlank() && !sharing && !justShared,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
if (sharing) {
|
||||
@@ -136,7 +168,7 @@ fun ShareBottomSheet(
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = onDismiss,
|
||||
enabled = !sharing,
|
||||
enabled = !sharing && !justShared,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(stringResource(R.string.share_cancel))
|
||||
@@ -145,32 +177,35 @@ fun ShareBottomSheet(
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
private fun AccessDropdown(
|
||||
selected: String,
|
||||
onSelect: (String) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true,
|
||||
) {
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
var expanded by rememberSaveable { mutableStateOf(false) }
|
||||
val selectedLabel = ACCESS_OPTIONS.firstOrNull { it.value == selected }?.labelRes
|
||||
?: ACCESS_OPTIONS.first().labelRes
|
||||
|
||||
Box(modifier = modifier) {
|
||||
OutlinedButton(
|
||||
onClick = { expanded = true },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(selectedLabel),
|
||||
modifier = Modifier.weight(1f),
|
||||
textAlign = TextAlign.Start,
|
||||
)
|
||||
Icon(
|
||||
imageVector = Icons.Filled.KeyboardArrowDown,
|
||||
contentDescription = null,
|
||||
)
|
||||
}
|
||||
DropdownMenu(
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = expanded,
|
||||
onExpandedChange = { if (enabled) expanded = it },
|
||||
modifier = modifier,
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = stringResource(selectedLabel),
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
enabled = enabled,
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
|
||||
colors = ExposedDropdownMenuDefaults.outlinedTextFieldColors(),
|
||||
modifier = Modifier
|
||||
.menuAnchor(MenuAnchorType.PrimaryNotEditable)
|
||||
.fillMaxWidth(),
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = expanded,
|
||||
onDismissRequest = { expanded = false },
|
||||
) {
|
||||
@@ -181,6 +216,7 @@ private fun AccessDropdown(
|
||||
onSelect(option.value)
|
||||
expanded = false
|
||||
},
|
||||
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,31 @@ package com.kazier.mobile.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
// Marque — inchangée (contrat visuel existant).
|
||||
val BrandBlue = Color(0xFF1A73E8)
|
||||
val BrandBlueDark = Color(0xFF004A9E)
|
||||
val BondBlueLight = Color(0xFFD2E3FC)
|
||||
val BondBlueContainerDark = Color(0xFF004A77)
|
||||
val InactiveGray = Color(0xFF6B7280)
|
||||
|
||||
// Cartes / bordures — déclinaison light + dark (ne plus hardcoder en UI).
|
||||
val CardBackground = Color(0xFFF7F8FA)
|
||||
val CardBackgroundDark = Color(0xFF1E1F22)
|
||||
val CardBorder = Color(0xFFEAEAEA)
|
||||
val CardBorderDark = Color(0xFF333639)
|
||||
|
||||
// Sémantique métier — paires light/dark lisibles sur fond clair ET sombre.
|
||||
val SuccessLight = Color(0xFF2E7D32)
|
||||
val SuccessDark = Color(0xFF81C784)
|
||||
val WarningLight = Color(0xFFB26A00)
|
||||
val WarningDark = Color(0xFFFFB74D)
|
||||
val InfoLight = Color(0xFF1565C0)
|
||||
val InfoDark = Color(0xFF90CAF9)
|
||||
val ErrorLight = Color(0xFFB3261E)
|
||||
val ErrorDark = Color(0xFFF2B8B5)
|
||||
|
||||
// Pastilles sync / serveur — versions lisibles en dark (texte blanc exclu).
|
||||
val SyncingLight = Color(0xFF1E88E5)
|
||||
val SyncingDark = Color(0xFF90CAF9)
|
||||
val PendingLight = Color(0xFFB26A00)
|
||||
val PendingDark = Color(0xFFFFB74D)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.kazier.mobile.ui.theme
|
||||
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/** Espacements et élévations partagés — évite les valeurs magiques dispersées. */
|
||||
object KazierDimens {
|
||||
val SpacingXxs = 2.dp
|
||||
val SpacingXs = 4.dp
|
||||
val SpacingSm = 8.dp
|
||||
val SpacingMd = 12.dp
|
||||
val SpacingLg = 16.dp
|
||||
val SpacingXl = 20.dp
|
||||
|
||||
val CardElevation = 1.dp
|
||||
val NavElevation = 8.dp
|
||||
val CardBorderWidth = 1.dp
|
||||
|
||||
val ListMaxWidth = 400.dp
|
||||
val DialogListMaxHeight = 360.dp
|
||||
val MinTouchTarget = 48.dp
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.kazier.mobile.ui.theme
|
||||
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Shapes
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/** Rayons unifiés : cartes 12dp, sheets/dialogs 20dp, pills 28dp. */
|
||||
val KazierShapes = Shapes(
|
||||
extraSmall = RoundedCornerShape(8.dp),
|
||||
small = RoundedCornerShape(12.dp),
|
||||
medium = RoundedCornerShape(20.dp),
|
||||
large = RoundedCornerShape(28.dp),
|
||||
extraLarge = RoundedCornerShape(30.dp),
|
||||
)
|
||||
|
||||
/** Formes nommées pour les usages récurrents (listes, nav, badges). */
|
||||
val ListCardShape = RoundedCornerShape(12.dp)
|
||||
val SheetShape = RoundedCornerShape(20.dp)
|
||||
val PillShape = RoundedCornerShape(percent = 50)
|
||||
val NavPillShape = RoundedCornerShape(30.dp)
|
||||
val NavItemShape = RoundedCornerShape(20.dp)
|
||||
val ThumbShape = RoundedCornerShape(8.dp)
|
||||
@@ -4,18 +4,61 @@ import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import com.kazier.mobile.domain.ThemePreference
|
||||
|
||||
private val LightColors = lightColorScheme(
|
||||
primary = BrandBlue,
|
||||
onPrimary = androidx.compose.ui.graphics.Color.White,
|
||||
onPrimary = Color.White,
|
||||
primaryContainer = BondBlueLight,
|
||||
onPrimaryContainer = BrandBlueDark,
|
||||
secondary = InactiveGray,
|
||||
onSecondary = Color.White,
|
||||
secondaryContainer = CardBackground,
|
||||
onSecondaryContainer = Color(0xFF1A1C1E),
|
||||
tertiary = SuccessLight,
|
||||
onTertiary = Color.White,
|
||||
tertiaryContainer = Color(0xFFE3F2E6),
|
||||
onTertiaryContainer = Color(0xFF1B4D1F),
|
||||
error = ErrorLight,
|
||||
onError = Color.White,
|
||||
errorContainer = Color(0xFFF9DEDC),
|
||||
onErrorContainer = Color(0xFF410E0B),
|
||||
surface = Color(0xFFFFFBFE),
|
||||
onSurface = Color(0xFF1A1C1E),
|
||||
surfaceVariant = CardBackground,
|
||||
onSurfaceVariant = Color(0xFF43474E),
|
||||
surfaceContainerLowest = Color.White,
|
||||
surfaceContainerLow = CardBackground,
|
||||
outline = Color(0xFFC3C6CF),
|
||||
outlineVariant = CardBorder,
|
||||
)
|
||||
|
||||
private val DarkColors = darkColorScheme(
|
||||
primary = BondBlueLight,
|
||||
onPrimary = androidx.compose.ui.graphics.Color.Black,
|
||||
onPrimary = Color(0xFF001D35),
|
||||
primaryContainer = BondBlueContainerDark,
|
||||
onPrimaryContainer = BondBlueLight,
|
||||
secondary = Color(0xFF9AA0AA),
|
||||
onSecondary = Color(0xFF1A1C1E),
|
||||
secondaryContainer = CardBackgroundDark,
|
||||
onSecondaryContainer = Color(0xFFE2E2E6),
|
||||
tertiary = SuccessDark,
|
||||
onTertiary = Color(0xFF00330A),
|
||||
tertiaryContainer = Color(0xFF1B4D1F),
|
||||
onTertiaryContainer = Color(0xFFE3F2E6),
|
||||
error = ErrorDark,
|
||||
onError = Color(0xFF601410),
|
||||
errorContainer = Color(0xFF8C1D18),
|
||||
onErrorContainer = Color(0xFFF9DEDC),
|
||||
surface = Color(0xFF141218),
|
||||
onSurface = Color(0xFFE6E0E9),
|
||||
surfaceVariant = CardBackgroundDark,
|
||||
onSurfaceVariant = Color(0xFFCAC4D0),
|
||||
surfaceContainerLowest = Color(0xFF0F0D13),
|
||||
surfaceContainerLow = CardBackgroundDark,
|
||||
outline = Color(0xFF4A4E57),
|
||||
outlineVariant = CardBorderDark,
|
||||
)
|
||||
|
||||
@Composable
|
||||
@@ -39,6 +82,7 @@ fun KazierTheme(
|
||||
MaterialTheme(
|
||||
colorScheme = if (darkTheme) DarkColors else LightColors,
|
||||
typography = Typography,
|
||||
shapes = KazierShapes,
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,16 +6,46 @@ import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
val Typography = Typography(
|
||||
bodyLarge = TextStyle(
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 24.sp,
|
||||
fontWeight = FontWeight.Normal,
|
||||
headlineSmall = TextStyle(
|
||||
fontSize = 20.sp,
|
||||
lineHeight = 28.sp,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
),
|
||||
headlineMedium = TextStyle(
|
||||
fontSize = 24.sp,
|
||||
lineHeight = 32.sp,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
),
|
||||
titleSmall = TextStyle(
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 20.sp,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
),
|
||||
titleMedium = TextStyle(
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 24.sp,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
),
|
||||
bodyLarge = TextStyle(
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 24.sp,
|
||||
fontWeight = FontWeight.Normal,
|
||||
),
|
||||
bodyMedium = TextStyle(
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 20.sp,
|
||||
fontWeight = FontWeight.Normal,
|
||||
),
|
||||
bodySmall = TextStyle(
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 16.sp,
|
||||
fontWeight = FontWeight.Normal,
|
||||
),
|
||||
labelSmall = TextStyle(
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
),
|
||||
labelMedium = TextStyle(
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 16.sp,
|
||||
|
||||
+59
-14
@@ -16,26 +16,30 @@ import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.Folder
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
@@ -65,6 +69,20 @@ fun WatchedFoldersScreen(
|
||||
|
||||
val context = LocalContext.current
|
||||
val folderLabel = stringResource(R.string.folder)
|
||||
val importDoneLabel = stringResource(R.string.settings_import_done)
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
// Erreur d'import → snackbar (une fois par message, auto-dismiss).
|
||||
LaunchedEffect(importState.error) {
|
||||
importState.error?.let { snackbarHostState.showSnackbar(it) }
|
||||
}
|
||||
// Fin d'import sans erreur → confirmation (succès silencieux sinon).
|
||||
var wasImporting by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(importState.isImporting) {
|
||||
if (wasImporting && !importState.isImporting && importState.error == null) {
|
||||
snackbarHostState.showSnackbar(importDoneLabel)
|
||||
}
|
||||
wasImporting = importState.isImporting
|
||||
}
|
||||
val pickFolderLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.OpenDocumentTree(),
|
||||
) { uri: Uri? ->
|
||||
@@ -96,6 +114,7 @@ fun WatchedFoldersScreen(
|
||||
},
|
||||
)
|
||||
},
|
||||
snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
|
||||
) { padding ->
|
||||
LazyColumn(
|
||||
modifier = Modifier
|
||||
@@ -128,15 +147,20 @@ fun WatchedFoldersScreen(
|
||||
}
|
||||
|
||||
items(folders, key = { it.resourceId }) { root ->
|
||||
WatchedFolderRow(root)
|
||||
HorizontalDivider()
|
||||
WatchedFolderRow(
|
||||
folder = root,
|
||||
rescanEnabled = !importState.isImporting,
|
||||
onRescan = { uri ->
|
||||
syncViewModel.importRoot(uri = uri, name = root.name)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (folders.isEmpty() && !importState.isImporting) {
|
||||
item(key = "empty") {
|
||||
Text(
|
||||
text = stringResource(R.string.settings_saf_folders_empty),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier
|
||||
@@ -150,7 +174,20 @@ fun WatchedFoldersScreen(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WatchedFolderRow(folder: FolderEntity) {
|
||||
private fun WatchedFolderRow(
|
||||
folder: FolderEntity,
|
||||
rescanEnabled: Boolean,
|
||||
onRescan: (uri: String) -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
// Nom lisible du dossier au lieu de l'URI brute `content://…`.
|
||||
val location = remember(folder.uri) {
|
||||
folder.uri?.let { raw ->
|
||||
runCatching {
|
||||
Uri.parse(raw)?.safDisplayName(context)
|
||||
}.getOrNull()?.takeIf { it.isNotBlank() && it != folder.name }
|
||||
}
|
||||
}
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
@@ -160,12 +197,9 @@ private fun WatchedFolderRow(folder: FolderEntity) {
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Folder,
|
||||
contentDescription = null,
|
||||
contentDescription = folder.name,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier
|
||||
.size(40.dp)
|
||||
.clip(CircleShape)
|
||||
.padding(8.dp),
|
||||
modifier = Modifier.size(28.dp),
|
||||
)
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
@@ -175,9 +209,9 @@ private fun WatchedFolderRow(folder: FolderEntity) {
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
folder.uri?.let { uri ->
|
||||
location?.let {
|
||||
Text(
|
||||
text = uri,
|
||||
text = it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
@@ -185,5 +219,16 @@ private fun WatchedFolderRow(folder: FolderEntity) {
|
||||
)
|
||||
}
|
||||
}
|
||||
folder.uri?.let { uri ->
|
||||
IconButton(
|
||||
onClick = { onRescan(uri) },
|
||||
enabled = rescanEnabled,
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Refresh,
|
||||
contentDescription = stringResource(R.string.refresh),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
<string name="dashboard_review_title">%1$d document(s) to review</string>
|
||||
<string name="dashboard_review_hint">Review them in swipe mode: keep (and sync) or delete.</string>
|
||||
<string name="dashboard_all_processed">All up to date — nothing to review.</string>
|
||||
<string name="dashboard_sync_title">Sync</string>
|
||||
|
||||
<!-- Review mode (swipe) -->
|
||||
<string name="review_title">New documents</string>
|
||||
@@ -84,6 +85,10 @@
|
||||
<string name="document_loading">Reading document…</string>
|
||||
<string name="document_cannot_read">Could not read this document.</string>
|
||||
<string name="document_page_unreadable">Unreadable page</string>
|
||||
<string name="focus_tap_to_exit">Tap to exit</string>
|
||||
<string name="login_show_password">Show password</string>
|
||||
<string name="login_hide_password">Hide password</string>
|
||||
<string name="scan_permission_open_settings">Open Settings</string>
|
||||
|
||||
<!-- Server OCR -->
|
||||
<string name="ocr_action">OCR</string>
|
||||
@@ -124,6 +129,18 @@
|
||||
<string name="settings_saf_folders_empty">No watched folders yet.</string>
|
||||
<string name="settings_watched_folders">Watched system folders</string>
|
||||
<string name="settings_watched_folders_hint">View watched folders</string>
|
||||
<string name="settings_theme_choose">Choose theme</string>
|
||||
<string name="settings_server_hint">Configure the server address</string>
|
||||
<string name="settings_sign_in_hint">Sign in to your server</string>
|
||||
<string name="settings_not_connected">Not signed in</string>
|
||||
<string name="settings_disconnect_confirm">Sign out from %1$s?</string>
|
||||
<string name="settings_close">Close</string>
|
||||
<string name="settings_cancel">Cancel</string>
|
||||
<string name="settings_import_done">Import finished</string>
|
||||
|
||||
<!-- Single header status pill + status bottom-sheet -->
|
||||
<string name="status_sheet_title">Connection status</string>
|
||||
<string name="status_sheet_view_queue">View queue</string>
|
||||
<string name="watched_count_many">99+</string>
|
||||
|
||||
<!-- Search -->
|
||||
@@ -132,6 +149,8 @@
|
||||
<string name="search_empty">Type a search or pick a category</string>
|
||||
<string name="search_recent">Recent documents</string>
|
||||
<string name="search_no_results">No results</string>
|
||||
<string name="search_results_count">%1$d result(s)</string>
|
||||
<string name="search_clear">Clear search</string>
|
||||
<string name="category_all">All</string>
|
||||
<string name="category_pdf">PDF</string>
|
||||
<string name="category_office">Office</string>
|
||||
@@ -152,6 +171,7 @@
|
||||
<string name="login_error_generic">Could not sign in right now</string>
|
||||
<string name="login_error_unauthorized">Incorrect username or password</string>
|
||||
<string name="login_skip">Continue without account</string>
|
||||
<string name="login_choice_subtitle">Choose how to use Kazier</string>
|
||||
<string name="skip_message">Local mode — your folders stay on this device and are not synced.</string>
|
||||
|
||||
<!-- Server status (header badge) -->
|
||||
@@ -163,26 +183,31 @@
|
||||
|
||||
<!-- Sync status (badge + outbox list) -->
|
||||
<string name="sync_syncing">Syncing…</string>
|
||||
<string name="sync_pending_count">%1$d pending</string>
|
||||
<string name="sync_pending_count_one">1 pending</string>
|
||||
<string name="sync_pending_count">%1$d to send</string>
|
||||
<string name="sync_pending_count_one">1 to send</string>
|
||||
<string name="sync_idle">Up to date</string>
|
||||
<string name="sync_tap_to_view">Sync — tap to view the operations list</string>
|
||||
<string name="sync_list_title">Sync list</string>
|
||||
<string name="sync_list_empty">No operations yet.</string>
|
||||
<string name="sync_tap_to_view">Status — tap for details</string>
|
||||
<string name="sync_list_title">Sync</string>
|
||||
<string name="sync_list_empty">Nothing here yet.</string>
|
||||
<string name="sync_list_close">Close</string>
|
||||
<string name="sync_summary_total">%1$d operations</string>
|
||||
<string name="sync_summary_pending">%1$d pending</string>
|
||||
<string name="sync_summary_total">%1$d items</string>
|
||||
<string name="sync_summary_pending">%1$d to send</string>
|
||||
<string name="sync_summary_failed">%1$d failed</string>
|
||||
<string name="sync_status_pending">Pending</string>
|
||||
<string name="sync_status_synced">Synced</string>
|
||||
<string name="sync_status_pending">To send</string>
|
||||
<string name="sync_status_synced">Sent</string>
|
||||
<string name="sync_status_failed">Failed</string>
|
||||
<string name="sync_op_create">Create resource</string>
|
||||
<string name="sync_op_create">Added</string>
|
||||
<string name="sync_op_move">Move</string>
|
||||
<string name="sync_op_delete">Delete</string>
|
||||
<string name="sync_op_update">Update</string>
|
||||
<string name="sync_placement_local">Local-only file</string>
|
||||
<string name="sync_placement_cloud">Cloud-only file</string>
|
||||
<string name="sync_placement_local_cloud">Synced file</string>
|
||||
|
||||
<!-- Multi-select + PDF assembly -->
|
||||
<string name="selection_count">%1$d selected</string>
|
||||
<string name="selection_selected">Selected</string>
|
||||
<string name="selection_unselected">Not selected</string>
|
||||
<string name="selection_assemble">Assemble PDF</string>
|
||||
<string name="selection_cancel">Cancel selection</string>
|
||||
|
||||
@@ -217,6 +242,8 @@
|
||||
<string name="pdf_builder_name_hint">e.g. january_invoices</string>
|
||||
<string name="pdf_builder_name_save">Save</string>
|
||||
<string name="pdf_builder_saved">PDF created</string>
|
||||
<string name="pdf_builder_view">View</string>
|
||||
<string name="pdf_builder_search_files">Search files…</string>
|
||||
<string name="pdf_builder_preview">Preview</string>
|
||||
<string name="pdf_builder_close_preview">Close preview</string>
|
||||
<string name="pdf_generated_folder">Generated PDFs</string>
|
||||
@@ -268,6 +295,7 @@
|
||||
<string name="delete_confirm_button">Confirm</string>
|
||||
<string name="delete_cancel">Cancel</string>
|
||||
<string name="delete_error">Error while deleting</string>
|
||||
<string name="delete_success">Items deleted</string>
|
||||
|
||||
<!-- Sharing (share grants) -->
|
||||
<string name="share_title">Share with a user</string>
|
||||
@@ -280,6 +308,7 @@
|
||||
<string name="share_cancel">Cancel</string>
|
||||
<string name="share_error_not_found">No user found with this username.</string>
|
||||
<string name="share_error_generic">Could not share right now.</string>
|
||||
<string name="share_enqueued">Share saved — syncing.</string>
|
||||
<string name="share_content_description">Share this folder</string>
|
||||
<string name="share_action">Share</string>
|
||||
<string name="more_actions">More actions</string>
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
<string name="dashboard_review_title">%1$d document(s) à traiter</string>
|
||||
<string name="dashboard_review_hint">Révise-les en mode swipe : garder (et synchroniser) ou supprimer.</string>
|
||||
<string name="dashboard_all_processed">Tout est à jour — aucun document à traiter.</string>
|
||||
<string name="dashboard_sync_title">Synchronisation</string>
|
||||
|
||||
<!-- Mode review (swipe) -->
|
||||
<string name="review_title">Nouveaux documents</string>
|
||||
@@ -84,6 +85,10 @@
|
||||
<string name="document_loading">Lecture du document…</string>
|
||||
<string name="document_cannot_read">Impossible de lire ce document.</string>
|
||||
<string name="document_page_unreadable">Page illisible</string>
|
||||
<string name="focus_tap_to_exit">Toucher pour quitter</string>
|
||||
<string name="login_show_password">Afficher le mot de passe</string>
|
||||
<string name="login_hide_password">Masquer le mot de passe</string>
|
||||
<string name="scan_permission_open_settings">Ouvrir les Réglages</string>
|
||||
|
||||
<!-- OCR serveur -->
|
||||
<string name="ocr_action">OCR</string>
|
||||
@@ -124,6 +129,18 @@
|
||||
<string name="settings_saf_folders_empty">Aucun dossier surveillé pour le moment.</string>
|
||||
<string name="settings_watched_folders">Dossiers système surveillés</string>
|
||||
<string name="settings_watched_folders_hint">Consulter les dossiers surveillés</string>
|
||||
<string name="settings_theme_choose">Choisir le thème</string>
|
||||
<string name="settings_server_hint">Configurer l\'adresse du serveur</string>
|
||||
<string name="settings_sign_in_hint">Se connecter à ton serveur</string>
|
||||
<string name="settings_not_connected">Non connecté</string>
|
||||
<string name="settings_disconnect_confirm">Se déconnecter du compte %1$s ?</string>
|
||||
<string name="settings_close">Fermer</string>
|
||||
<string name="settings_cancel">Annuler</string>
|
||||
<string name="settings_import_done">Import terminé</string>
|
||||
|
||||
<!-- Pastille statut unique du header + bottom-sheet état -->
|
||||
<string name="status_sheet_title">État de la connexion</string>
|
||||
<string name="status_sheet_view_queue">Voir la file</string>
|
||||
<string name="watched_count_many">99+</string>
|
||||
|
||||
<!-- Recherche -->
|
||||
@@ -132,6 +149,8 @@
|
||||
<string name="search_empty">Saisis une recherche ou choisis une catégorie</string>
|
||||
<string name="search_recent">Documents récents</string>
|
||||
<string name="search_no_results">Aucun résultat</string>
|
||||
<string name="search_results_count">%1$d résultat(s)</string>
|
||||
<string name="search_clear">Effacer la recherche</string>
|
||||
<string name="category_all">Tous</string>
|
||||
<string name="category_pdf">PDF</string>
|
||||
<string name="category_office">Bureautique</string>
|
||||
@@ -152,6 +171,7 @@
|
||||
<string name="login_error_generic">Impossible de se connecter pour le moment</string>
|
||||
<string name="login_error_unauthorized">Nom d\'utilisateur ou mot de passe incorrect</string>
|
||||
<string name="login_skip">Continuer sans compte</string>
|
||||
<string name="login_choice_subtitle">Choisis comment utiliser Kazier</string>
|
||||
<string name="skip_message">Mode local — tes dossiers restent sur cet appareil et ne sont pas synchronisés.</string>
|
||||
|
||||
<!-- Statut serveur (badge du header) -->
|
||||
@@ -163,26 +183,31 @@
|
||||
|
||||
<!-- Statut de synchronisation (badge + liste outbox) -->
|
||||
<string name="sync_syncing">Synchro…</string>
|
||||
<string name="sync_pending_count">%1$d en attente</string>
|
||||
<string name="sync_pending_count_one">1 en attente</string>
|
||||
<string name="sync_pending_count">%1$d à envoyer</string>
|
||||
<string name="sync_pending_count_one">1 à envoyer</string>
|
||||
<string name="sync_idle">À jour</string>
|
||||
<string name="sync_tap_to_view">Synchro — appuyer pour voir la liste des ops</string>
|
||||
<string name="sync_list_title">Liste des sync</string>
|
||||
<string name="sync_list_empty">Aucune opération pour le moment.</string>
|
||||
<string name="sync_tap_to_view">État — appuyer pour voir le détail</string>
|
||||
<string name="sync_list_title">Synchronisation</string>
|
||||
<string name="sync_list_empty">Aucun élément pour le moment.</string>
|
||||
<string name="sync_list_close">Fermer</string>
|
||||
<string name="sync_summary_total">%1$d opérations</string>
|
||||
<string name="sync_summary_pending">%1$d en attente</string>
|
||||
<string name="sync_summary_failed">%1$d échouée(s)</string>
|
||||
<string name="sync_status_pending">En attente</string>
|
||||
<string name="sync_status_synced">Poussée</string>
|
||||
<string name="sync_status_failed">Échouée</string>
|
||||
<string name="sync_op_create">Création de ressource</string>
|
||||
<string name="sync_summary_total">%1$d éléments</string>
|
||||
<string name="sync_summary_pending">%1$d à envoyer</string>
|
||||
<string name="sync_summary_failed">%1$d en échec</string>
|
||||
<string name="sync_status_pending">À envoyer</string>
|
||||
<string name="sync_status_synced">Envoyé</string>
|
||||
<string name="sync_status_failed">En échec</string>
|
||||
<string name="sync_op_create">Ajout</string>
|
||||
<string name="sync_op_move">Déplacement</string>
|
||||
<string name="sync_op_delete">Suppression</string>
|
||||
<string name="sync_op_update">Mise à jour</string>
|
||||
<string name="sync_placement_local">Fichier local uniquement</string>
|
||||
<string name="sync_placement_cloud">Fichier distant uniquement</string>
|
||||
<string name="sync_placement_local_cloud">Fichier synchronisé</string>
|
||||
|
||||
<!-- Sélection multi-fichiers + assemblage PDF -->
|
||||
<string name="selection_count">%1$d sélectionné(s)</string>
|
||||
<string name="selection_selected">Sélectionné</string>
|
||||
<string name="selection_unselected">Non sélectionné</string>
|
||||
<string name="selection_assemble">Assembler en PDF</string>
|
||||
<string name="selection_cancel">Annuler la sélection</string>
|
||||
|
||||
@@ -217,6 +242,8 @@
|
||||
<string name="pdf_builder_name_hint">ex. factures_janvier</string>
|
||||
<string name="pdf_builder_name_save">Enregistrer</string>
|
||||
<string name="pdf_builder_saved">PDF créé</string>
|
||||
<string name="pdf_builder_view">Voir</string>
|
||||
<string name="pdf_builder_search_files">Rechercher un fichier…</string>
|
||||
<string name="pdf_builder_preview">Aperçu</string>
|
||||
<string name="pdf_builder_close_preview">Fermer l\'aperçu</string>
|
||||
<string name="pdf_generated_folder">PDF générés</string>
|
||||
@@ -268,6 +295,7 @@
|
||||
<string name="delete_confirm_button">Confirmer</string>
|
||||
<string name="delete_cancel">Annuler</string>
|
||||
<string name="delete_error">Erreur lors de la suppression</string>
|
||||
<string name="delete_success">Éléments supprimés</string>
|
||||
|
||||
<!-- Partage (share grants) -->
|
||||
<string name="share_title">Partager avec un utilisateur</string>
|
||||
@@ -280,6 +308,7 @@
|
||||
<string name="share_cancel">Annuler</string>
|
||||
<string name="share_error_not_found">Aucun utilisateur connu sous ce nom.</string>
|
||||
<string name="share_error_generic">Impossible de partager pour le moment.</string>
|
||||
<string name="share_enqueued">Partage enregistré — synchronisation en cours.</string>
|
||||
<string name="share_content_description">Partager ce dossier</string>
|
||||
<string name="share_action">Partager</string>
|
||||
<string name="more_actions">Plus d\'actions</string>
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.kazier.mobile.data.local.dao
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.kazier.mobile.data.local.AppDatabase
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/**
|
||||
* m7 : la recherche `LIKE` échappe `%`/`_` (littéraux, pas des jokers) —
|
||||
* « 100% » ne matchait pas tout avant le fix. La casse ASCII reste
|
||||
* insensible (`COLLATE NOCASE`).
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class SearchEscapeTest {
|
||||
|
||||
private lateinit var db: AppDatabase
|
||||
private lateinit var fileDao: FileDao
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||
.allowMainThreadQueries()
|
||||
.build()
|
||||
fileDao = db.fileDao()
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
db.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pourcentage_litteral_ne_match_pas_tout() = runTest {
|
||||
fileDao.upsert(file("a".repeat(32), "100%.txt"))
|
||||
fileDao.upsert(file("b".repeat(32), "a_b.txt"))
|
||||
fileDao.upsert(file("c".repeat(32), "normal.txt"))
|
||||
|
||||
// Le repository échappe avant d'appeler le DAO — on rejoue ici le
|
||||
// contrat (`escapeLike`) pour verrouiller le comportement SQL.
|
||||
val escaped = "100%".escapeLikeForTest()
|
||||
val rows = fileDao.searchWithFilters(escaped, null).first()
|
||||
|
||||
assertEquals(listOf("100%.txt"), rows.map { it.name })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun underscore_litteral_ne_match_pas_tout() = runTest {
|
||||
fileDao.upsert(file("a".repeat(32), "100%.txt"))
|
||||
fileDao.upsert(file("b".repeat(32), "a_b.txt"))
|
||||
fileDao.upsert(file("c".repeat(32), "axb.txt"))
|
||||
|
||||
val rows = fileDao.searchWithFilters("a\\_b", null).first()
|
||||
|
||||
assertEquals(listOf("a_b.txt"), rows.map { it.name })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun recherche_insensible_a_la_casse_ascii() = runTest {
|
||||
fileDao.upsert(file("a".repeat(32), "Rapport.TXT"))
|
||||
|
||||
val rows = fileDao.searchWithFilters("rapport", null).first()
|
||||
|
||||
assertEquals(listOf("Rapport.TXT"), rows.map { it.name })
|
||||
}
|
||||
|
||||
private fun file(resourceId: String, name: String) = FileEntity(
|
||||
resourceId = resourceId,
|
||||
name = name,
|
||||
folderResourceId = "f".repeat(32),
|
||||
size = 10L,
|
||||
exists = 1,
|
||||
addedAt = NOW,
|
||||
updatedAt = NOW,
|
||||
)
|
||||
|
||||
/** Miroir de `escapeLike` (interne au main) : `%`/`_`/`\` échappés. */
|
||||
private fun String.escapeLikeForTest(): String =
|
||||
replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
|
||||
private companion object {
|
||||
const val NOW = 1_700_000_000_000L
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.kazier.mobile.data.local.migration
|
||||
|
||||
import android.content.Context
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import androidx.sqlite.db.SupportSQLiteOpenHelper
|
||||
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/**
|
||||
* M13 : la migration 14→15 backfill `exists` NULL→1 sur `folders` et `files`.
|
||||
* Les lignes insérées sans `exists` explicite (défaut Kotlin `null` avant ce
|
||||
* fix) étaient invisibles des requêtes `WHERE exists = 1` — elles
|
||||
* réapparaissent comme présentes, état le plus sûr (le walk les re-marque
|
||||
* `exists = 0` si elles ont vraiment disparu). Les lignes déjà à 0/1 sont
|
||||
* intactes.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class Migration14To15Test {
|
||||
|
||||
@Test
|
||||
fun migration_backfill_exists_null_vers_1_sans_toucher_les_lignes_renseignees() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val helper = FrameworkSQLiteOpenHelperFactory().create(
|
||||
SupportSQLiteOpenHelper.Configuration.builder(context)
|
||||
.name(null)
|
||||
.callback(V14Callback())
|
||||
.build(),
|
||||
)
|
||||
val db = helper.writableDatabase
|
||||
db.execSQL(
|
||||
"INSERT INTO `folders` (`resource_id`, `name`, `exists`, `sync_status`, `added_at`, `updated_at`) " +
|
||||
"VALUES ('f-null', 'Null', NULL, 'local', 1, 1), ('f-zero', 'Zero', 0, 'local', 1, 1), ('f-one', 'One', 1, 'local', 1, 1)",
|
||||
)
|
||||
db.execSQL(
|
||||
"INSERT INTO `files` (`resource_id`, `name`, `folder_resource_id`, `size`, `exists`, `added_at`, `updated_at`) " +
|
||||
"VALUES ('d-null', 'n.txt', 'f-one', 10, NULL, 1, 1), ('d-zero', 'z.txt', 'f-one', 10, 0, 1, 1)",
|
||||
)
|
||||
|
||||
val migration = Migrations.ALL.first { it.startVersion == 14 && it.endVersion == 15 }
|
||||
migration.migrate(db)
|
||||
|
||||
db.query("SELECT `resource_id`, `exists` FROM `folders` ORDER BY `resource_id`").use { cursor ->
|
||||
val rows = mutableMapOf<String, Int>()
|
||||
while (cursor.moveToNext()) rows[cursor.getString(0)] = cursor.getInt(1)
|
||||
assertEquals(mapOf("f-null" to 1, "f-one" to 1, "f-zero" to 0), rows)
|
||||
}
|
||||
db.query("SELECT `resource_id`, `exists` FROM `files` ORDER BY `resource_id`").use { cursor ->
|
||||
val rows = mutableMapOf<String, Int>()
|
||||
while (cursor.moveToNext()) rows[cursor.getString(0)] = cursor.getInt(1)
|
||||
assertEquals(mapOf("d-null" to 1, "d-zero" to 0), rows)
|
||||
}
|
||||
helper.close()
|
||||
}
|
||||
|
||||
/** Schéma v14 minimal de `folders`/`files` (colonne `exists` nullable). */
|
||||
private class V14Callback : SupportSQLiteOpenHelper.Callback(14) {
|
||||
override fun onCreate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL(
|
||||
"CREATE TABLE `folders` (" +
|
||||
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
|
||||
"`resource_id` TEXT NOT NULL, " +
|
||||
"`uri` TEXT, " +
|
||||
"`name` TEXT NOT NULL, " +
|
||||
"`exists` INTEGER, " +
|
||||
"`parent_resource_id` TEXT, " +
|
||||
"`owner_id` TEXT, " +
|
||||
"`sync_status` TEXT NOT NULL, " +
|
||||
"`created_in_app` INTEGER NOT NULL DEFAULT 0, " +
|
||||
"`added_at` INTEGER NOT NULL, " +
|
||||
"`updated_at` INTEGER NOT NULL)",
|
||||
)
|
||||
db.execSQL(
|
||||
"CREATE TABLE `files` (" +
|
||||
"`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
|
||||
"`resource_id` TEXT NOT NULL, " +
|
||||
"`uri` TEXT, " +
|
||||
"`name` TEXT NOT NULL, " +
|
||||
"`folder_resource_id` TEXT NOT NULL, " +
|
||||
"`extension` TEXT, " +
|
||||
"`size` INTEGER NOT NULL, " +
|
||||
"`mime_type` TEXT, " +
|
||||
"`exists` INTEGER, " +
|
||||
"`added_at` INTEGER NOT NULL, " +
|
||||
"`updated_at` INTEGER NOT NULL)",
|
||||
)
|
||||
}
|
||||
|
||||
override fun onUpgrade(
|
||||
db: SupportSQLiteDatabase,
|
||||
oldVersion: Int,
|
||||
newVersion: Int,
|
||||
) = Unit
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.kazier.mobile.data.local.migration
|
||||
|
||||
import android.content.Context
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import androidx.sqlite.db.SupportSQLiteOpenHelper
|
||||
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/**
|
||||
* M27 : la migration 15→16 crée la table `resource_permissions` (cache du
|
||||
* snapshot `GET /sync/permissions`, fondement de `canAccess`) + son index
|
||||
* `expires_at`. Une coquille SQL briquerait l'app au démarrage après update.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class Migration15To16Test {
|
||||
|
||||
@Test
|
||||
fun migration_cree_la_table_et_l_index() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
val helper = FrameworkSQLiteOpenHelperFactory().create(
|
||||
SupportSQLiteOpenHelper.Configuration.builder(context)
|
||||
.name(null)
|
||||
.callback(EmptyV15Callback())
|
||||
.build(),
|
||||
)
|
||||
val db = helper.writableDatabase
|
||||
|
||||
val migration = Migrations.ALL.first { it.startVersion == 15 && it.endVersion == 16 }
|
||||
migration.migrate(db)
|
||||
|
||||
val tables = mutableListOf<String>()
|
||||
db.query(
|
||||
"SELECT `name` FROM `sqlite_master` WHERE `type` = 'table' AND `name` = 'resource_permissions'",
|
||||
).use { cursor ->
|
||||
while (cursor.moveToNext()) tables += cursor.getString(0)
|
||||
}
|
||||
assertTrue("table resource_permissions manquante", tables.contains("resource_permissions"))
|
||||
|
||||
val columns = mutableListOf<String>()
|
||||
db.query("PRAGMA table_info(`resource_permissions`)").use { cursor ->
|
||||
val nameIdx = cursor.getColumnIndexOrThrow("name")
|
||||
while (cursor.moveToNext()) columns += cursor.getString(nameIdx)
|
||||
}
|
||||
for (expected in listOf(
|
||||
"resource_id", "resource_type", "effective_access", "owner_id",
|
||||
"shared_by_id", "expires_at", "cached_at", "updated_at",
|
||||
)) {
|
||||
assertTrue("colonne $expected manquante", columns.contains(expected))
|
||||
}
|
||||
|
||||
var indexFound = false
|
||||
db.query("PRAGMA index_list(`resource_permissions`)").use { cursor ->
|
||||
val nameIdx = cursor.getColumnIndexOrThrow("name")
|
||||
while (cursor.moveToNext()) {
|
||||
if (cursor.getString(nameIdx) == "index_resource_permissions_expires_at") {
|
||||
indexFound = true
|
||||
}
|
||||
}
|
||||
}
|
||||
assertTrue("index expires_at manquant", indexFound)
|
||||
helper.close()
|
||||
}
|
||||
|
||||
private class EmptyV15Callback : SupportSQLiteOpenHelper.Callback(15) {
|
||||
override fun onCreate(db: SupportSQLiteDatabase) = Unit
|
||||
|
||||
override fun onUpgrade(
|
||||
db: SupportSQLiteDatabase,
|
||||
oldVersion: Int,
|
||||
newVersion: Int,
|
||||
) = Unit
|
||||
}
|
||||
}
|
||||
+19
@@ -11,6 +11,7 @@ import com.kazier.mobile.data.local.dao.FileDao
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.data.local.entity.FileStatus
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import com.kazier.mobile.data.remote.ApiException
|
||||
import com.kazier.mobile.data.remote.ApiService
|
||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
@@ -109,6 +110,24 @@ class OcrRepositoryTest {
|
||||
assertEquals("bonjour monde", stored?.ocrText)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `poll_timeout_si_job_bloque_en_processing`() = runTest {
|
||||
// m20 : un job resté `processing` (stale claim serveur) ne tient plus
|
||||
// la coroutine indéfiniment — `OCR_TIMEOUT` au bout du timeout.
|
||||
apiService.jobSequence = listOf(
|
||||
OcrJobDto(id = "job-stuck", status = OcrJobStatus.PROCESSING),
|
||||
)
|
||||
|
||||
var progressCalls = 0
|
||||
val ex = runCatching {
|
||||
repository.poll("job-stuck", timeoutMs = 0) { progressCalls++ }
|
||||
}.exceptionOrNull()
|
||||
|
||||
assertTrue(ex is ApiException)
|
||||
assertEquals("OCR_TIMEOUT", (ex as ApiException).code)
|
||||
assertEquals(1, progressCalls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `poll_stop_sur_un_job_failed_et_remonte_lerreur`() = runTest {
|
||||
apiService.jobSequence = listOf(
|
||||
|
||||
+143
-16
@@ -232,22 +232,146 @@ class ShareRepositoryTest {
|
||||
assertEquals(1, folderDao.getByResourceId("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")!!.exists)
|
||||
}
|
||||
|
||||
// --- delta / TTL (M27) ---------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun premier_pull_complet_puis_delta() = runTest {
|
||||
apiService.permissions = listOf(
|
||||
perm(id = FOLDER_ID, type = "folder", access = "viewer", name = "S", parentId = null),
|
||||
)
|
||||
|
||||
shareRepository.syncSnapshot()
|
||||
assertNull("premier pull : snapshot complet (after=null)", apiService.lastAfter)
|
||||
|
||||
shareRepository.syncSnapshot()
|
||||
assertTrue(
|
||||
"second pull : delta (after=cachedAt)",
|
||||
apiService.lastAfter != null,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun forceFull_repasse_en_complet_meme_avec_cache() = runTest {
|
||||
apiService.permissions = emptyList()
|
||||
|
||||
shareRepository.syncSnapshot()
|
||||
shareRepository.syncSnapshot(forceFull = true)
|
||||
|
||||
assertNull("forceFull : snapshot complet (after=null)", apiService.lastAfter)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun delta_ne_fait_pas_converger_les_absents() = runTest {
|
||||
// Pull complet initial avec une ressource partagée…
|
||||
activeUserStore.set(CURRENT_USER)
|
||||
apiService.permissions = listOf(
|
||||
perm(id = FOLDER_ID, type = "folder", access = "viewer", name = "S", parentId = null),
|
||||
)
|
||||
shareRepository.syncSnapshot()
|
||||
assertEquals(1, folderDao.getByResourceId(FOLDER_ID)!!.exists)
|
||||
|
||||
// …puis delta vide : la ressource NE doit pas être marquée disparue
|
||||
// (un delta ne contient que les changements, pas l'état complet).
|
||||
apiService.permissions = emptyList()
|
||||
shareRepository.syncSnapshot()
|
||||
|
||||
assertEquals(1, folderDao.getByResourceId(FOLDER_ID)!!.exists)
|
||||
}
|
||||
|
||||
// --- expiration (M27) ------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun grant_expire_masque_la_ligne_au_lieu_d_hydrater() = runTest {
|
||||
activeUserStore.set(CURRENT_USER)
|
||||
folderDao.upsert(folder(FOLDER_ID, uri = null, ownerId = OTHER_USER))
|
||||
apiService.permissions = listOf(
|
||||
perm(
|
||||
id = FOLDER_ID, type = "folder", access = "viewer", name = "S", parentId = null,
|
||||
expiresAt = NOW - 1_000L,
|
||||
),
|
||||
)
|
||||
|
||||
shareRepository.syncSnapshot()
|
||||
|
||||
assertEquals(0, folderDao.getByResourceId(FOLDER_ID)!!.exists)
|
||||
}
|
||||
|
||||
// --- canAccess (M27) ---------------------------------------------------------
|
||||
|
||||
@Test
|
||||
fun canAccess_ownership_rang_expiration() = runTest {
|
||||
activeUserStore.set(CURRENT_USER)
|
||||
// Ressource possédée localement → owner implicite.
|
||||
folderDao.upsert(folder(OWNED_ID, uri = null, ownerId = CURRENT_USER))
|
||||
// Grants partagés.
|
||||
apiService.permissions = listOf(
|
||||
perm(id = FOLDER_ID, type = "folder", access = "editor", name = "E", parentId = null),
|
||||
perm(id = FILE_ID, type = "file", access = "viewer", name = "v.pdf", parentId = FOLDER_ID),
|
||||
)
|
||||
shareRepository.syncSnapshot()
|
||||
|
||||
assertTrue(shareRepository.canAccess(OWNED_ID, "editor"))
|
||||
assertTrue(shareRepository.canAccess(FOLDER_ID, "editor"))
|
||||
assertTrue("viewer suffit pour viewer", shareRepository.canAccess(FILE_ID, "viewer"))
|
||||
assertFalse("viewer < editor", shareRepository.canAccess(FILE_ID, "editor"))
|
||||
assertFalse("ressource inconnue", shareRepository.canAccess("d".repeat(32), "viewer"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun canAccess_grant_expire_refuse() = runTest {
|
||||
activeUserStore.set(CURRENT_USER)
|
||||
apiService.permissions = listOf(
|
||||
perm(
|
||||
id = FOLDER_ID, type = "folder", access = "editor", name = "E", parentId = null,
|
||||
expiresAt = NOW - 1_000L,
|
||||
),
|
||||
)
|
||||
shareRepository.syncSnapshot()
|
||||
|
||||
assertFalse("grant expiré : pas d'accès", shareRepository.canAccess(FOLDER_ID, "viewer"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun canAccess_snapshot_perime_downgrade_lecture_seule() = runTest {
|
||||
activeUserStore.set(CURRENT_USER)
|
||||
apiService.permissions = listOf(
|
||||
perm(id = FOLDER_ID, type = "folder", access = "editor", name = "E", parentId = null),
|
||||
)
|
||||
shareRepository.syncSnapshot()
|
||||
assertTrue(shareRepository.canAccess(FOLDER_ID, "editor"))
|
||||
|
||||
// Simule un cache périmé (TTL 24h dépassé sans reseed).
|
||||
val stale = db.resourcePermissionDao().getByResourceId(FOLDER_ID)!!
|
||||
db.resourcePermissionDao().upsertAll(
|
||||
listOf(stale.copy(cachedAt = System.currentTimeMillis() - ShareRepository.PERMISSION_TTL_MS - 1)),
|
||||
)
|
||||
|
||||
assertTrue("stale : lecture conservée", shareRepository.canAccess(FOLDER_ID, "viewer"))
|
||||
assertFalse("stale : écriture refusée", shareRepository.canAccess(FOLDER_ID, "editor"))
|
||||
}
|
||||
|
||||
// --- fixtures ------------------------------------------------------------
|
||||
|
||||
private fun perm(id: String, type: String, access: String, name: String, parentId: String?) =
|
||||
ResourcePermissionDto(
|
||||
resourceId = id.padEnd(32, '0'),
|
||||
resourceType = type,
|
||||
effectiveAccess = access,
|
||||
inherit = true,
|
||||
ownerId = OTHER_USER,
|
||||
sharedById = OWNER_ID,
|
||||
expiresAt = null,
|
||||
cachedAt = NOW,
|
||||
updatedAt = NOW,
|
||||
name = name,
|
||||
parentId = parentId?.padEnd(32, '0'),
|
||||
)
|
||||
private fun perm(
|
||||
id: String,
|
||||
type: String,
|
||||
access: String,
|
||||
name: String,
|
||||
parentId: String?,
|
||||
expiresAt: Long? = null,
|
||||
) = ResourcePermissionDto(
|
||||
resourceId = id.padEnd(32, '0'),
|
||||
resourceType = type,
|
||||
effectiveAccess = access,
|
||||
inherit = true,
|
||||
ownerId = OTHER_USER,
|
||||
sharedById = OWNER_ID,
|
||||
expiresAt = expiresAt,
|
||||
cachedAt = NOW,
|
||||
updatedAt = NOW,
|
||||
name = name,
|
||||
parentId = parentId?.padEnd(32, '0'),
|
||||
)
|
||||
|
||||
private fun folder(id: String, uri: String?, ownerId: String?) = FolderEntity(
|
||||
resourceId = id.padEnd(32, '0'),
|
||||
@@ -290,6 +414,7 @@ class ShareRepositoryTest {
|
||||
/** Fake `ApiService` — uniquement le snapshot est réellement consommé. */
|
||||
private class FakeApiService : ApiService {
|
||||
var permissions: List<ResourcePermissionDto> = emptyList()
|
||||
var lastAfter: Long? = null
|
||||
|
||||
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
@@ -319,8 +444,10 @@ private class FakeApiService : ApiService {
|
||||
|
||||
override suspend fun syncPermissions(
|
||||
after: Long?,
|
||||
): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
|
||||
Response.success(ApiEnvelope(data = permissions))
|
||||
): Response<ApiEnvelope<List<ResourcePermissionDto>>> {
|
||||
lastAfter = after
|
||||
return Response.success(ApiEnvelope(data = permissions))
|
||||
}
|
||||
|
||||
override suspend fun uploadFile(
|
||||
file: MultipartBody.Part,
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.kazier.mobile.features.saf
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import com.kazier.mobile.data.local.AppDatabase
|
||||
import com.kazier.mobile.data.local.dao.PendingOperationDao
|
||||
import com.kazier.mobile.data.local.entity.PendingOperationType
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import com.kazier.mobile.data.remote.ApiService
|
||||
import com.kazier.mobile.data.repository.FileRepository
|
||||
import com.kazier.mobile.data.repository.FolderRepository
|
||||
import com.kazier.mobile.data.repository.OutboxRepository
|
||||
import com.kazier.mobile.data.repository.SaveFileInput
|
||||
import com.kazier.mobile.data.repository.SaveFolderInput
|
||||
import com.kazier.mobile.domain.ActiveUserStore
|
||||
import com.kazier.mobile.domain.DeviceIdentity
|
||||
import com.kazier.mobile.domain.GenerateId
|
||||
import com.kazier.mobile.features.thumbnails.ThumbnailStore
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import retrofit2.Retrofit
|
||||
import retrofit2.converter.moshi.MoshiConverterFactory
|
||||
|
||||
/**
|
||||
* M5 : `deleteInCloud` journalise `delete_resource` ET pose la tombstone
|
||||
* locale (`exists = 0`) dans la même transaction — sans ça la ressource
|
||||
* restait affichée et le walk la revoyait (fantôme local vs serveur supprimé).
|
||||
* - fichier déjà poussé (create synced) → `delete_resource` + `exists = 0` ;
|
||||
* - fichier jamais poussé → pas de `delete_resource`, mais `exists = 0` ;
|
||||
* - dossier poussé → dossier + descendance en `exists = 0`, deletes journalisés.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class DeleteInCloudTest {
|
||||
|
||||
private lateinit var context: Context
|
||||
private lateinit var db: AppDatabase
|
||||
private lateinit var opsDao: PendingOperationDao
|
||||
private lateinit var fileRepository: FileRepository
|
||||
private lateinit var folderRepository: FolderRepository
|
||||
private lateinit var outboxRepository: OutboxRepository
|
||||
private lateinit var fileDeleter: FileDeleter
|
||||
private lateinit var folderDeleter: FolderDeleter
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
context = ApplicationProvider.getApplicationContext()
|
||||
db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java)
|
||||
.allowMainThreadQueries()
|
||||
.build()
|
||||
opsDao = db.pendingOperationDao()
|
||||
|
||||
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||
val apiService = Retrofit.Builder()
|
||||
.baseUrl("http://localhost:1/")
|
||||
.addConverterFactory(MoshiConverterFactory.create(moshi))
|
||||
.build()
|
||||
.create(ApiService::class.java)
|
||||
val apiClient = ApiClient(apiService, moshi)
|
||||
val generateId = GenerateId()
|
||||
val deviceIdentity = DeviceIdentity(db.userPreferenceDao(), generateId)
|
||||
val activeUserStore = ActiveUserStore(db.userPreferenceDao())
|
||||
|
||||
outboxRepository = OutboxRepository(opsDao, generateId, deviceIdentity, moshi)
|
||||
fileRepository = FileRepository(db.fileDao(), db.folderDao(), apiClient, generateId, db, outboxRepository)
|
||||
folderRepository = FolderRepository(db.folderDao(), apiClient, generateId, activeUserStore, db, outboxRepository)
|
||||
val thumbnails = ThumbnailStore(context)
|
||||
fileDeleter = FileDeleter(context, fileRepository, outboxRepository, db, thumbnails)
|
||||
folderDeleter = FolderDeleter(context, folderRepository, fileRepository, outboxRepository, db, thumbnails)
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
db.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fichier_pousse_delete_cloud_pose_tombstone_et_journalise() = runTest {
|
||||
val folder = folderRepository.saveFolder(SaveFolderInput(uri = FOLDER_URI, name = "R", exists = true))
|
||||
fileRepository.saveLocalFile(
|
||||
input = SaveFileInput(uri = FILE_URI, name = "a.txt", size = 10, resourceId = FILE_ID, processed = true),
|
||||
folderResourceId = folder.resourceId,
|
||||
)
|
||||
markSynced(FILE_ID, PendingOperationType.CREATE_RESOURCE)
|
||||
|
||||
val report = fileDeleter.deleteFiles(
|
||||
listOf(db.fileDao().getByResourceId(FILE_ID)!!),
|
||||
FileDeleter.DeleteMode.IN_CLOUD,
|
||||
)
|
||||
|
||||
assertEquals(1, report.succeeded)
|
||||
assertEquals(0, db.fileDao().getByResourceId(FILE_ID)!!.exists)
|
||||
val deletes = opsDao.selectPending(100).filter {
|
||||
it.resourceId == FILE_ID && it.operation == PendingOperationType.DELETE_RESOURCE
|
||||
}
|
||||
assertEquals(1, deletes.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fichier_jamais_pousse_delete_cloud_sans_delete_resource_mais_masque() = runTest {
|
||||
val folder = folderRepository.saveFolder(SaveFolderInput(uri = FOLDER_URI, name = "R", exists = true))
|
||||
fileRepository.saveLocalFile(
|
||||
input = SaveFileInput(uri = FILE_URI, name = "a.txt", size = 10, resourceId = FILE_ID, processed = false),
|
||||
folderResourceId = folder.resourceId,
|
||||
)
|
||||
|
||||
val report = fileDeleter.deleteFiles(
|
||||
listOf(db.fileDao().getByResourceId(FILE_ID)!!),
|
||||
FileDeleter.DeleteMode.IN_CLOUD,
|
||||
)
|
||||
|
||||
assertEquals(1, report.succeeded)
|
||||
assertEquals(0, db.fileDao().getByResourceId(FILE_ID)!!.exists)
|
||||
val deletes = opsDao.selectPending(100).filter {
|
||||
it.resourceId == FILE_ID && it.operation == PendingOperationType.DELETE_RESOURCE
|
||||
}
|
||||
assertTrue("jamais poussé : aucun delete_resource", deletes.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dossier_pousse_delete_cloud_masque_tout_l_arbre() = runTest {
|
||||
val folder = folderRepository.saveFolder(SaveFolderInput(uri = FOLDER_URI, name = "R", exists = true))
|
||||
fileRepository.saveLocalFile(
|
||||
input = SaveFileInput(uri = FILE_URI, name = "a.txt", size = 10, resourceId = FILE_ID, processed = true),
|
||||
folderResourceId = folder.resourceId,
|
||||
)
|
||||
markSynced(folder.resourceId, PendingOperationType.CREATE_RESOURCE)
|
||||
markSynced(FILE_ID, PendingOperationType.CREATE_RESOURCE)
|
||||
|
||||
val report = folderDeleter.deleteFolders(
|
||||
listOf(db.folderDao().getByResourceId(folder.resourceId)!!),
|
||||
FileDeleter.DeleteMode.IN_CLOUD,
|
||||
)
|
||||
|
||||
assertEquals(1, report.succeeded)
|
||||
assertEquals(0, db.folderDao().getByResourceId(folder.resourceId)!!.exists)
|
||||
assertEquals(0, db.fileDao().getByResourceId(FILE_ID)!!.exists)
|
||||
val deletes = opsDao.selectPending(100).filter {
|
||||
it.operation == PendingOperationType.DELETE_RESOURCE
|
||||
}.map { it.resourceId }.toSet()
|
||||
assertTrue(deletes.contains(folder.resourceId))
|
||||
assertTrue(deletes.contains(FILE_ID))
|
||||
}
|
||||
|
||||
private suspend fun markSynced(resourceId: String, operation: String) {
|
||||
val op = opsDao.selectPending(100).first {
|
||||
it.resourceId == resourceId && it.operation == operation
|
||||
}
|
||||
opsDao.markSynced(op.id, NOW)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val NOW = 1_700_000_000_000L
|
||||
const val FOLDER_URI = "content://tree/root"
|
||||
const val FILE_URI = "content://tree/root/a.txt"
|
||||
const val FILE_ID = "aabbccddeeff11223344556677889900"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user