V3 S5 : graphe documentaire + doublons + collections

Backend : resource_links + scan_session_id (000021), réconciliation
déterministe (same_scan outbox, doublons SHA-256 à l'upload + backfill,
same_issuer/référence via faits effectifs, verdicts préservés, élagage
auto), GET /files/:id/relations + verdict (owner-only),
GET /duplicates (groupes + gain récupérable). Tests service + handlers
+ migrations.

Mobile (Room v22) : links + collections, scanSessionId dans les creates
de scan, LinksRepository (sync + verdicts REST), « Voir aussi » dans la
fiche (verdict infirmer/re-confirmer), écran Doublons (garder le plus
récent), collections locales (sauver/rejouer/supprimer). FR/EN.

Contrat docs/api-v1.md (/relations, pas /links — pris par le partage),
V3.md (S5 livré, version_of non matérialisé).
This commit is contained in:
venture
2026-09-26 11:16:35 +02:00
parent 2d984fd665
commit 37dc36f1f2
66 changed files with 3933 additions and 34 deletions
+2 -2
View File
@@ -24,7 +24,7 @@ func TestFactsEndpoint(t *testing.T) {
t.Fatalf("ocr text: %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 {
if err := extractSvc.ProcessText(userID, fileID, "EDF\nFacture n° F-1 du 01/02/2026\nTotal : 10,00 €\n"); err != nil {
t.Fatalf("extract: %v", err)
}
_ = store
@@ -95,7 +95,7 @@ func TestCorrectFactsEndpoint(t *testing.T) {
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 {
if err := extractSvc.ProcessText(userID, fileID, "EDF\nFacture n° F-1 du 01/02/2026\nTotal : 10,00 €\n"); err != nil {
t.Fatalf("extract: %v", err)
}
_ = store
+90
View File
@@ -183,6 +183,96 @@ func FilesCorrectFacts(c *gin.Context) {
api.OK(c, facts)
}
// RelationsList expose le graphe documentaire d'une ressource possédée
// (V3 S5) : `GET /files/:id/relations`. Réconcilie d'abord (les arêtes
// déterministes convergent à la lecture), puis renvoie les arêtes vivantes
// (l'autre bout non trashé), confiance décroissante. Owner-only : le graphe
// d'autrui ne s'énumère pas (404, comme `/shares`).
func RelationsList(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
}
relations, err := Store.ListRelations(userID, id)
if err != nil {
writeError(c, err)
return
}
if relations == nil {
relations = []service.RelationDTO{}
}
api.OK(c, relations)
}
// RelationVerdict enregistre un verdict explicite sur une arête (V3 S5) :
// `POST /files/:id/relations/verdict { otherId, linkType, confirmed }`.
// Confirmé → 1.0, infirmé → 0.0 (conservé, bloque la re-création auto).
// Owner-only, les deux bouts possédés et vifs, sinon 404 ; type/paire
// invalide → 400.
func RelationVerdict(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 {
OtherID string `json:"otherId"`
LinkType string `json:"linkType"`
Confirmed bool `json:"confirmed"`
}
if err := c.ShouldBindJSON(&req); err != nil {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid JSON body (expected { otherId, linkType, confirmed })")
return
}
if !deviceIDPattern.MatchString(req.OtherID) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid `otherId` (32 lowercase hex)")
return
}
if err := Store.LinkVerdict(userID, id, req.OtherID, req.LinkType, req.Confirmed); err != nil {
if errors.Is(err, service.ErrInvalidLinkType) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", err.Error())
return
}
writeError(c, err)
return
}
relations, err := Store.ListRelations(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, relations)
}
// DuplicatesList expose les doublons d'octets du compte (V3 S5 B2) :
// `GET /duplicates`. Groupes par hash, plus gros d'abord, avec le gain
// récupérable (« garder un seul »). Scope owner — `[]` quand propre.
func DuplicatesList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
groups, err := Store.ListDuplicates(userID)
if err != nil {
writeError(c, err)
return
}
api.OK(c, groups)
}
// FilesContent streame les octets physiques d'un fichier visible (viewer+,
// 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
+93
View File
@@ -0,0 +1,93 @@
package handlers_test
import (
"encoding/json"
"fmt"
"net/http"
"testing"
"github.com/kazier/backend/repository"
)
// TestRelationsEndpoints : GET /files/:id/relations (réconciliation à la
// lecture) + POST verdict (confirmé/infirmé, 400/404).
func TestRelationsEndpoints(t *testing.T) {
r, _, repo := setup(t)
device := repository.NewID()
token, userID := registerAndLogin(t, r, repo, testUserUsername(device, "rl"), "relations-test-password", device)
session := repository.NewID()
page1, page2 := repository.NewID(), repository.NewID()
for _, id := range []string{page1, page2} {
if err := repo.Resources.InsertFile(userID, id, id+".png", "", 0, nil, nil); err != nil {
t.Fatalf("insert: %v", err)
}
if err := repo.Resources.SetScanSession(userID, id, session); err != nil {
t.Fatalf("session: %v", err)
}
}
rec, _ := doRequest(t, r, http.MethodGet, "/api/v1/files/"+page1+"/relations", token, nil, "")
env := expectOK(t, rec, "relations-get")
var rels []struct {
ID string `json:"id"`
OtherID string `json:"otherId"`
Type string `json:"type"`
Confidence float64 `json:"confidence"`
CreatedBy string `json:"createdBy"`
OtherName string `json:"otherName"`
}
if err := json.Unmarshal(env.Data, &rels); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if len(rels) != 1 || rels[0].Type != "same_scan" || rels[0].OtherID != page2 {
t.Fatalf("relations inattendues: %+v", rels)
}
// Verdict infirmé : arête conservée à 0.0, origine user.
body := fmt.Sprintf(`{"otherId":%q,"linkType":"same_scan","confirmed":false}`, page2)
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/files/"+page1+"/relations/verdict", token, []byte(body), "application/json")
env = expectOK(t, rec, "relations-verdict")
rels = nil
if err := json.Unmarshal(env.Data, &rels); err != nil {
t.Fatalf("unmarshal verdict: %v", err)
}
if len(rels) != 1 || rels[0].Confidence != 0 || rels[0].CreatedBy != "user" {
t.Fatalf("verdict inattendu: %+v", rels)
}
// Type inconnu → 400 ; paire non-hex → 400 ; étranger → 404.
for _, tc := range []struct {
name, body string
status int
code string
}{
{"type", fmt.Sprintf(`{"otherId":%q,"linkType":"copains","confirmed":true}`, page2), http.StatusBadRequest, "INVALID_REQUEST"},
{"hex", `{"otherId":"nope","linkType":"same_scan","confirmed":true}`, http.StatusBadRequest, "INVALID_REQUEST"},
} {
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/files/"+page1+"/relations/verdict", token, []byte(tc.body), "application/json")
expectError(t, rec, tc.status, tc.code, "relations-verdict-400:"+tc.name)
}
deviceB := repository.NewID()
tokenB, _ := registerAndLogin(t, r, repo, testUserUsername(deviceB, "rb"), "relations-test-password", deviceB)
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+page1+"/relations", tokenB, nil, "")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "relations-foreign")
rec, _ = doRequest(t, r, http.MethodPost, "/api/v1/files/"+page1+"/relations/verdict", tokenB,
[]byte(fmt.Sprintf(`{"otherId":%q,"linkType":"same_scan","confirmed":true}`, page2)), "application/json")
expectError(t, rec, http.StatusNotFound, "NOT_FOUND", "relations-verdict-foreign")
// Trashé → 404 (l'autre bout trashé disparaît aussi de la liste).
if err := repo.Resources.TrashResource(userID, page2); err != nil {
t.Fatalf("trash: %v", err)
}
rec, _ = doRequest(t, r, http.MethodGet, "/api/v1/files/"+page1+"/relations", token, nil, "")
env = expectOK(t, rec, "relations-trashed-other")
rels = nil
if err := json.Unmarshal(env.Data, &rels); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if len(rels) != 0 {
t.Fatalf("bout trashé encore listé: %+v", rels)
}
}
+3
View File
@@ -40,6 +40,9 @@ func RegisterRoutes(r *gin.Engine) {
protected.GET("/files/:id/links", LinksList)
protected.GET("/files/:id/placements", PlacementsList)
protected.GET("/files/:id/versions", VersionsList)
protected.GET("/files/:id/relations", RelationsList)
protected.POST("/files/:id/relations/verdict", RelationVerdict)
protected.GET("/duplicates", DuplicatesList)
protected.POST("/files/:id/restore", FilesRestore)
protected.POST("/files/:id/versions/:n/restore", VersionRestore)
protected.GET("/trash", TrashList)