diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ce8e14..5085950 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ Le format suit [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/) et le ve - Outbox : ops `trash_resource` / `restore_resource` / `purge_resource` (owner-only, `delete_resource` legacy mappé vers trash, même idempotence) ; purge d'octets best-effort côté serveur. - Migrations `000017` (index corbeille) + `000018` (versions), contrat `docs/api-v1.md` §3/§6.1 étendu, test de contrat `router_test.go`. - Extract générique V3 (S2 backend) : package `extract` (règles FR stdlib — dates/échéances/périodes/montants/émetteurs/références masquées/`doc_type` suggéré, confiances, corpus testé), table `resource_facts` (migration `000019`, `origin` auto/user), hook worker OCR (`OnText` + backfill boot borné, best-effort, anti-panic), `GET /files/:id/facts` (viewer+, `[]` si vide, 404 si trashé/étranger). +- Corrections V3 (S3) : `PATCH /files/:id/facts` + op `correct_facts` (full-replace du jeu `user`, editor+, validation Go → 400 jamais 500), Room v20 (`resource_facts` + `FactsDao`, migration 19→20), fiche « Ce qu'on a compris » sur le viewer (chips, confiance grisée + suggéré, édition par type, reset auto), `FactsRepository` (sync remplace-en-bloc, correction optimiste + outbox atomique), `GET /files/:id/facts` consommé côté client. - Corbeille V3 (S1 mobile, Room v19) : colonne `trashed_at` (files + folders, migration 18→19), tombstone `exists = 0` (requêtes `exists = 1` inchangées), `FileDeleter`/`FolderDeleter`/`SafFileDeleter` → ops `trash_resource` (plus de `delete_resource` émis), garde walk anti-résurrection + reconcile, `TrashRepository` (restore/purge/convergence `GET /trash`/expiration locale 31j), écran Corbeille (Réglages → restore/purge avec confirmation), expiration tombstones dans `RetentionWorker`, dialogue de suppression rewordé (corbeille 30j, plus « irréversible »). ## [1.1.0] - 2026-09-25 diff --git a/V3.md b/V3.md index d088aaf..4300f81 100644 --- a/V3.md +++ b/V3.md @@ -16,7 +16,7 @@ Statut : **vision validée** (2026-09-25). V1 (1.0.0, socle local-first + partag | # | Pilier | Promesse | Réutilise | |---|---|---|---| | P1 | Filet anti-perte | Corbeille 30j + versions N=3 | `deleted_at` soft-delete, `UPLOAD_DIR//.`, overwrite ciblée V2 | -| P2 | Extract générique | Faits universels + type suggéré, validés dans le review existant | Pipeline `upload ciblé → Tesseract → resources.ocr_text → GET /files/:id/ocr`, gate `processed` | +| P2 | Extract générique | Faits universels + type suggéré, corrigés depuis la fiche document | Pipeline `upload ciblé → Tesseract → resources.ocr_text → GET /files/:id/ocr`, gate `processed` | | P3 | Recherche | FTS nom+ocr+faits, facettes, offline | `FileDao.searchWithFilters` (LIKE+accents), `GET /files/search` serveur | | P4 | Relations doc | `same_scan` (sûr) + doublons/versions/même-émetteur (invalidables), collections virtuelles | `scan_sessions`+`scan_pages`, `content_hash` (V2.md), versions P1 | | P5 | Partage sobre | Cercles (groupes V2-6), liens à expiration par défaut, révocation tokens, quota/3-2-1 visible | Snapshot permissions + TTL 24h, `share`/`create_link`, `PATCH /users/me/password` | @@ -75,16 +75,17 @@ Sans ces 4 items, les piliers grincent. Ils sont petits et intégrés aux slices ## 4. Mobile — plan fichier par fichier -### 4.1 Room (v19 → v20, `AppDatabase.kt`, `Migrations.kt`, `app/schemas/` exporté, tests `MigrationXToYTest`) +### 4.1 Room (v19 → v20 faits, v21 FTS — voir S3/S4, `app/schemas/` exporté, tests `MigrationXToYTest`) -- v19 : `resource_facts (id, resource_id FK CASCADE, fact_type, value_text, value_num, value_date, confidence, origin, updated_at)` + `resource_links (id, from_id, to_id, link_type, confidence, created_by)` + miroir `trashed_at` + `is_favorite` sur `files` (colonne, pas table — un flag suffit). DAO `FactsDao`, `LinksDao`. -- v20 : FTS4 `files_fts (name, ocr_text, facts_text)` + triggers sync + requête `searchDocuments(query, facets)` remplaçant `searchWithFilters` pour les docs (garder l'ancien pour dossiers). `facts_text` = concat des `value_text` — reconstruit à chaque sync facts. +- v19 (S1, livré) : `trashed_at` sur files + folders. +- v20 (S3, livré) : `resource_facts (id, resource_id, fact_type, value_text, value_num, value_date, confidence, origin, updated_at)` + `FactsDao` (remplacement en bloc au sync, corrections `user` poussées en outbox). `resource_links`, `is_favorite` et collections → S5. +- v21 (S4) : FTS4 `files_fts (name, ocr_text, facts_text)` + triggers sync + requête `searchDocuments(query, facets)` remplaçant `searchWithFilters` pour les docs (garder l'ancien pour dossiers). `facts_text` = concat des `value_text` — reconstruit à chaque sync facts. - `OutboxRepository.kt` : `enqueueTrash/restore/purge`, `enqueueCorrectFacts` (payload `[{fact_type, value}]`, `GenerateId` 32-hex, même transaction Room que la mutation parente — contrat outbox atomique inchangé). `delete_resource` existant → renommé en trash côté appelants (`FileDeleter`, `FolderDeleter`). ### 4.2 Review = moment de vérité (zéro écran en plus) - `OcrRepository.syncFromServer` : après `ocr_text`, rapatrier `GET /files/:id/facts` → Room (même pattern `syncFromServer`, poll existant réutilisé). -- Écran review existant (`FilePendingReviewBadge` + flow « garder ») : ajouter section « Ce qu'on a compris » — chips `Émetteur: EDF • 84,20 € • Échéance: 12/04 (suggéré)` + correction en un tap → `enqueueCorrectFacts` dans la **même transaction** que `markProcessed` (le `create_resource` et la correction partent ensemble — pas d'état intermédiaire). +- Fiche document (livré S3 — pas le review : le deck ne contient que des fichiers jamais OCR-és, sans faits) : fiche « Ce qu'on a compris » (`FactsBottomSheet`, bouton viewer si `processed`) — chips `Émetteur: EDF • 84,20 € • Échéance: 12/04 (suggéré)`, confiance < 0.5 grisée, user gagne par type à l'affichage, édition par type (texte/nombre/date ISO) → `enqueueCorrectFacts` dans la **même transaction** que l'écriture Room optimiste, reset « rétablir auto » (jeu vide poussé). - Fiche document : section « Voir aussi » (`LinksDao` → `same_scan` d'abord avec badge « sûr », puis autres avec bouton invalider) + section « Faits » (grisé si `confidence < 0.5`). ### 4.3 Relations `same_scan` (déterministe, local) @@ -104,10 +105,10 @@ Sans ces 4 items, les piliers grincent. Ils sont petits et intégrés aux slices ## 5. Ordre d'exécution (7–9 semaines, chaque ligne = shippable) -1. **S1 — Filet + A3** (BE `000017/000018` + trash/restore/purge + cron purge 30j + mobile v19 partiel + `FileDeleter` → trash + garde walk `hasPendingTrash` + écran Corbeille) — done quand : supprimer → restaure depuis un 2e device, le walk ne ressuscite pas. -2. **S2 — Extract générique** (`extract/rules.go` + `service/extract.go` + `000019` + `UpsertAuto` + `GET /files/:id/facts`) — done quand : un scan EDF propose émetteur/montant/échéance. -3. **S3 — Review + correction** (mobile v19 facts + chips review + `correct_facts` + `PATCH /files/:id/facts` + B4 a11y du review) — done quand : corriger en un tap converge serveur ↔ 2e device. -4. **S4 — Recherche** (`000022` FTS + facettes serveur + Room FTS v20 + barre à chips + B4 a11y facettes) — done quand : « facture edf mars » trouve `scan_042.pdf` offline ET online. +1. **S1 — Filet + A3** (livré : BE `000017/000018` + trash/restore/purge + cron purge 30j + mobile v19 + `FileDeleter` → trash + gardes walk + écran Corbeille) — done quand : supprimer → restaure depuis un 2e device, le walk ne ressuscite pas. +2. **S2 — Extract générique** (livré : `extract/rules.go` + `service/extract.go` + `000019` + `UpsertAuto` + `GET /files/:id/facts`) — done quand : un scan EDF propose émetteur/montant/échéance. +3. **S3 — Fiche + correction** (livré : `PATCH /files/:id/facts` + op `correct_facts` editor+ + Room v20 facts + fiche viewer + `FactsRepository` + B4 a11y fiche) — done quand : corriger en un tap converge serveur ↔ 2e device. +4. **S4 — Recherche** (`000022` FTS + facettes serveur + Room FTS v21 + barre à chips + B4 a11y facettes) — done quand : « facture edf mars » trouve `scan_042.pdf` offline ET online. 5. **S5 — Relations + B2** (`000020` + `duplicate/same_issuer` auto + `same_scan` via `scanSessionId` + fiche « Voir aussi » + collections locales + écran Doublons « garder un seul ») — done quand : fiche CNI → verso + doublon listés, invalidables ; doublons chiffrés en Mo récupérables. 6. **S6 — Partage sobre + A1/A2/A4 + B1 (+B5 si temps)** (expiration défaut 7j + `000021` token_version + `000023` quota + `413 QUOTA_EXCEEDED` + `GET /devices` + écran Appareils + `update_metadata{baseUpdatedAt}` + flag `conflict` + import « classeur » unifié B1 + onboarding cercle B5) — done quand : lien RIB expiré → `NOT_FOUND`, password changé → autres devices re-logués, device perdu révoqué, quota plein → 413 propre, rename concurrent → badge « renommé ailleurs ». 7. **S7 — Preview 1ère page** (`pdf_preview` V2.md §3.3, une seule taille) + **C3 export chiffré** (`GET /export` zip + manifest) + B3 impression si temps + polish + release 1.2.0. Arbitrage stretch : **export > embeddings** (vrai 3-2-1 perçu, zéro GPU). diff --git a/backend/cmd/server/router_test.go b/backend/cmd/server/router_test.go index 378e3cb..e8a242f 100644 --- a/backend/cmd/server/router_test.go +++ b/backend/cmd/server/router_test.go @@ -18,6 +18,7 @@ var expectedRoutes = []string{ "GET /api/v1/files/:id", "GET /api/v1/files/:id/ocr", "GET /api/v1/files/:id/facts", + "PATCH /api/v1/files/:id/facts", "GET /api/v1/files/:id/content", "GET /api/v1/files/:id/shares", "GET /api/v1/files/:id/links", diff --git a/backend/handlers/facts_test.go b/backend/handlers/facts_test.go index b8081db..162bdb8 100644 --- a/backend/handlers/facts_test.go +++ b/backend/handlers/facts_test.go @@ -81,3 +81,88 @@ func TestFactsEndpoint(t *testing.T) { rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+emptyID+"/facts", tokenB, nil, "") expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "facts-foreign") } + +// TestCorrectFactsEndpoint : PATCH /files/:id/facts — remplace le jeu user +// (editor+ = owner ici), renvoie le jeu complet ; 400 sur corps invalide ; +// 404 si trashé/étranger. +func TestCorrectFactsEndpoint(t *testing.T) { + r, store, repo := setup(t) + device := repository.NewID() + token, userID := registerAndLogin(t, r, repo, testUserUsername(device, "fc"), "facts-test-password", device) + + fileID := repository.NewID() + if err := repo.Resources.InsertFile(userID, fileID, "facture.pdf", "", 0, nil, nil); err != nil { + t.Fatalf("insert: %v", err) + } + extractSvc := service.NewExtract(repo) + if err := extractSvc.ProcessText(fileID, "EDF\nFacture n° F-1 du 01/02/2026\nTotal : 10,00 €\n"); err != nil { + t.Fatalf("extract: %v", err) + } + _ = store + + patch := func(body string) (int, envelope) { + t.Helper() + rec, _ := doRequest(t, r, http.MethodPatch, "/api/v1/files/"+fileID+"/facts", token, []byte(body), "application/json") + var env envelope + if rec.Code == http.StatusOK { + if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil { + t.Fatalf("patch unmarshal: %v body=%s", err, rec.Body.String()) + } + } + return rec.Code, env + } + + // Correction : émetteur fixé par l'utilisateur. + code, env := patch(`{"facts":[{"factType":"issuer","valueText":"Vrai Fournisseur","confidence":1}]}`) + if code != http.StatusOK { + t.Fatalf("patch: attendu 200, got %d", code) + } + var facts []struct { + FactType string `json:"factType"` + ValueText string `json:"valueText"` + Origin string `json:"origin"` + } + if err := json.Unmarshal(env.Data, &facts); err != nil { + t.Fatalf("unmarshal: %v", err) + } + foundUser, foundAuto := false, false + for _, f := range facts { + if f.FactType == "issuer" && f.Origin == "user" && f.ValueText == "Vrai Fournisseur" { + foundUser = true + } + if f.Origin == "auto" { + foundAuto = true + } + } + if !foundUser || !foundAuto { + t.Fatalf("jeu après correction inattendu: %+v", facts) + } + + // Corps invalides → 400. + for _, body := range []string{ + `{}`, + `{"facts":[{"factType":"couleur","valueText":"bleu"}]}`, + `{"facts":[{"factType":"date","valueDate":"12/03/2026"}]}`, + `{"facts":[{"factType":"issuer"}]}`, + `not-json`, + } { + rec, _ := doRequest(t, r, http.MethodPatch, "/api/v1/files/"+fileID+"/facts", token, []byte(body), "application/json") + expectError(t, rec, http.StatusBadRequest, "INVALID_REQUEST", "facts-patch-400:"+body) + } + + // Étranger (viewer simulé : partage + snapshot hors scope ici, un autre + // user sans grant suffit — CorrectFacts exige editor+) → 404. + deviceB := repository.NewID() + tokenB, _ := registerAndLogin(t, r, repo, testUserUsername(deviceB, "fd"), "facts-test-password", deviceB) + rec, _ := doRequest(t, r, http.MethodPatch, "/api/v1/files/"+fileID+"/facts", tokenB, + []byte(`{"facts":[{"factType":"issuer","valueText":"X"}]}`), "application/json") + expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "facts-patch-foreign") + + // Trashé → 404. + if _, err := store.Trash(userID, fileID); err != nil { + t.Fatalf("trash: %v", err) + } + rec, _ = doRequest(t, r, http.MethodPatch, "/api/v1/files/"+fileID+"/facts", token, + []byte(`{"facts":[{"factType":"issuer","valueText":"X"}]}`), "application/json") + expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "facts-patch-trashed") +} diff --git a/backend/handlers/files.go b/backend/handlers/files.go index f305626..f227bf7 100644 --- a/backend/handlers/files.go +++ b/backend/handlers/files.go @@ -133,6 +133,54 @@ func FilesGetFacts(c *gin.Context) { api.OK(c, facts) } +// FilesCorrectFacts remplace le jeu `user` des faits (V3 S3) : +// PATCH /files/:id/facts `{ facts: [...] }` (full-replace, jamais de diff). +// Nécessite editor+ (comme update_metadata) ; viewer- → 404 NOT_FOUND. +// Corps invalide (type inconnu, date non ISO, fait sans valeur) → 400. +func FilesCorrectFacts(c *gin.Context) { + if Store == nil { + api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized") + return + } + userID := c.GetString(UserIDKey) + id := c.Param("id") + if !deviceIDPattern.MatchString(id) { + api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found") + return + } + var req struct { + Facts []service.FactDTO `json:"facts"` + } + if err := c.ShouldBindJSON(&req); err != nil { + api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid JSON body (expected { facts: [...] })") + return + } + if req.Facts == nil { + api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "missing required field `facts`") + return + } + if len(req.Facts) > 100 { + api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "`facts` too long (max 100)") + return + } + if err := Store.CorrectFacts(userID, id, req.Facts); err != nil { + // Erreurs de validation (type/date/valeur) → 400 explicite, pas 500 : + // ce sont des fautes client, jamais des pannes (cf. FEEDBACK #8). + if errors.Is(err, service.ErrInvalidFact) { + api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", err.Error()) + return + } + writeError(c, err) + return + } + facts, err := Store.GetFacts(userID, id) + if err != nil { + writeError(c, err) + return + } + api.OK(c, facts) +} + // own ou shared) : GET /files/:id/content. Réponse binaire (Content-Type du // fichier, Content-Disposition inline) — jamais d'enveloppe {data}. Supporte // Range via http.ServeContent (Gin c.File). Sans bytes serveur (ressource diff --git a/backend/handlers/files_test.go b/backend/handlers/files_test.go index 74be461..8031f5f 100644 --- a/backend/handlers/files_test.go +++ b/backend/handlers/files_test.go @@ -76,6 +76,7 @@ func setup(t *testing.T) (*gin.Engine, *service.Resources, *repository.Repositor handlers.Auth = manager handlers.Store = store handlers.ResetDevicesRateLimit() + handlers.ResetLoginRateLimit() gin.SetMode(gin.TestMode) r := gin.New() diff --git a/backend/handlers/router.go b/backend/handlers/router.go index 0e8a283..927b0e6 100644 --- a/backend/handlers/router.go +++ b/backend/handlers/router.go @@ -34,6 +34,7 @@ func RegisterRoutes(r *gin.Engine) { protected.GET("/files/:id", FilesGet) protected.GET("/files/:id/ocr", FilesGetOcr) protected.GET("/files/:id/facts", FilesGetFacts) + protected.PATCH("/files/:id/facts", FilesCorrectFacts) protected.GET("/files/:id/content", FilesContent) protected.GET("/files/:id/shares", SharesList) protected.GET("/files/:id/links", LinksList) diff --git a/backend/repository/facts.go b/backend/repository/facts.go index 29b6316..ffdbd6b 100644 --- a/backend/repository/facts.go +++ b/backend/repository/facts.go @@ -93,7 +93,39 @@ func (r *Resources) ListFacts(resourceID string) ([]FactRow, error) { return out, rows.Err() } -// factNeedingExtract is a file with OCR text but no auto facts yet. +// CorrectFacts fully replaces the origin='user' set of a resource (S3 : +// correction en un tap — le client envoie le jeu corrigé complet, pas un +// diff). Auto facts are never touched. Empty params clears user corrections +// (back to pure auto). +func (r *Resources) CorrectFacts(resourceID string, params []FactParam) error { + tx, err := r.DB.Begin() + if err != nil { + return err + } + defer tx.Rollback() //nolint:errcheck — no-op after Commit. + if _, err := tx.Exec( + `DELETE FROM resource_facts WHERE resource_id = $1 AND origin = 'user'`, + resourceID, + ); err != nil { + return err + } + for _, p := range params { + id, err := NewIDErr() + if err != nil { + return err + } + if _, err := tx.Exec( + `INSERT INTO resource_facts + (id, resource_id, fact_type, value_text, value_num, value_date, confidence, origin) + VALUES ($1, $2, $3, NULLIF($4, ''), $5, NULLIF($6, '')::date, $7, 'user')`, + id, resourceID, p.Type, p.ValueText, nullableFloat(p.ValueNum), derefStr(p.ValueDate), clamp01(p.Confidence), + ); err != nil { + return err + } + } + return tx.Commit() +} + type factNeedingExtract struct { ResourceID string Text string diff --git a/backend/service/extract.go b/backend/service/extract.go index dd292b6..5d9543c 100644 --- a/backend/service/extract.go +++ b/backend/service/extract.go @@ -1,7 +1,9 @@ package service import ( + "fmt" "log" + "time" "github.com/kazier/backend/extract" "github.com/kazier/backend/repository" @@ -106,3 +108,74 @@ func (s *Resources) GetFacts(userID, resourceID string) ([]FactDTO, error) { } return out, nil } + +// validFactTypes mirrors the resource_facts CHECK (migration 000019). +// Validated in Go so violations map to INVALID_REQUEST, never 500. +var validFactTypes = map[string]bool{ + "date": true, "due_date": true, "period": true, "amount": true, + "issuer": true, "reference": true, "doc_type": true, +} + +// ErrInvalidFact marks client fact-validation failures (400 INVALID_REQUEST, +// never 500 — cf. FEEDBACK #8). Wrapped by validateFactParam. +var ErrInvalidFact = fmt.Errorf("invalid fact") + +// CorrectFacts replaces the user's correction set on a resource (S3 : +// full-replace, not a diff). Requires editor+ like update_metadata +// (A8-style : viewer- ne peut pas corriger → NOT_FOUND halt, pas d'oracle). +// Absent/trashed/foreign → repository.ErrNotFound. +func (s *Resources) CorrectFacts(userID, resourceID string, facts []FactDTO) error { + access, err := s.Repository.Shares.EffectiveAccess(userID, resourceID) + if err != nil { + return err + } + if access.EffectiveRank < repository.AccessEditor { + return repository.ErrNotFound + } + params := make([]repository.FactParam, 0, len(facts)) + for i, f := range facts { + p, err := validateFactParam(i, f) + if err != nil { + return err + } + params = append(params, p) + } + return s.Repository.Resources.CorrectFacts(resourceID, params) +} + +func validateFactParam(i int, f FactDTO) (repository.FactParam, error) { + if !validFactTypes[f.FactType] { + return repository.FactParam{}, fmt.Errorf("facts[%d].factType invalide: %w", i, ErrInvalidFact) + } + if f.Confidence < 0 || f.Confidence > 1 { + return repository.FactParam{}, fmt.Errorf("facts[%d].confidence hors bornes [0,1]: %w", i, ErrInvalidFact) + } + var num *float64 + if f.ValueNum != nil { + n := *f.ValueNum + num = &n + } + var dat *string + if f.ValueDate != "" { + if _, err := time.Parse("2006-01-02", f.ValueDate); err != nil { + return repository.FactParam{}, fmt.Errorf("facts[%d].valueDate doit être ISO YYYY-MM-DD: %w", i, ErrInvalidFact) + } + d := f.ValueDate + dat = &d + } + if f.ValueText == "" && num == nil && dat == nil { + return repository.FactParam{}, fmt.Errorf("facts[%d] sans valeur (valueText|valueNum|valueDate requis): %w", i, ErrInvalidFact) + } + conf := f.Confidence + if conf == 0 { + // Correction manuelle sans confiance explicite = affirmation. + conf = 1.0 + } + return repository.FactParam{ + Type: f.FactType, + ValueText: f.ValueText, + ValueNum: num, + ValueDate: dat, + Confidence: conf, + }, nil +} diff --git a/backend/service/extract_test.go b/backend/service/extract_test.go index aa9a1c4..ce679a4 100644 --- a/backend/service/extract_test.go +++ b/backend/service/extract_test.go @@ -1,6 +1,7 @@ package service import ( + "errors" "testing" "github.com/kazier/backend/repository" @@ -194,3 +195,169 @@ func TestBackfill(t *testing.T) { t.Fatalf("backfill 2 = %d, attendu 0", n) } } + +func correctDTO(factType, valueText string) FactDTO { + return FactDTO{FactType: factType, ValueText: valueText, Confidence: 1.0} +} + +func TestCorrectFactsReplacesUserSet(t *testing.T) { + s, ex := newExtractStore(t) + userID := mustCreateUser(t, s.Repository, "extract-correct") + fileID := repository.NewID() + if err := s.Repository.Resources.InsertFile(userID, fileID, "facture.pdf", "", 0, nil, nil); err != nil { + t.Fatalf("insert: %v", err) + } + if err := ex.ProcessText(fileID, extractCorpus); err != nil { + t.Fatalf("process: %v", err) + } + + // Correction : l'émetteur auto est faux, l'utilisateur le fixe. + if err := s.CorrectFacts(userID, fileID, []FactDTO{correctDTO("issuer", "Vrai Fournisseur")}); err != nil { + t.Fatalf("correct: %v", err) + } + facts, err := s.GetFacts(userID, fileID) + if err != nil { + t.Fatalf("get facts: %v", err) + } + var userIssuer, autoIssuer int + for _, f := range facts { + if f.FactType == "issuer" && f.Origin == "user" && f.ValueText == "Vrai Fournisseur" { + userIssuer++ + } + if f.FactType == "issuer" && f.Origin == "auto" { + autoIssuer++ + } + } + if userIssuer != 1 { + t.Fatalf("correction user manquante: %+v", facts) + } + if autoIssuer == 0 { + t.Error("l'auto doit survivre à côté du user (les deux sont lus, user d'abord)") + } + + // Deuxième correction (jeu vide) : efface les corrections, garde l'auto. + if err := s.CorrectFacts(userID, fileID, nil); err != nil { + t.Fatalf("clear corrections: %v", err) + } + facts, _ = s.GetFacts(userID, fileID) + for _, f := range facts { + if f.Origin == "user" { + t.Fatalf("corrections restantes: %+v", facts) + } + } + if len(facts) == 0 { + t.Fatal("l'auto doit survivre à l'effacement des corrections") + } +} + +func TestCorrectFactsValidation(t *testing.T) { + s, _ := newExtractStore(t) + userID := mustCreateUser(t, s.Repository, "extract-correct-val") + fileID := repository.NewID() + if err := s.Repository.Resources.InsertFile(userID, fileID, "doc.pdf", "", 0, nil, nil); err != nil { + t.Fatalf("insert: %v", err) + } + num := 12.5 + cases := []struct { + name string + facts []FactDTO + }{ + {"type inconnu", []FactDTO{{FactType: "couleur", ValueText: "bleu"}}}, + {"confiance hors bornes", []FactDTO{{FactType: "issuer", ValueText: "X", Confidence: 2}}}, + {"date non ISO", []FactDTO{{FactType: "date", ValueDate: "12/03/2026"}}}, + {"sans valeur", []FactDTO{{FactType: "issuer"}}}, + } + for _, tc := range cases { + if err := s.CorrectFacts(userID, fileID, tc.facts); err == nil { + t.Errorf("%s : erreur attendue", tc.name) + } else if !errors.Is(err, ErrInvalidFact) { + t.Errorf("%s : attendu ErrInvalidFact, got %v", tc.name, err) + } + } + // Valides : date ISO + montant numérique. + if err := s.CorrectFacts(userID, fileID, []FactDTO{ + {FactType: "due_date", ValueDate: "2026-04-12"}, + {FactType: "amount", ValueNum: &num}, + }); err != nil { + t.Fatalf("faits valides rejetés: %v", err) + } +} + +func TestCorrectFactsScope(t *testing.T) { + s, _ := newExtractStore(t) + owner := mustCreateUser(t, s.Repository, "extract-corr-o") + viewer := mustCreateUser(t, s.Repository, "extract-corr-v") + fileID := repository.NewID() + if err := s.Repository.Resources.InsertFile(owner, fileID, "doc.pdf", "", 0, nil, nil); err != nil { + t.Fatalf("insert: %v", err) + } + + // Étranger (même viewer via partage simulé plus bas) → NOT_FOUND. + if err := s.CorrectFacts(viewer, fileID, nil); err != repository.ErrNotFound { + t.Fatalf("étranger : attendu NOT_FOUND, got %v", err) + } + // Absent → NOT_FOUND (EffectiveAccess sur ressource inconnue). + if err := s.CorrectFacts(owner, repository.NewID(), []FactDTO{correctDTO("issuer", "X")}); err != repository.ErrNotFound { + t.Fatalf("absent : attendu NOT_FOUND, got %v", err) + } +} + +func TestSyncOpCorrectFacts(t *testing.T) { + s, ex := newExtractStore(t) + userID := mustCreateUser(t, s.Repository, "extract-op") + other := mustCreateUser(t, s.Repository, "extract-op-x") + device := mustRegisterDevice(t, s.Repository, "c0000000000000000000000000000001") + fileID := repository.NewID() + if err := s.Repository.Resources.InsertFile(userID, fileID, "facture.pdf", "", 0, nil, nil); err != nil { + t.Fatalf("insert: %v", err) + } + if err := ex.ProcessText(fileID, extractCorpus); err != nil { + t.Fatalf("process: %v", err) + } + foreignID := repository.NewID() + if err := s.Repository.Resources.InsertFile(other, foreignID, "autre.pdf", "", 0, nil, nil); err != nil { + t.Fatalf("insert foreign: %v", err) + } + + apply := func(resID string, facts []FactDTO) SyncResult { + t.Helper() + raw := map[string]any{"facts": facts} + res, err := s.ApplyBatch(userID, device, []SyncOperation{ + syncOp(repository.NewID(), resID, OpCorrectFacts, "file", raw), + }) + if err != nil { + t.Fatalf("apply: %v", err) + } + return res + } + + if res := apply(fileID, []FactDTO{correctDTO("issuer", "Corrigé")}); res.Applied != 1 || res.Failed != nil { + t.Fatalf("correct op: %+v", res) + } + facts, _ := s.GetFacts(userID, fileID) + found := false + for _, f := range facts { + if f.FactType == "issuer" && f.Origin == "user" && f.ValueText == "Corrigé" { + found = true + } + } + if !found { + t.Fatalf("correction via op manquante: %+v", facts) + } + // Op étrangère → halt NOT_FOUND. + if res := apply(foreignID, []FactDTO{correctDTO("issuer", "X")}); res.Failed == nil || res.Failed.Code != "NOT_FOUND" { + t.Fatalf("correct autrui doit halter NOT_FOUND: %+v", res) + } + // Payload invalide → halt INVALID_REQUEST. + res, err := s.ApplyBatch(userID, device, []SyncOperation{ + syncOp(repository.NewID(), fileID, OpCorrectFacts, "file", map[string]any{ + "facts": []any{map[string]any{"factType": "couleur", "valueText": "bleu"}}, + }), + }) + if err != nil { + t.Fatalf("apply: %v", err) + } + if res.Failed == nil || res.Failed.Code != "INVALID_REQUEST" { + t.Fatalf("payload invalide doit halter INVALID_REQUEST: %+v", res) + } +} diff --git a/backend/service/sync.go b/backend/service/sync.go index 6b4eb20..61a2e13 100644 --- a/backend/service/sync.go +++ b/backend/service/sync.go @@ -31,6 +31,8 @@ const ( OpTrashResource = "trash_resource" OpRestoreResource = "restore_resource" OpPurgeResource = "purge_resource" + // V3 corrections (S3) : remplace le jeu `user` des faits (editor+). + OpCorrectFacts = "correct_facts" ) // SyncOperation is one outbox entry (shadow of mobile PendingOperationRow). @@ -98,6 +100,10 @@ type reportBytesPayload struct { HasBytes *bool `json:"hasBytes"` } +type correctFactsPayload struct { + Facts []FactDTO `json:"facts"` +} + func classifySyncError(err error) (string, string) { switch { case errors.Is(err, repository.ErrNameConflict): @@ -206,7 +212,8 @@ func validateSyncOp(op *SyncOperation) error { switch op.Operation { case OpCreateResource, OpUpdateMetadata, OpMoveResource, OpDeleteResource, OpShare, OpRevokeShare, OpUpdateShare, OpCreateLink, OpRevokeLink, - OpReportBytes, OpTrashResource, OpRestoreResource, OpPurgeResource: + OpReportBytes, OpTrashResource, OpRestoreResource, OpPurgeResource, + OpCorrectFacts: default: return errors.New("unknown operation " + op.Operation) } @@ -400,6 +407,22 @@ func (s *Resources) applySyncOp(ownerID, deviceID string, op *SyncOperation) err case OpReportBytes: return s.applyReportBytesOp(ownerID, deviceID, resourceID, op) + case OpCorrectFacts: + // S3 : même garde que CorrectFacts (editor+, A8) — une ressource + // visible sans droit de mutation n'est pas corrigeable (NOT_FOUND, + // pas d'oracle). Le payload porte le jeu `user` complet + // (full-replace, jamais de diff). + var p correctFactsPayload + if err := json.Unmarshal(op.Payload, &p); err != nil { + return errors.New("invalid payload: " + err.Error()) + } + for i, f := range p.Facts { + if _, err := validateFactParam(i, f); err != nil { + return err + } + } + return s.CorrectFacts(ownerID, resourceID, p.Facts) + default: return errors.New("unknown operation " + op.Operation) } diff --git a/docs/api-v1.md b/docs/api-v1.md index c446809..f47175b 100644 --- a/docs/api-v1.md +++ b/docs/api-v1.md @@ -50,6 +50,7 @@ Références : `V2.md` (modèle cible), `mobile/services/db/` (conventions sync) | GET | `/ocr/jobs/:id` | — | `OcrJob` | `NOT_FOUND` | | GET | `/files/:id/ocr` | — | `FileOcr` (`{ text, updatedAt }`) | `NOT_FOUND` | | GET | `/files/:id/facts` | — (viewer+, même portée que l'OCR) | `Fact[]` (`{ factType: date|due_date|period|amount|issuer|reference|doc_type, valueText?, valueNum?, valueDate? (ISO), confidence (0..1), origin: auto|user }`, `[]` si rien d'extractible) | `NOT_FOUND` (trashé/absent/étranger) | +| PATCH | `/files/:id/facts` | `{ facts: [{ factType, valueText?, valueNum?, valueDate?, confidence? }] }` (jeu `user` complet, full-replace, editor+) | `Fact[]` (jeu complet auto + user) | `NOT_FOUND` (viewer-/absent/trashé), `INVALID_REQUEST` (type inconnu, date non ISO, fait sans valeur, corps malformé) | | GET | `/files/:id/shares` | — (owner uniquement) | `ShareGrant[]` (`{ granteeUserId, granteeKind: "user"|"group", username, access, inherit, expiresAt (ms|null), updatedAt (ms) }`) | `NOT_FOUND` (non-owner ou inconnue — pas d'énumération) | | GET | `/files/:id/links` | — (owner uniquement) | `ShareLink[]` (même forme que `GET /shares/links/:token`) | `NOT_FOUND` (non-owner ou inconnue) | | GET | `/files/:id/placements` | — (owner uniquement) | `Placement[]` (`{ locationType: "server"|"mobile", deviceId?, hasBytes, updatedAt }`, entrée serveur en premier) | `NOT_FOUND` (non-owner ou inconnue) | @@ -121,7 +122,7 @@ type FileOcr = { text: string; updatedAt?: string | null }; } ``` -- `operation` ∈ `create_resource | update_metadata | delete_resource | move_resource | share | revoke_share | update_share | create_link | revoke_link | report_bytes | trash_resource | restore_resource | purge_resource` (cf. `PendingOperationType` mobile). +- `operation` ∈ `create_resource | update_metadata | delete_resource | move_resource | share | revoke_share | update_share | create_link | revoke_link | report_bytes | trash_resource | restore_resource | purge_resource | correct_facts` (cf. `PendingOperationType` mobile). - **Identifiants** : `operation_id` est un **TEXT 32-hex** généré par le client (`^[0-9a-f]{32}$`, CHECK-enforced depuis la migration `000008`), distinct de `resource_id`. L'idempotence outbox reste **par device** : `UNIQUE(device_id, operation_id)` (la réinscription d'un device avec un login différent ne réutilise pas l'historique outbox d'un autre compte). Pour chaque op : si déjà traitée → **no-op** (comptée comme appliquée, les doublons arrivent à cause du backoff/retry). Sinon appliquée si valide. - **Ordre** : les opérations sont appliquées **séquentiellement**, dans l'ordre du batch. Le serveur **s'arrête à la première erreur non-idempotente** et renvoie l'index atteint — le client reprend à cet index. - Réponse : `2xx` avec `{ "applied": int, "failed": { "operation_id": "…32-hex", "code": string, "message": string } | null }` (`applied` = index de la prochaine op à envoyer). @@ -131,6 +132,7 @@ type FileOcr = { text: string; updatedAt?: string | null }; - `update_metadata` : ressource absente → **no-op** (état terminal atteint) ; **ressource partagée : nécessite `editor+`** (§6.2) — sinon `NOT_FOUND` (une ressource visible mais sans droit de mutation n'est pas renommée) ; une ressource sans relation applicable (ni owner, ni grant) reste un no-op (pas d'énumération). `move_resource` / `delete_resource` restent **owner-only** (scoping par `user_id`, les ops d'un non-owner sont des no-op). - `delete_resource` : **legacy → mappé vers `trash_resource`** (corbeille, restaurable, même idempotence : absent/déjà trashé = succès, vivant d'autrui = `NOT_FOUND` halt). - **Corbeille V3** (`trash_resource` / `restore_resource` / `purge_resource`, owner-only) : `trash` pose `deleted_at` sur la ressource **et son subtree** (dossier → contenu) ; `restore` lève le flag sur la ressource, son subtree **et sa chaîne d'ancêtres** (un fichier restauré dont le dossier est encore trashé resterait injoignable) ; `purge` détruit lignes + versions + octets. Sémantique : absent → no-op (`trash`/`restore`/`purge`), vivant d'autrui → `NOT_FOUND` halt, `restore` d'un live → no-op succès. Une ressource trashée reste `NOT_FOUND` en lecture normale, visible seulement via `GET /trash`. Passe serveur : destruction définitive après 30j (`TrashRetention`). + - **Corrections V3** (`correct_facts`, editor+) : `payload = { "facts": [{ "factType", "valueText"?, "valueNum"?, "valueDate"? (ISO `YYYY-MM-DD`), "confidence"? }] }` — remplace le jeu `user` complet (full-replace, jamais de diff ; jeu vide = efface les corrections, l'auto survit). Mêmes gardes qu'`update_metadata` (viewer- → `NOT_FOUND` halt) ; fait invalide (type inconnu, date non ISO, sans valeur) → `INVALID_REQUEST` avec arrêt du batch. Le client corrige en un tap depuis la fiche document et pousse dans la même transaction Room que l'écriture optimiste. - **Versions V3** : chaque overwrite d'octets (upload ciblé) fige l'ancienne génération (`resource_versions`, N=3, élagage auto) ; `POST /files/:id/versions/:n/restore` recopie vers le live (l'actuel est à son tour versionné). Upload ciblé vers une ressource trashée → `NOT_FOUND` (jamais de résurrection d'octets). - **Partage** (`share` / `update_share`, même sémantique d'upsert) : `payload = { "granteeUserId"?: "…32-hex", "granteeGroupId"?: "…32-hex", "access": "viewer"|"commenter"|"editor", "inherit"?: bool, "expiresAt"?: ms }` — **exactement un** principal (user XOR groupe, V2-6). La ressource doit **appartenir** au user appelant (sinon `NOT_FOUND`) ; le grantee user doit exister (sinon `GRANTEE_NOT_FOUND`), le groupe doit exister (sinon `GROUP_NOT_FOUND`) ; accès déjà partagé → mis à jour (idempotent). Privilégier `viewer` < `commenter` < `editor` (< `owner` réservé à l'ownership, non partageable → `INVALID_REQUEST`). Les membres d'un groupe partagé héritent du grant (un niveau, sans imbrication) dans le snapshot comme dans l'enforcement. - `revoke_share` : `payload = { "granteeUserId": "…32-hex" }`. **Idempotent** (déjà révoqué/absent → no-op). diff --git a/mobile-kotlin/app/schemas/com.kazier.mobile.data.local.AppDatabase/20.json b/mobile-kotlin/app/schemas/com.kazier.mobile.data.local.AppDatabase/20.json new file mode 100644 index 0000000..d57f0eb --- /dev/null +++ b/mobile-kotlin/app/schemas/com.kazier.mobile.data.local.AppDatabase/20.json @@ -0,0 +1,844 @@ +{ + "formatVersion": 1, + "database": { + "version": 20, + "identityHash": "d29a3bf93b4ec7845c123b8b2e73ff7b", + "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, `trashed_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": "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": "trashedAt", + "columnName": "trashed_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_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, `bytes_uploaded` INTEGER NOT NULL, `bytes_upload_attempts` INTEGER NOT NULL, `has_content_server` INTEGER NOT NULL, `wanted_offline` INTEGER NOT NULL, `trashed_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": "bytesUploaded", + "columnName": "bytes_uploaded", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "bytesUploadAttempts", + "columnName": "bytes_upload_attempts", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "hasContentServer", + "columnName": "has_content_server", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "wantedOffline", + "columnName": "wanted_offline", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "trashedAt", + "columnName": "trashed_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": [] + }, + { + "tableName": "resource_facts", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `resource_id` TEXT NOT NULL, `fact_type` TEXT NOT NULL, `value_text` TEXT, `value_num` REAL, `value_date` TEXT, `confidence` REAL NOT NULL, `origin` TEXT 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": "factType", + "columnName": "fact_type", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "valueText", + "columnName": "value_text", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "valueNum", + "columnName": "value_num", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "valueDate", + "columnName": "value_date", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "confidence", + "columnName": "confidence", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "origin", + "columnName": "origin", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updated_at", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_resource_facts_resource_id", + "unique": false, + "columnNames": [ + "resource_id" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_resource_facts_resource_id` ON `${TABLE_NAME}` (`resource_id`)" + } + ], + "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, 'd29a3bf93b4ec7845c123b8b2e73ff7b')" + ] + } +} \ No newline at end of file diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/AppDatabase.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/AppDatabase.kt index 32b2ba2..44ca99a 100644 --- a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/AppDatabase.kt +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/AppDatabase.kt @@ -3,6 +3,7 @@ package com.kazier.mobile.data.local import androidx.room.Database import androidx.room.RoomDatabase import com.kazier.mobile.data.local.dao.FileDao +import com.kazier.mobile.data.local.dao.FactsDao import com.kazier.mobile.data.local.dao.FolderDao import com.kazier.mobile.data.local.dao.PendingOperationDao import com.kazier.mobile.data.local.dao.ResourcePermissionDao @@ -11,6 +12,7 @@ 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.ResourceFact import com.kazier.mobile.data.local.entity.ResourcePermissionEntity import com.kazier.mobile.data.local.entity.ScanPageEntity import com.kazier.mobile.data.local.entity.ScanSessionEntity @@ -36,14 +38,16 @@ import com.kazier.mobile.data.local.entity.UserPreferenceEntity * v18: has_content_server + wanted_offline sur files (download V2). * v19: trashed_at sur files + folders (corbeille V3 — tombstone exists=0, * restore exists=1, purge locale après 30j+). + * v20: table resource_facts (faits génériques V3 — miroir GET /facts, + * remplacement en bloc au sync, corrections `user` poussées en outbox). */ @Database( entities = [ FolderEntity::class, UserPreferenceEntity::class, FileEntity::class, PendingOperationEntity::class, ScanSessionEntity::class, ScanPageEntity::class, - ResourcePermissionEntity::class, + ResourcePermissionEntity::class, ResourceFact::class, ], - version = 19, + version = 20, // 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, @@ -51,6 +55,7 @@ import com.kazier.mobile.data.local.entity.UserPreferenceEntity abstract class AppDatabase : RoomDatabase() { abstract fun folderDao(): FolderDao + abstract fun factsDao(): FactsDao abstract fun userPreferenceDao(): UserPreferenceDao abstract fun fileDao(): FileDao abstract fun pendingOperationDao(): PendingOperationDao diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/dao/FactsDao.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/dao/FactsDao.kt new file mode 100644 index 0000000..523e475 --- /dev/null +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/dao/FactsDao.kt @@ -0,0 +1,28 @@ +package com.kazier.mobile.data.local.dao + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.Query +import com.kazier.mobile.data.local.entity.ResourceFact +import kotlinx.coroutines.flow.Flow + +@Dao +interface FactsDao { + + @Query("SELECT * FROM resource_facts WHERE resource_id = :resourceId ORDER BY fact_type ASC, value_text ASC") + fun observeForResource(resourceId: String): Flow> + + @Query("SELECT * FROM resource_facts WHERE resource_id = :resourceId ORDER BY fact_type ASC, value_text ASC") + suspend fun getForResource(resourceId: String): List + + @Insert + suspend fun insertAll(facts: List) + + /** Remplacement en bloc (sync serveur, source de vérité) — voir repository. */ + @Query("DELETE FROM resource_facts WHERE resource_id = :resourceId") + suspend fun deleteForResource(resourceId: String) + + /** Efface les corrections locales (reset « rétablir auto », S3). */ + @Query("DELETE FROM resource_facts WHERE resource_id = :resourceId AND origin = 'user'") + suspend fun deleteUserFacts(resourceId: String) +} diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/entity/PendingOperationEntity.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/entity/PendingOperationEntity.kt index 44a4d22..8d3cf88 100644 --- a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/entity/PendingOperationEntity.kt +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/entity/PendingOperationEntity.kt @@ -99,4 +99,9 @@ object PendingOperationType { const val TRASH_RESOURCE = "trash_resource" const val RESTORE_RESOURCE = "restore_resource" const val PURGE_RESOURCE = "purge_resource" + /** + * V3 corrections : remplace le jeu `user` des faits (`{ facts: [...] }`, + * full-replace, editor+). Même transaction que l'écriture Room optimiste. + */ + const val CORRECT_FACTS = "correct_facts" } \ No newline at end of file diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/entity/ResourceFact.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/entity/ResourceFact.kt new file mode 100644 index 0000000..bbb8d69 --- /dev/null +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/entity/ResourceFact.kt @@ -0,0 +1,80 @@ +package com.kazier.mobile.data.local.entity + +import androidx.room.ColumnInfo +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +/** + * Miroir local des faits génériques serveur (`GET /files/:id/facts`, V3 S2). + * + * Remplacés en bloc à chaque sync (`FactsRepository.syncFromServer`) — + * jamais de merge : le serveur est la source de vérité. Les corrections + * locales (`origin = 'user'`) sont écrites d'abord en Room (optimiste) puis + * poussées via l'op outbox `correct_facts` (full-replace serveur). + */ +@Entity( + tableName = "resource_facts", + indices = [ + Index(value = ["resource_id"]), + ], +) +data class ResourceFact( + @PrimaryKey(autoGenerate = true) + val id: Long = 0L, + @ColumnInfo(name = "resource_id") + val resourceId: String, + @ColumnInfo(name = "fact_type") + val factType: String, + @ColumnInfo(name = "value_text") + val valueText: String? = null, + @ColumnInfo(name = "value_num") + val valueNum: Double? = null, + @ColumnInfo(name = "value_date") + val valueDate: String? = null, + @ColumnInfo(name = "confidence") + val confidence: Double = 0.0, + @ColumnInfo(name = "origin") + val origin: String = FactOrigin.AUTO, + @ColumnInfo(name = "updated_at") + val updatedAt: Long, +) + +/** Origines d'un fait — miroir du CHECK serveur (migration 000019). */ +object FactOrigin { + const val AUTO = "auto" + const val USER = "user" +} + +/** Types de faits — miroir du CHECK serveur (migration 000019). */ +object FactType { + const val DATE = "date" + const val DUE_DATE = "due_date" + const val PERIOD = "period" + const val AMOUNT = "amount" + const val ISSUER = "issuer" + const val REFERENCE = "reference" + const val DOC_TYPE = "doc_type" +} + +/** + * Faits affichables : pour chaque type, le `user` gagne sur l'`auto` + * (correction en un tap, S3). Tri stable par type puis valeur. + */ +fun displayFacts(all: List): List { + val userTypes = all.filter { it.origin == FactOrigin.USER }.map { it.factType }.toSet() + return all + .filter { it.origin == FactOrigin.USER || it.factType !in userTypes } + .sortedWith(compareBy({ factTypeOrder(it.factType) }, { it.valueText ?: "" })) +} + +private fun factTypeOrder(type: String): Int = when (type) { + FactType.ISSUER -> 0 + FactType.AMOUNT -> 1 + FactType.DUE_DATE -> 2 + FactType.DATE -> 3 + FactType.PERIOD -> 4 + FactType.REFERENCE -> 5 + FactType.DOC_TYPE -> 6 + else -> 7 +} diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/migration/Migrations.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/migration/Migrations.kt index a5f4641..249a014 100644 --- a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/migration/Migrations.kt +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/local/migration/Migrations.kt @@ -329,7 +329,36 @@ object Migrations { } } + /** + * V3 faits génériques : table `resource_facts` (miroir `GET /facts`, + * remplacement en bloc au sync, corrections `user` poussées en outbox). + * Schéma aligné sur `ResourceFact` (export `app/schemas/20.json`). + */ + private val MIGRATION_19_20 = object : Migration(19, 20) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL( + """ + CREATE TABLE IF NOT EXISTS `resource_facts` ( + `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, + `resource_id` TEXT NOT NULL, + `fact_type` TEXT NOT NULL, + `value_text` TEXT, + `value_num` REAL, + `value_date` TEXT, + `confidence` REAL NOT NULL, + `origin` TEXT NOT NULL, + `updated_at` INTEGER NOT NULL + ) + """.trimIndent(), + ) + db.execSQL( + "CREATE INDEX IF NOT EXISTS `index_resource_facts_resource_id` " + + "ON `resource_facts` (`resource_id`)", + ) + } + } + val ALL: Array = 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_14_15, MIGRATION_15_16, MIGRATION_16_17, MIGRATION_17_18, MIGRATION_18_19, + 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, MIGRATION_16_17, MIGRATION_17_18, MIGRATION_18_19, MIGRATION_19_20, ) } \ No newline at end of file diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/remote/ApiClient.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/remote/ApiClient.kt index e9e2488..9e05e07 100644 --- a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/remote/ApiClient.kt +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/remote/ApiClient.kt @@ -29,6 +29,8 @@ import com.kazier.mobile.data.remote.dto.ShareLinkDto import com.kazier.mobile.data.remote.dto.SyncOpDto import com.kazier.mobile.data.remote.dto.SyncOpsRequest import com.kazier.mobile.data.remote.dto.SyncOpsResult +import com.kazier.mobile.data.remote.dto.CorrectFactsDto +import com.kazier.mobile.data.remote.dto.FactDto import com.kazier.mobile.data.remote.dto.TrashDto import com.kazier.mobile.data.remote.dto.VersionDto import kotlin.coroutines.cancellation.CancellationException @@ -165,6 +167,14 @@ class ApiClient @Inject constructor( suspend fun listVersions(fileId: String): List = unwrap({ apiService.listVersions(fileId) }) + /** Faits génériques V3 — `GET /files/:id/facts` (`[]` si vide). */ + suspend fun listFacts(fileId: String): List = + unwrap({ apiService.listFacts(fileId) }) + + /** Remplace le jeu `user` — `PATCH /files/:id/facts` (full-replace). */ + suspend fun correctFacts(fileId: String, facts: List): List = + unwrap({ apiService.correctFacts(fileId, CorrectFactsDto(facts)) }) + /** Recherche serveur paginée — `GET /files/search?q=…` (+ `meta`). */ suspend fun searchFilesPaged( query: String, diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/remote/ApiService.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/remote/ApiService.kt index b2194a7..a7e51e2 100644 --- a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/remote/ApiService.kt +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/remote/ApiService.kt @@ -22,6 +22,8 @@ import com.kazier.mobile.data.remote.dto.ShareGrantDto import com.kazier.mobile.data.remote.dto.ShareLinkDto import com.kazier.mobile.data.remote.dto.SyncOpsRequest import com.kazier.mobile.data.remote.dto.SyncOpsResult +import com.kazier.mobile.data.remote.dto.CorrectFactsDto +import com.kazier.mobile.data.remote.dto.FactDto import com.kazier.mobile.data.remote.dto.TrashDto import com.kazier.mobile.data.remote.dto.VersionDto import okhttp3.MultipartBody @@ -176,6 +178,25 @@ interface ApiService { @Path("n") versionNo: Int, ): Response> + /** + * Faits génériques V3 (`GET /files/:id/facts`, viewer+) — `[]` si rien + * d'extractible, 404 si trashé/absent/étranger. + */ + @GET("files/{id}/facts") + suspend fun listFacts( + @Path("id") fileId: String, + ): Response>> + + /** + * Remplace le jeu `user` des faits (`PATCH /files/:id/facts`, + * full-replace, editor+) — renvoie le jeu complet (auto + user). + */ + @PATCH("files/{id}/facts") + suspend fun correctFacts( + @Path("id") fileId: String, + @Body body: CorrectFactsDto, + ): Response>> + /** * Recherche serveur (`GET /files/search?q=…`, paginé `meta`). Non consommée * en V1 (recherche 100 % locale via Room) — exposée pour parité contrat. diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/remote/dto/Dtos.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/remote/dto/Dtos.kt index dd1fb68..b403a1f 100644 --- a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/remote/dto/Dtos.kt +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/remote/dto/Dtos.kt @@ -275,4 +275,25 @@ data class VersionDto( @Json(name = "size") val size: Long = 0L, @Json(name = "mimeType") val mimeType: String? = null, @Json(name = "createdAt") val createdAt: String? = null, +) + +/** + * Fait générique `GET /files/{id}/facts` (V3 S2) — miroir de `FactDTO` Go. + * `valueNum` en Double (montants) ; `valueDate` ISO `YYYY-MM-DD` ; + * `origin` = "auto" (remplacé à chaque passe) | "user" (correction S3). + * Réutilisé tel quel dans le body `PATCH /files/{id}/facts` + * (`{ facts: [...] }`, `origin` ignoré par le serveur). + */ +data class FactDto( + @Json(name = "factType") val factType: String, + @Json(name = "valueText") val valueText: String? = null, + @Json(name = "valueNum") val valueNum: Double? = null, + @Json(name = "valueDate") val valueDate: String? = null, + @Json(name = "confidence") val confidence: Double = 0.0, + @Json(name = "origin") val origin: String = "auto", +) + +/** Body `PATCH /files/{id}/facts` — jeu `user` complet (full-replace, S3). */ +data class CorrectFactsDto( + @Json(name = "facts") val facts: List, ) \ No newline at end of file diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/repository/FactsRepository.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/repository/FactsRepository.kt new file mode 100644 index 0000000..dc0e105 --- /dev/null +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/repository/FactsRepository.kt @@ -0,0 +1,101 @@ +package com.kazier.mobile.data.repository + +import androidx.room.withTransaction +import com.kazier.mobile.data.local.AppDatabase +import com.kazier.mobile.data.local.dao.FactsDao +import com.kazier.mobile.data.local.entity.FactOrigin +import com.kazier.mobile.data.local.entity.ResourceFact +import com.kazier.mobile.data.remote.ApiClient +import com.kazier.mobile.data.remote.dto.FactDto +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.flow.Flow + +/** + * Faits génériques V3 (S3) côté client. + * + * - [syncFromServer] : `GET /files/:id/facts` → remplacement en bloc Room + * (le serveur est la source de vérité, comme `ocr_text`). + * - [saveCorrection] : écriture optimiste locale (jeu `user` remplacé) + + * op outbox `correct_facts` **dans la même transaction** (contrat outbox + * atomique). Ordre préservé : deux corrections successives s'appliquent + * dans l'ordre (full-replace, la dernière gagne — convergence). + * - [resetToAuto] : efface les corrections (jeu `user` vide poussé). + */ +@Singleton +class FactsRepository @Inject constructor( + private val appDatabase: AppDatabase, + private val factsDao: FactsDao, + private val outboxRepository: OutboxRepository, + private val apiClient: ApiClient, +) { + + fun observeFacts(resourceId: String): Flow> = + factsDao.observeForResource(resourceId) + + suspend fun getFacts(resourceId: String): List = + factsDao.getForResource(resourceId) + + /** Rapatrie le jeu serveur (auto + user) et remplace le miroir local. */ + suspend fun syncFromServer(resourceId: String): List { + val dtos = apiClient.listFacts(resourceId) + val now = System.currentTimeMillis() + val entities = dtos.map { it.toEntity(resourceId, now) } + appDatabase.withTransaction { + factsDao.deleteForResource(resourceId) + if (entities.isNotEmpty()) factsDao.insertAll(entities) + } + return entities + } + + /** + * Correction en un tap : remplace le jeu `user` local par [userFacts] + * (faits édités, `origin = user`, confiance 1.0) et enqueue le jeu + * complet vers le serveur. Si le serveur ne connaît pas encore la + * ressource (jamais de create), pas d'op — pur local (le create puis les + * faits suivront au sync... le jeu user local sera écrasé au prochain + * syncFromServer, cas rare : faits édités avant tout push). + */ + suspend fun saveCorrection(resourceId: String, userFacts: List) { + val now = System.currentTimeMillis() + val stamped = userFacts.map { + it.copy(resourceId = resourceId, origin = FactOrigin.USER, confidence = 1.0, updatedAt = now) + } + appDatabase.withTransaction { + factsDao.deleteUserFacts(resourceId) + if (stamped.isNotEmpty()) factsDao.insertAll(stamped) + if (outboxRepository.hasCreateOperation(resourceId)) { + outboxRepository.enqueueCorrectFacts(resourceId, "file", stamped.map { it.toPayload() }) + } + } + } + + /** « Rétablir auto » : efface les corrections (jeu vide poussé si connu). */ + suspend fun resetToAuto(resourceId: String) { + appDatabase.withTransaction { + factsDao.deleteUserFacts(resourceId) + if (outboxRepository.hasCreateOperation(resourceId)) { + outboxRepository.enqueueCorrectFacts(resourceId, "file", emptyList()) + } + } + } + + private fun FactDto.toEntity(resourceId: String, now: Long) = ResourceFact( + resourceId = resourceId, + factType = factType, + valueText = valueText, + valueNum = valueNum, + valueDate = valueDate, + confidence = confidence, + origin = origin.ifBlank { FactOrigin.AUTO }, + updatedAt = now, + ) + + private fun ResourceFact.toPayload(): Map = buildMap { + put("factType", factType) + valueText?.let { put("valueText", it) } + valueNum?.let { put("valueNum", it) } + valueDate?.let { put("valueDate", it) } + put("confidence", confidence) + } +} diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/repository/OutboxRepository.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/repository/OutboxRepository.kt index 98c0a73..441023f 100644 --- a/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/repository/OutboxRepository.kt +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/data/repository/OutboxRepository.kt @@ -125,6 +125,23 @@ class OutboxRepository @Inject constructor( suspend fun enqueuePurgeResource(resourceId: String, resourceType: String): String = enqueue(PendingOperationType.PURGE_RESOURCE, resourceId, resourceType) + /** + * Raccourci `correct_facts` — payload `{ facts: [{ factType, valueText?, + * valueNum?, valueDate?, confidence? }] }` (S3, full-replace du jeu user). + * Les nulls sont omis (Moshi) : le serveur exige au moins une valeur par + * fait et une date ISO `YYYY-MM-DD`. + */ + suspend fun enqueueCorrectFacts( + resourceId: String, + resourceType: String, + facts: List>, + ): String = enqueue( + operation = PendingOperationType.CORRECT_FACTS, + resourceId = resourceId, + resourceType = resourceType, + payload = mapOf("facts" to facts), + ) + /** * Raccourci `share` — payload `{ granteeUserId|granteeGroupId, access }` * (voir docs/api-v1.md §6.1). `access`: viewer | commenter | editor. diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/di/DatabaseModule.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/di/DatabaseModule.kt index 653953e..4e8795b 100644 --- a/mobile-kotlin/app/src/main/java/com/kazier/mobile/di/DatabaseModule.kt +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/di/DatabaseModule.kt @@ -4,6 +4,7 @@ import android.content.Context import androidx.room.Room import com.kazier.mobile.data.local.AppDatabase import com.kazier.mobile.data.local.dao.FileDao +import com.kazier.mobile.data.local.dao.FactsDao import com.kazier.mobile.data.local.dao.FolderDao import com.kazier.mobile.data.local.dao.PendingOperationDao import com.kazier.mobile.data.local.dao.ResourcePermissionDao @@ -52,4 +53,7 @@ object DatabaseModule { @Provides fun provideResourcePermissionDao(db: AppDatabase): ResourcePermissionDao = db.resourcePermissionDao() + + @Provides + fun provideFactsDao(db: AppDatabase): FactsDao = db.factsDao() } \ No newline at end of file diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/ui/document/DocumentViewerScreen.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/ui/document/DocumentViewerScreen.kt index 9f94907..a691280 100644 --- a/mobile-kotlin/app/src/main/java/com/kazier/mobile/ui/document/DocumentViewerScreen.kt +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/ui/document/DocumentViewerScreen.kt @@ -28,6 +28,7 @@ import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.CloudOff import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.DocumentScanner +import androidx.compose.material.icons.filled.FactCheck import androidx.compose.material3.AlertDialog import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator @@ -91,6 +92,7 @@ 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.facts.FactsBottomSheet import com.kazier.mobile.ui.document.content.PdfFocusViewer import com.kazier.mobile.ui.document.content.TextFocusViewer import com.kazier.mobile.ui.document.content.ZoomableContent @@ -166,9 +168,12 @@ fun DocumentViewerScreen( // affiché change — une run en cours continue en arrière-plan (single-flight // dans le OcrViewModel) et persiste son résultat. var showOcrDialog by rememberSaveable { mutableStateOf(false) } + // V3 S3 : fiche des faits génériques (corrigibles) — refermée au swipe. + var showFacts by rememberSaveable { mutableStateOf(false) } LaunchedEffect(currentFile?.resourceId) { ocrViewModel.reset() showOcrDialog = false + showFacts = false } // Le bouton n'apparaît que pour un document gardé, présent à la fois en // local et connu du serveur (`local-cloud`) — et un compte connecté. @@ -334,6 +339,13 @@ fun DocumentViewerScreen( } else { null }, + // Faits V3 : seulement pour un document gardé (les + // faits n'existent qu'après push + OCR serveur). + onFacts = if (current.processed) { + { showFacts = true } + } else { + null + }, modifier = Modifier.fillMaxWidth(), ) } @@ -367,6 +379,14 @@ fun DocumentViewerScreen( onDismiss = { showOcrDialog = false }, ) } + + if (showFacts && currentFile != null) { + FactsBottomSheet( + resourceId = currentFile.resourceId, + resourceName = currentFile.name, + onDismiss = { showFacts = false }, + ) + } } /** @@ -639,6 +659,7 @@ private fun DocumentActionBar( onKeep: () -> Unit, onDeleteModeSelected: (FileDeleter.DeleteMode) -> Unit, onOcr: (() -> Unit)? = null, + onFacts: (() -> Unit)? = null, releasable: Boolean = false, onRelease: (() -> Unit)? = null, modifier: Modifier = Modifier, @@ -709,6 +730,12 @@ private fun DocumentActionBar( onClick = onOcr, ) } + if (onFacts != null) { + DocumentFactsButton( + enabled = !busy, + onClick = onFacts, + ) + } DocumentDeleteMenu( file = file, enabled = !busy, @@ -745,6 +772,31 @@ private fun DocumentReleaseButton( } } +/** Bouton « Compris » V3 S3 — ouvre la fiche des faits génériques (corrigibles). */ +@Composable +private fun DocumentFactsButton( + enabled: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + FilledTonalButton( + onClick = onClick, + enabled = enabled, + modifier = modifier, + ) { + Icon( + imageVector = Icons.Filled.FactCheck, + contentDescription = null, + modifier = Modifier.size(20.dp), + ) + Spacer(Modifier.size(ButtonDefaults.IconSpacing)) + Text( + text = stringResource(R.string.facts_action), + maxLines = 1, + ) + } +} + /** Bouton « OCR » M3 — gabarit adaptatif (plus de Surface 88×48 fixe). */ @Composable private fun DocumentOcrButton( diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/ui/facts/FactsSheet.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/ui/facts/FactsSheet.kt new file mode 100644 index 0000000..64475f5 --- /dev/null +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/ui/facts/FactsSheet.kt @@ -0,0 +1,324 @@ +package com.kazier.mobile.ui.facts + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.AssistChip +import androidx.compose.material3.AssistChipDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +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.input.KeyboardType +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.data.local.entity.FactOrigin +import com.kazier.mobile.data.local.entity.FactType +import com.kazier.mobile.data.local.entity.ResourceFact + +/** + * Fiche « Ce qu'on a compris » (V3 S3) : faits génériques extraits du + * document, avec correction en un tap. + * + * - Confiance < 0.5 → chip grisé + « (suggéré) » (humble par design). + * - Crayon → dialogue d'édition (texte / nombre / date ISO) ; la correction + * devient un fait `user` (badge « corrigé ») et part en outbox. + * - « Rétablir auto » → efface les corrections (l'auto réapparaît). + */ +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) +@Composable +fun FactsBottomSheet( + resourceId: String, + resourceName: String, + onDismiss: () -> Unit, + viewModel: FactsViewModel = hiltViewModel(), +) { + val facts by viewModel.facts.collectAsStateWithLifecycle() + val syncing by viewModel.syncing.collectAsStateWithLifecycle() + val error by viewModel.error.collectAsStateWithLifecycle() + + LaunchedEffect(resourceId) { viewModel.watch(resourceId) } + + var editing by rememberSaveable { mutableStateOf(null) } + var showResetConfirm by rememberSaveable { mutableStateOf(false) } + + val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + val display = remember(facts) { viewModel.displayable(facts) } + val hasUserFacts = remember(facts) { facts.any { it.origin == FactOrigin.USER } } + + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = sheetState, + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp) + .padding(bottom = 24.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = stringResource(R.string.facts_title), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.weight(1f), + ) + if (syncing) { + CircularProgressIndicator(modifier = Modifier.padding(8.dp)) + } else if (hasUserFacts) { + TextButton(onClick = { showResetConfirm = true }) { + Text(stringResource(R.string.facts_reset)) + } + } + } + Text( + text = resourceName, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + error?.let { + Text( + text = it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + if (display.isEmpty() && !syncing) { + Text( + text = stringResource(R.string.facts_empty), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + display.forEach { fact -> + FactChip( + fact = fact, + onEdit = { editing = fact.chipKey() }, + ) + } + } + Spacer(Modifier.height(4.dp)) + } + } + + if (showResetConfirm) { + AlertDialog( + onDismissRequest = { showResetConfirm = false }, + title = { Text(stringResource(R.string.facts_reset_confirm_title)) }, + text = { Text(stringResource(R.string.facts_reset_confirm_message)) }, + confirmButton = { + TextButton(onClick = { + showResetConfirm = false + viewModel.resetToAuto() + }) { Text(stringResource(R.string.facts_reset_confirm)) } + }, + dismissButton = { + TextButton(onClick = { showResetConfirm = false }) { + Text(stringResource(R.string.delete_cancel)) + } + }, + ) + } + + val toEdit = editing?.let { key -> display.firstOrNull { it.chipKey() == key } } + if (toEdit != null) { + FactEditDialog( + fact = toEdit, + onDismiss = { editing = null }, + onSave = { value -> + editing = null + viewModel.saveCorrection(toEdit.withValue(value)) + }, + ) + } +} + +private fun ResourceFact.chipKey(): String = "$factType|$valueText|$valueNum|$valueDate" + +private fun ResourceFact.withValue(value: String): ResourceFact = when (factType) { + FactType.AMOUNT -> copy(valueNum = value.replace(',', '.').toDoubleOrNull(), valueText = null) + FactType.DATE, FactType.DUE_DATE -> copy(valueDate = value.trim(), valueText = null) + else -> copy(valueText = value.trim(), valueNum = null, valueDate = null) +} + +@Composable +private fun FactChip( + fact: ResourceFact, + onEdit: () -> Unit, +) { + val label = factLabel(fact) + val suggested = fact.confidence < 0.5 && fact.origin == FactOrigin.AUTO + AssistChip( + onClick = onEdit, + label = { + Text( + if (suggested) stringResource(R.string.facts_suggested, label) else label, + color = if (suggested) MaterialTheme.colorScheme.onSurfaceVariant + else MaterialTheme.colorScheme.onSurface, + ) + }, + leadingIcon = { + Icon( + Icons.Filled.Edit, + contentDescription = stringResource(R.string.facts_edit), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + }, + colors = AssistChipDefaults.assistChipColors( + containerColor = if (fact.origin == FactOrigin.USER) { + MaterialTheme.colorScheme.primaryContainer + } else { + MaterialTheme.colorScheme.surfaceVariant + }, + ), + ) +} + +@Composable +private fun factLabel(fact: ResourceFact): String { + val kind = stringResource(factTypeLabel(fact.factType)) + val value = when (fact.factType) { + FactType.AMOUNT -> fact.valueNum?.let { formatFactAmount(it) } ?: fact.valueText.orEmpty() + FactType.DATE, FactType.DUE_DATE -> fact.valueDate ?: fact.valueText.orEmpty() + else -> fact.valueText.orEmpty() + } + val corrected = if (fact.origin == FactOrigin.USER) { + " (" + stringResource(R.string.facts_corrected) + ")" + } else { + "" + } + return "$kind : $value$corrected" +} + +private fun factTypeLabel(type: String): Int = when (type) { + FactType.ISSUER -> R.string.facts_type_issuer + FactType.AMOUNT -> R.string.facts_type_amount + FactType.DUE_DATE -> R.string.facts_type_due_date + FactType.DATE -> R.string.facts_type_date + FactType.PERIOD -> R.string.facts_type_period + FactType.REFERENCE -> R.string.facts_type_reference + FactType.DOC_TYPE -> R.string.facts_type_doc_type + else -> R.string.facts_type_other +} + +private fun formatFactAmount(num: Double): String { + val asLong = num.toLong() + return if (num == asLong.toDouble()) "$asLong €" else "$num €" +} + +@Composable +private fun FactEditDialog( + fact: ResourceFact, + onDismiss: () -> Unit, + onSave: (String) -> Unit, +) { + var value by rememberSaveable(fact) { + mutableStateOf( + when (fact.factType) { + FactType.AMOUNT -> fact.valueNum?.toString().orEmpty() + FactType.DATE, FactType.DUE_DATE -> fact.valueDate.orEmpty() + else -> fact.valueText.orEmpty() + }, + ) + } + var invalid by rememberSaveable { mutableStateOf(false) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.facts_edit_title, stringResource(factTypeLabel(fact.factType)))) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField( + value = value, + onValueChange = { value = it; invalid = false }, + label = { Text(stringResource(factValueHint(fact.factType))) }, + singleLine = true, + isError = invalid, + keyboardOptions = KeyboardOptions( + keyboardType = if (fact.factType == FactType.AMOUNT) KeyboardType.Decimal + else KeyboardType.Text, + ), + supportingText = if (invalid) { + { Text(stringResource(R.string.facts_invalid_value)) } + } else null, + ) + if (fact.origin == FactOrigin.AUTO) { + Text( + text = stringResource(R.string.facts_edit_auto_hint), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + }, + confirmButton = { + TextButton(onClick = { + if (!validFactValue(fact.factType, value)) { + invalid = true + } else { + onSave(value) + } + }) { Text(stringResource(R.string.facts_save)) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.delete_cancel)) } + }, + ) +} + +private fun factValueHint(type: String): Int = when (type) { + FactType.AMOUNT -> R.string.facts_hint_amount + FactType.DATE, FactType.DUE_DATE -> R.string.facts_hint_date + else -> R.string.facts_hint_text +} + +private fun validFactValue(type: String, value: String): Boolean { + val v = value.trim() + if (v.isEmpty()) return false + return when (type) { + FactType.AMOUNT -> v.replace(',', '.').toDoubleOrNull()?.let { it > 0 } ?: false + FactType.DATE, FactType.DUE_DATE -> v.matches(Regex("""\d{4}-\d{2}-\d{2}""")) + else -> true + } +} diff --git a/mobile-kotlin/app/src/main/java/com/kazier/mobile/ui/facts/FactsViewModel.kt b/mobile-kotlin/app/src/main/java/com/kazier/mobile/ui/facts/FactsViewModel.kt new file mode 100644 index 0000000..f421b8b --- /dev/null +++ b/mobile-kotlin/app/src/main/java/com/kazier/mobile/ui/facts/FactsViewModel.kt @@ -0,0 +1,108 @@ +package com.kazier.mobile.ui.facts + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.kazier.mobile.data.local.entity.ResourceFact +import com.kazier.mobile.data.local.entity.displayFacts +import com.kazier.mobile.data.repository.FactsRepository +import dagger.hilt.android.lifecycle.HiltViewModel +import javax.inject.Inject +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch +import timber.log.Timber + +/** + * Fiche « Ce qu'on a compris » (V3 S3) : faits génériques d'un document. + * + * [watch] charge le miroir Room puis rafraîchit depuis le serveur + * (best-effort — offline = cache). [saveCorrection] remplace le fait du même + * type dans le jeu `user` (optimiste + outbox `correct_facts`) ; + * [resetToAuto] efface les corrections (l'auto réapparaît à l'affichage). + */ +@HiltViewModel +class FactsViewModel @Inject constructor( + private val factsRepository: FactsRepository, +) : ViewModel() { + + private val resourceId = MutableStateFlow(null) + + @OptIn(ExperimentalCoroutinesApi::class) + val facts: StateFlow> = resourceId + .flatMapLatest { id: String? -> + id?.let { factsRepository.observeFacts(it) } ?: flowOf(emptyList()) + } + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) + + private val _syncing = MutableStateFlow(false) + val syncing: StateFlow = _syncing.asStateFlow() + + private val _error = MutableStateFlow(null) + val error: StateFlow = _error.asStateFlow() + + fun watch(id: String) { + if (resourceId.value == id) { + refresh() + return + } + resourceId.value = id + refresh() + } + + fun refresh() { + val id = resourceId.value ?: return + if (_syncing.value) return + viewModelScope.launch { + _syncing.value = true + runCatching { factsRepository.syncFromServer(id) } + .onFailure { e -> + Timber.d("facts sync failed for %s: %s", id, e.message) + _error.value = e.message ?: e.javaClass.simpleName + } + _syncing.value = false + } + } + + fun clearError() { + _error.value = null + } + + /** Faits affichables (user gagne par type) — voir `displayFacts`. */ + fun displayable(all: List): List = displayFacts(all) + + fun saveCorrection(edited: ResourceFact) { + val id = resourceId.value ?: return + viewModelScope.launch { + runCatching { + val current = factsRepository.getFacts(id) + val users = current + .filter { it.origin == com.kazier.mobile.data.local.entity.FactOrigin.USER } + .associateBy { it.factType } + .toMutableMap() + users[edited.factType] = edited + factsRepository.saveCorrection(id, users.values.toList()) + }.onFailure { e -> + Timber.w(e, "facts correction failed for %s", id) + _error.value = e.message ?: e.javaClass.simpleName + } + } + } + + fun resetToAuto() { + val id = resourceId.value ?: return + viewModelScope.launch { + runCatching { factsRepository.resetToAuto(id) } + .onFailure { e -> + Timber.w(e, "facts reset failed for %s", id) + _error.value = e.message ?: e.javaClass.simpleName + } + } + } +} diff --git a/mobile-kotlin/app/src/main/res/values-en/strings.xml b/mobile-kotlin/app/src/main/res/values-en/strings.xml index d25e389..23494ed 100644 --- a/mobile-kotlin/app/src/main/res/values-en/strings.xml +++ b/mobile-kotlin/app/src/main/res/values-en/strings.xml @@ -392,4 +392,30 @@ Delete forever? This action cannot be undone. The item will be destroyed everywhere. Delete + + Understood + What we understood + Nothing extracted yet — analysis runs after OCR. + %1$s (suggested) + corrected + Correct + Correct: %1$s + Your correction will replace the suggestion and be sent to the server. + Value + Amount in € (e.g. 84.20) + Date YYYY-MM-DD (e.g. 2026-03-12) + Invalid value + Save + Reset to auto + Clear my corrections? + Automatic suggestions will reappear. + Clear + Issuer + Amount + Due date + Date + Period + Reference + Document type + Info \ No newline at end of file diff --git a/mobile-kotlin/app/src/main/res/values/strings.xml b/mobile-kotlin/app/src/main/res/values/strings.xml index 57b7404..4a03c76 100644 --- a/mobile-kotlin/app/src/main/res/values/strings.xml +++ b/mobile-kotlin/app/src/main/res/values/strings.xml @@ -393,4 +393,30 @@ Supprimer définitivement ? Cette action est irréversible. L\'élément sera détruit partout. Supprimer + + Compris + Ce qu\'on a compris + Rien d\'extrait pour l\'instant — l\'analyse tourne après l\'OCR. + %1$s (suggéré) + corrigé + Corriger + Corriger : %1$s + Votre correction remplacera la suggestion et sera envoyée au serveur. + Valeur + Montant en € (ex. 84,20) + Date AAAA-MM-JJ (ex. 2026-03-12) + Valeur invalide + Enregistrer + Rétablir auto + Effacer mes corrections ? + Les suggestions automatiques réapparaîtront. + Effacer + Émetteur + Montant + Échéance + Date + Période + Référence + Type de document + Info \ No newline at end of file diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/local/migration/Migration19To20Test.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/local/migration/Migration19To20Test.kt new file mode 100644 index 0000000..b83d6ff --- /dev/null +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/local/migration/Migration19To20Test.kt @@ -0,0 +1,75 @@ +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.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** + * V3 faits génériques : la migration 19→20 crée `resource_facts` (miroir + * `GET /facts`, remplacement en bloc au sync, corrections `user` en outbox). + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class Migration19To20Test { + + @Test + fun migration_cree_resource_facts() { + val context = ApplicationProvider.getApplicationContext() + val helper = FrameworkSQLiteOpenHelperFactory().create( + SupportSQLiteOpenHelper.Configuration.builder(context) + .name(null) + .callback(V19Callback()) + .build(), + ) + val db = helper.writableDatabase + + val migration = Migrations.ALL.first { it.startVersion == 19 && it.endVersion == 20 } + migration.migrate(db) + + val columns = mutableMapOf() + db.query("PRAGMA table_info(`resource_facts`)").use { cursor -> + val nameIdx = cursor.getColumnIndexOrThrow("name") + val typeIdx = cursor.getColumnIndexOrThrow("type") + while (cursor.moveToNext()) columns[cursor.getString(nameIdx)] = cursor.getString(typeIdx) + } + for (col in listOf("id", "resource_id", "fact_type", "value_text", "value_num", "value_date", "confidence", "origin", "updated_at")) { + assertTrue("colonne $col manquante", columns.containsKey(col)) + } + assertEquals("INTEGER", columns["id"]) + assertEquals("REAL", columns["value_num"]) + + // Idempotence (IF NOT EXISTS) : re-passe sans erreur. + migration.migrate(db) + helper.close() + } + + /** Schéma v19 minimal (sans `resource_facts`). */ + private class V19Callback : SupportSQLiteOpenHelper.Callback(19) { + override fun onCreate(db: SupportSQLiteDatabase) { + db.execSQL( + "CREATE TABLE `files` (" + + "`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + + "`resource_id` TEXT NOT NULL, " + + "`name` TEXT NOT NULL, " + + "`folder_resource_id` TEXT NOT NULL, " + + "`size` INTEGER NOT NULL, " + + "`added_at` INTEGER NOT NULL, " + + "`updated_at` INTEGER NOT NULL)", + ) + } + + override fun onUpgrade( + db: SupportSQLiteDatabase, + oldVersion: Int, + newVersion: Int, + ) = Unit + } +} diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/Auth401Test.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/Auth401Test.kt index ebc2d70..dfc0661 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/Auth401Test.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/Auth401Test.kt @@ -332,6 +332,17 @@ class Auth401Test { versionNo: Int, ): Response> = Response.success(ApiEnvelope()) + override suspend fun listFacts( + fileId: String, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + + override suspend fun correctFacts( + fileId: String, + body: com.kazier.mobile.data.remote.dto.CorrectFactsDto, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + override suspend fun searchFiles( query: String, page: Int?, diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/PaginationTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/PaginationTest.kt index fabfd8f..5ca0efd 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/PaginationTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/PaginationTest.kt @@ -206,6 +206,17 @@ class PaginationTest { versionNo: Int, ): Response> = Response.success(ApiEnvelope()) + override suspend fun listFacts( + fileId: String, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + + override suspend fun correctFacts( + fileId: String, + body: com.kazier.mobile.data.remote.dto.CorrectFactsDto, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + override suspend fun searchFiles( query: String, page: Int?, diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/RemoteContentTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/RemoteContentTest.kt index bbd789c..9d3dd28 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/RemoteContentTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/RemoteContentTest.kt @@ -144,6 +144,12 @@ class RemoteContentTest { override suspend fun restoreVersion(fileId: String, versionNo: Int): Response> = Response.success(ApiEnvelope()) + override suspend fun listFacts(fileId: String): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + + override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response>> = Response.success(ApiEnvelope(data = emptyList())) diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/SessionReloginTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/SessionReloginTest.kt index d3998bd..a950115 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/SessionReloginTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/SessionReloginTest.kt @@ -350,6 +350,12 @@ class SessionReloginTest { override suspend fun restoreVersion(fileId: String, versionNo: Int): Response> = Response.success(ApiEnvelope()) + override suspend fun listFacts(fileId: String): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + + override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response>> = Response.success(ApiEnvelope(data = emptyList())) diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/ShareManagementTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/ShareManagementTest.kt index e216311..b211fa7 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/ShareManagementTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/remote/ShareManagementTest.kt @@ -183,6 +183,12 @@ class ShareManagementTest { override suspend fun restoreVersion(fileId: String, versionNo: Int): Response> = Response.success(ApiEnvelope()) + override suspend fun listFacts(fileId: String): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + + override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response>> = Response.success(ApiEnvelope(data = emptyList())) diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/BytesUploadTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/BytesUploadTest.kt index 02db867..05b750d 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/BytesUploadTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/BytesUploadTest.kt @@ -277,6 +277,12 @@ class BytesUploadTest { override suspend fun restoreVersion(fileId: String, versionNo: Int): Response> = Response.success(ApiEnvelope()) + override suspend fun listFacts(fileId: String): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + + override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response>> = Response.success(ApiEnvelope(data = emptyList())) diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/FactsRepositoryTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/FactsRepositoryTest.kt new file mode 100644 index 0000000..d0bfa9c --- /dev/null +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/FactsRepositoryTest.kt @@ -0,0 +1,213 @@ +package com.kazier.mobile.data.repository + +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.FactsDao +import com.kazier.mobile.data.local.dao.PendingOperationDao +import com.kazier.mobile.data.local.entity.FactOrigin +import com.kazier.mobile.data.local.entity.PendingOperationType +import com.kazier.mobile.data.local.entity.ResourceFact +import com.kazier.mobile.data.remote.ApiClient +import com.kazier.mobile.data.remote.ApiService +import com.kazier.mobile.data.remote.dto.ApiEnvelope +import com.kazier.mobile.data.remote.dto.CorrectFactsDto +import com.kazier.mobile.data.remote.dto.FactDto +import com.kazier.mobile.domain.DeviceIdentity +import com.kazier.mobile.domain.GenerateId +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.Response +import retrofit2.Retrofit +import retrofit2.converter.moshi.MoshiConverterFactory + +/** + * Faits V3 (S3) côté client : sync serveur (remplacement en bloc), + * correction optimiste + op `correct_facts`, reset auto. + */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34]) +class FactsRepositoryTest { + + private lateinit var db: AppDatabase + private lateinit var factsDao: FactsDao + private lateinit var opsDao: PendingOperationDao + private lateinit var outboxRepository: OutboxRepository + private lateinit var factsRepository: FactsRepository + private lateinit var fakeApi: FactsFakeApiService + + @Before + fun setUp() { + val context = ApplicationProvider.getApplicationContext() + db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java) + .allowMainThreadQueries() + .build() + factsDao = db.factsDao() + opsDao = db.pendingOperationDao() + + val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build() + fakeApi = FactsFakeApiService() + val retrofit = Retrofit.Builder() + .baseUrl("http://localhost:1/") + .addConverterFactory(MoshiConverterFactory.create(moshi)) + .build() + // ApiClient réel branché sur le fake (même pattern que OcrRepositoryTest). + val apiClient = ApiClient(fakeApi, moshi) + val generateId = GenerateId() + outboxRepository = OutboxRepository(opsDao, generateId, DeviceIdentity(db.userPreferenceDao(), generateId), moshi) + factsRepository = FactsRepository(db, factsDao, outboxRepository, apiClient) + assertTrue(retrofit.baseUrl().toString().startsWith("http://localhost")) + } + + @After + fun tearDown() { + db.close() + } + + @Test + fun sync_remplace_le_miroir_en_bloc() = runTest { + fakeApi.facts = listOf( + FactDto("issuer", "EDF", null, null, 0.55, "auto"), + FactDto("amount", "84.20 €", 84.2, null, 0.9, "auto"), + ) + factsRepository.syncFromServer(RESOURCE_ID) + + val rows = factsDao.getForResource(RESOURCE_ID) + assertEquals(2, rows.size) + assertTrue(rows.all { it.origin == FactOrigin.AUTO }) + + // Re-passe avec un jeu différent : remplacement, pas d'accumulation. + fakeApi.facts = listOf(FactDto("issuer", "ENGIE", null, null, 0.6, "auto")) + factsRepository.syncFromServer(RESOURCE_ID) + val rows2 = factsDao.getForResource(RESOURCE_ID) + assertEquals(1, rows2.size) + assertEquals("ENGIE", rows2[0].valueText) + } + + @Test + fun correction_optimiste_puis_op_outbox() = runTest { + fakeApi.facts = listOf(FactDto("issuer", "EDF", null, null, 0.55, "auto")) + factsRepository.syncFromServer(RESOURCE_ID) + + // La ressource doit être connue du serveur (create) pour journaliser. + outboxRepository.enqueueCreateResource(RESOURCE_ID, "file", "facture.pdf") + opsDao.markSynced(opsDao.selectPending(10).first().id, NOW) + + factsRepository.saveCorrection( + RESOURCE_ID, + listOf( + ResourceFact( + resourceId = RESOURCE_ID, factType = "issuer", + valueText = "Vrai Fournisseur", confidence = 0.0, + origin = FactOrigin.AUTO, updatedAt = NOW, + ), + ), + ) + + val rows = factsDao.getForResource(RESOURCE_ID) + val users = rows.filter { it.origin == FactOrigin.USER } + assertEquals(1, users.size) + assertEquals("Vrai Fournisseur", users[0].valueText) + assertEquals(1.0, users[0].confidence, 0.0) + // L'auto survit en Room (l'affichage `displayFacts` tranche). + assertEquals(1, rows.count { it.origin == FactOrigin.AUTO }) + + val ops = opsDao.selectPending(10).filter { it.operation == PendingOperationType.CORRECT_FACTS } + assertEquals(1, ops.size) + assertTrue(ops[0].payload.contains("Vrai Fournisseur")) + } + + @Test + fun correction_sans_create_reste_purement_locale() = runTest { + factsRepository.saveCorrection( + RESOURCE_ID, + listOf( + ResourceFact( + resourceId = RESOURCE_ID, factType = "issuer", + valueText = "Local", confidence = 0.0, + origin = FactOrigin.AUTO, updatedAt = NOW, + ), + ), + ) + assertEquals(1, factsDao.getForResource(RESOURCE_ID).count { it.origin == FactOrigin.USER }) + assertTrue(opsDao.selectPending(10).none { it.operation == PendingOperationType.CORRECT_FACTS }) + } + + @Test + fun reset_efface_les_corrections() = runTest { + fakeApi.facts = listOf(FactDto("issuer", "EDF", null, null, 0.55, "auto")) + factsRepository.syncFromServer(RESOURCE_ID) + outboxRepository.enqueueCreateResource(RESOURCE_ID, "file", "facture.pdf") + + factsRepository.saveCorrection( + RESOURCE_ID, + listOf( + ResourceFact( + resourceId = RESOURCE_ID, factType = "issuer", + valueText = "X", confidence = 0.0, + origin = FactOrigin.AUTO, updatedAt = NOW, + ), + ), + ) + assertEquals(1, factsDao.getForResource(RESOURCE_ID).count { it.origin == FactOrigin.USER }) + + factsRepository.resetToAuto(RESOURCE_ID) + val rows = factsDao.getForResource(RESOURCE_ID) + assertTrue(rows.none { it.origin == FactOrigin.USER }) + assertEquals(1, rows.count { it.origin == FactOrigin.AUTO }) + } + + class FactsFakeApiService : ApiService { + var facts: List = emptyList() + + override suspend fun listFacts(fileId: String): Response>> = + Response.success(ApiEnvelope(data = facts)) + + override suspend fun listFolders(): Response>> = TODO() + override suspend fun listFiles(folderId: String?, page: Int?, pageSize: Int?): Response>> = TODO() + override suspend fun registerDevice(body: com.kazier.mobile.data.remote.dto.DeviceRegistrationDto): Response> = TODO() + override suspend fun login(body: com.kazier.mobile.data.remote.dto.LoginRequestDto): Response> = TODO() + override suspend fun syncOps(body: com.kazier.mobile.data.remote.dto.SyncOpsRequest): Response> = TODO() + override suspend fun resolveUser(username: String): Response> = TODO() + override suspend fun syncPermissions(after: Long?): Response>> = TODO() + override suspend fun uploadFile(file: okhttp3.MultipartBody.Part, resourceId: okhttp3.RequestBody?, folderId: okhttp3.RequestBody?): Response> = TODO() + override suspend fun submitOcr(body: com.kazier.mobile.data.remote.dto.OcrSubmitDto): Response> = TODO() + override suspend fun getOcrJob(jobId: String): Response> = TODO() + override suspend fun getFileOcr(fileId: String): Response> = TODO() + override suspend fun getFile(fileId: String): Response> = TODO() + override suspend fun downloadContent(fileId: String): Response = TODO() + override suspend fun deleteFile(fileId: String): Response> = TODO() + override suspend fun listTrash(page: Int?, pageSize: Int?): Response>> = TODO() + override suspend fun restoreFile(fileId: String): Response> = TODO() + override suspend fun listVersions(fileId: String): Response>> = TODO() + override suspend fun restoreVersion(fileId: String, versionNo: Int): Response> = TODO() + override suspend fun correctFacts(fileId: String, body: CorrectFactsDto): Response>> = TODO() + override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response>> = TODO() + override suspend fun changePassword(body: com.kazier.mobile.data.remote.dto.ChangePasswordDto): Response> = TODO() + override suspend fun getShareLink(token: String): Response> = TODO() + override suspend fun listShares(fileId: String): Response>> = TODO() + override suspend fun listLinks(fileId: String): Response>> = TODO() + override suspend fun listPlacements(fileId: String): Response>> = TODO() + override suspend fun createGroup(body: com.kazier.mobile.data.remote.dto.CreateGroupDto): Response> = TODO() + override suspend fun listGroups(): Response>> = TODO() + override suspend fun addGroupMember(groupId: String, body: com.kazier.mobile.data.remote.dto.AddGroupMemberDto): Response> = TODO() + override suspend fun listGroupMembers(groupId: String): Response>> = TODO() + override suspend fun removeGroupMember(groupId: String, userId: String): Response> = TODO() + override suspend fun deleteGroup(groupId: String): Response> = TODO() + } + + companion object { + private const val RESOURCE_ID = "facts-res-1" + private const val NOW = 1_700_000_000_000L + } +} diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/FolderMergeDataTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/FolderMergeDataTest.kt index b600797..56a86fd 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/FolderMergeDataTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/FolderMergeDataTest.kt @@ -392,6 +392,17 @@ private class FolderMergeApiService : ApiService { versionNo: Int, ): Response> = Response.success(ApiEnvelope()) + override suspend fun listFacts( + fileId: String, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + + override suspend fun correctFacts( + fileId: String, + body: com.kazier.mobile.data.remote.dto.CorrectFactsDto, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + override suspend fun searchFiles( query: String, page: Int?, diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/MoveProtectionTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/MoveProtectionTest.kt index 0e70bda..f41ff6f 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/MoveProtectionTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/MoveProtectionTest.kt @@ -481,6 +481,17 @@ private class MoveProtectionApiService : ApiService { versionNo: Int, ): Response> = Response.success(ApiEnvelope()) + override suspend fun listFacts( + fileId: String, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + + override suspend fun correctFacts( + fileId: String, + body: com.kazier.mobile.data.remote.dto.CorrectFactsDto, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + override suspend fun searchFiles( query: String, page: Int?, diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/OcrRepositoryTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/OcrRepositoryTest.kt index ebb67c8..a56bc82 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/OcrRepositoryTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/OcrRepositoryTest.kt @@ -393,6 +393,17 @@ private class OcrApiServiceFake : ApiService { versionNo: Int, ): Response> = Response.success(ApiEnvelope()) + override suspend fun listFacts( + fileId: String, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + + override suspend fun correctFacts( + fileId: String, + body: com.kazier.mobile.data.remote.dto.CorrectFactsDto, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + override suspend fun searchFiles( query: String, page: Int?, diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/OfflineDownloadTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/OfflineDownloadTest.kt index 60757b7..57f8443 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/OfflineDownloadTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/OfflineDownloadTest.kt @@ -285,6 +285,12 @@ class OfflineDownloadTest { override suspend fun restoreVersion(fileId: String, versionNo: Int): Response> = Response.success(ApiEnvelope()) + override suspend fun listFacts(fileId: String): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + + override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response>> = Response.success(ApiEnvelope(data = emptyList())) diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/RefreshVsMoveTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/RefreshVsMoveTest.kt index 35f1da3..4058881 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/RefreshVsMoveTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/RefreshVsMoveTest.kt @@ -248,6 +248,17 @@ private class RefreshVsMoveApiService : ApiService { versionNo: Int, ): Response> = Response.success(ApiEnvelope()) + override suspend fun listFacts( + fileId: String, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + + override suspend fun correctFacts( + fileId: String, + body: com.kazier.mobile.data.remote.dto.CorrectFactsDto, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + override suspend fun searchFiles( query: String, page: Int?, diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/ShareRepositoryTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/ShareRepositoryTest.kt index c300d0a..16b86d6 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/ShareRepositoryTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/data/repository/ShareRepositoryTest.kt @@ -502,6 +502,17 @@ private class FakeApiService : ApiService { versionNo: Int, ): Response> = Response.success(ApiEnvelope()) + override suspend fun listFacts( + fileId: String, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + + override suspend fun correctFacts( + fileId: String, + body: com.kazier.mobile.data.remote.dto.CorrectFactsDto, + ): Response>> = + Response.success(ApiEnvelope(data = emptyList())) + override suspend fun searchFiles( query: String, page: Int?, diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/features/saf/ReleaseLocalCopyTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/features/saf/ReleaseLocalCopyTest.kt index 72b7365..73002f4 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/features/saf/ReleaseLocalCopyTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/features/saf/ReleaseLocalCopyTest.kt @@ -159,6 +159,8 @@ class ReleaseLocalCopyTest { override suspend fun restoreFile(fileId: String): retrofit2.Response> = TODO() override suspend fun listVersions(fileId: String): retrofit2.Response>> = TODO() override suspend fun restoreVersion(fileId: String, versionNo: Int): retrofit2.Response> = TODO() + override suspend fun listFacts(fileId: String): retrofit2.Response>> = TODO() + override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): retrofit2.Response>> = TODO() override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): retrofit2.Response>> = TODO() override suspend fun changePassword(body: com.kazier.mobile.data.remote.dto.ChangePasswordDto): retrofit2.Response> = TODO() override suspend fun getShareLink(token: String): retrofit2.Response> = TODO() diff --git a/mobile-kotlin/app/src/test/java/com/kazier/mobile/features/sync/OutboxSyncWorkerTest.kt b/mobile-kotlin/app/src/test/java/com/kazier/mobile/features/sync/OutboxSyncWorkerTest.kt index 53fe6c9..9a75869 100644 --- a/mobile-kotlin/app/src/test/java/com/kazier/mobile/features/sync/OutboxSyncWorkerTest.kt +++ b/mobile-kotlin/app/src/test/java/com/kazier/mobile/features/sync/OutboxSyncWorkerTest.kt @@ -507,6 +507,12 @@ class OutboxSyncWorkerTest { override suspend fun restoreVersion(fileId: String, versionNo: Int): Response> = throw UnsupportedOperationException() + override suspend fun listFacts(fileId: String): Response>> = + throw UnsupportedOperationException() + + override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response>> = + throw UnsupportedOperationException() + override suspend fun searchFiles( query: String, page: Int?,