Files
Kazier/backend/handlers/files.go
T
venture 2d984fd665 V3 S4 : recherche FTS + facettes (serveur + mobile)
Backend : search_tsv french + GIN (000020), SearchDocumentsVisible
(nom + TS + faits, rang nom > TS > fait sûr > fait douteux, jamais
d'exclusion), facettes issuer/type/montant/période sur
GET /files/search (400 si malformée). Tests repo + handlers + migrations.

Mobile (Room v21) : FTS4 files_fts + triggers partagés
(fresh-install/migration, entité déclarée pour KSP, SQL aligné 21.json),
searchDocuments offline (même rang, accents préservés) + UI filtres
(émetteur, types chips, montants, période ISO, compteur, effacer).

Contrat docs/api-v1.md, V3.md (S4 livré, migrations renumérotées
links->000021, token->000022).
2026-09-26 10:53:56 +02:00

463 lines
14 KiB
Go

package handlers
import (
"errors"
"net/http"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/kazier/backend/pkg/api"
"github.com/kazier/backend/repository"
"github.com/kazier/backend/service"
)
// parsePageParams valide page/pageSize (400 si garbage, cf. FEEDBACK A7/A16)
// au lieu du fallback silencieux. Cap pageSize 200 et offset 100000.
func parsePageParams(c *gin.Context) (page, pageSize int, ok bool) {
page = 1
pageSize = 50
if v := c.Query("page"); v != "" {
p, err := strconv.Atoi(v)
if err != nil || p < 1 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid query param `page`")
return 0, 0, false
}
page = p
}
if v := c.Query("pageSize"); v != "" {
ps, err := strconv.Atoi(v)
if err != nil || ps < 1 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid query param `pageSize`")
return 0, 0, false
}
pageSize = ps
}
if pageSize > 200 {
pageSize = 200
}
if (page-1)*pageSize > 100000 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "page offset too large")
return 0, 0, false
}
return page, pageSize, true
}
func FilesList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
page, pageSize, ok := parsePageParams(c)
if !ok {
return
}
folderID := c.Query("folderId")
if folderID != "" && !deviceIDPattern.MatchString(folderID) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid query param `folderId`")
return
}
files, total, err := Store.ListFiles(userID, folderID, page, pageSize, c.Query("sort"), c.Query("order"))
if err != nil {
writeError(c, err)
return
}
api.OKList(c, files, page, pageSize, total)
}
func FilesGet(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
}
file, err := Store.GetFile(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, file)
}
// FilesGetOcr expose l'extrait OCR server-side d'un fichier visible (viewer+,
// own ou shared) : GET /files/:id/ocr. Réponse { text } ("" si pas encore
// extrait) + updatedAt. Permet à un second device de récupérer le texte déjà
// calculé sans re-téléverser les octets (cf. docs/api-v1.md §5).
func FilesGetOcr(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
}
dto, err := Store.GetFileOcr(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, dto)
}
// FilesGetFacts expose les faits génériques d'un fichier visible (V3 S2) :
// GET /files/:id/facts. Même portée que l'OCR (viewer+, own ou shared) —
// les faits dérivent du texte. `[]` si rien d'extractible (jamais 404 pour
// un fichier visible sans faits) ; 404 si trashé/absent/étranger.
func FilesGetFacts(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
}
facts, err := Store.GetFacts(userID, id)
if err != nil {
writeError(c, err)
return
}
if facts == nil {
facts = []service.FactDTO{}
}
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
// metadata-only jamais uploadée) → 404 NOT_FOUND, comme invisible (pas
// d'énumération). V1 streaming : le client ne persiste rien.
func FilesContent(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
}
info, err := Store.OpenContent(userID, id)
if err != nil {
writeError(c, err)
return
}
c.Header("Content-Type", info.MimeType)
c.Header("Content-Disposition", "inline; filename=\""+info.Name+"\"")
c.File(info.Path)
}
func FilesDelete(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
}
// V3 corbeille : DELETE = trash par défaut ; ?mode=purge = destruction
// définitive (lignes + versions + octets). Mode inconnu → 400.
var deletedID string
var err error
switch c.Query("mode") {
case "", "trash":
deletedID, err = Store.Trash(userID, id)
case "purge":
deletedID, err = Store.Purge(userID, id)
default:
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid query param `mode` (trash|purge)")
return
}
if err != nil {
writeError(c, err)
return
}
api.OK(c, gin.H{"id": deletedID})
}
// FilesRestore restaure une ressource trashée (POST /files/:id/restore).
// Absente/étrangère → 404 NOT_FOUND ; déjà vivante → succès idempotent.
func FilesRestore(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
}
restoredID, err := Store.Restore(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, gin.H{"id": restoredID})
}
// TrashList expose la corbeille (GET /trash) : ressources trashées du user,
// les plus récentes d'abord, paginé comme les autres listes.
func TrashList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
page, pageSize, ok := parsePageParams(c)
if !ok {
return
}
items, total, err := Store.ListTrashed(userID, page, pageSize)
if err != nil {
writeError(c, err)
return
}
api.OKList(c, items, page, pageSize, total)
}
// VersionsList expose l'historique des octets (GET /files/:id/versions),
// le plus récent d'abord. Ressource trashée/absente/étrangère → 404.
func VersionsList(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
}
versions, err := Store.ListVersions(userID, id)
if err != nil {
writeError(c, err)
return
}
api.OK(c, versions)
}
// VersionRestore recopie la génération n vers le live
// (POST /files/:id/versions/:n/restore). Génération inconnue → 404.
func VersionRestore(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
}
n, err := strconv.Atoi(c.Param("n"))
if err != nil || n < 1 {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "version not found")
return
}
dto, err := Store.RestoreVersion(userID, id, n)
if err != nil {
writeError(c, err)
return
}
api.OK(c, dto)
}
func FilesUpload(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
folderID := c.PostForm("folderId")
if folderID != "" && !deviceIDPattern.MatchString(folderID) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid `folderId`")
return
}
// resourceId optionnel : cible un fichier déjà connu (metadata-only de
// l'outbox) pour lui attacher ses octets physiques (ex. OCR serveur).
resourceID := c.PostForm("resourceId")
if resourceID != "" && !deviceIDPattern.MatchString(resourceID) {
api.Error(c, http.StatusNotFound, "NOT_FOUND", "file not found")
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, Store.MaxFileSize+1)
file, err := c.FormFile("file")
if err != nil {
var maxBytesErr *http.MaxBytesError
if errors.As(err, &maxBytesErr) {
api.Error(c, http.StatusRequestEntityTooLarge, "FILE_TOO_LARGE", "file exceeds the maximum allowed size")
return
}
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "missing multipart field `file`")
return
}
if file.Size > Store.MaxFileSize {
api.Error(c, http.StatusRequestEntityTooLarge, "FILE_TOO_LARGE", "file exceeds the maximum allowed size")
return
}
dto, err := Store.Upload(userID, file, folderID, resourceID)
if err != nil {
// Nom/extension rejetés côté service (TrimSpace, cap 255,
// anti-slash/retour-ligne, cf. FEEDBACK A16) → 400, jamais 500.
if errors.Is(err, service.ErrInvalidUpload) {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "invalid file name")
return
}
writeError(c, err)
return
}
api.OK(c, dto)
}
func FoldersList(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
folders, err := Store.ListRootFolders(userID)
if err != nil {
writeError(c, err)
return
}
api.OK(c, folders)
}
func FilesSearch(c *gin.Context) {
if Store == nil {
api.Error(c, http.StatusServiceUnavailable, "SERVICE_UNAVAILABLE", "backend not initialized")
return
}
userID := c.GetString(UserIDKey)
q := strings.TrimSpace(c.Query("q"))
if q == "" {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "missing required query param `q`")
return
}
if len(q) > 200 {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "query param `q` too long (max 200)")
return
}
page, pageSize, ok := parsePageParams(c)
if !ok {
return
}
facets, ok := parseSearchFacets(c)
if !ok {
return
}
files, total, err := Store.SearchFiles(userID, q, page, pageSize, facets)
if err != nil {
writeError(c, err)
return
}
api.OKList(c, files, page, pageSize, total)
}
// parseSearchFacets lit les facettes V3 (`issuer`, `from`/`to` ISO,
// `min_amount`/`max_amount` numériques, `doc_type`) — 400 si malformées.
func parseSearchFacets(c *gin.Context) (repository.SearchFacets, bool) {
var facets repository.SearchFacets
facets.Issuer = strings.TrimSpace(c.Query("issuer"))
facets.DocType = strings.TrimSpace(c.Query("doc_type"))
if v := strings.TrimSpace(c.Query("from")); v != "" {
if _, err := time.Parse("2006-01-02", v); err != nil {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "query param `from` must be ISO YYYY-MM-DD")
return facets, false
}
facets.From = v
}
if v := strings.TrimSpace(c.Query("to")); v != "" {
if _, err := time.Parse("2006-01-02", v); err != nil {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "query param `to` must be ISO YYYY-MM-DD")
return facets, false
}
facets.To = v
}
if v := strings.TrimSpace(c.Query("min_amount")); v != "" {
f, err := strconv.ParseFloat(strings.ReplaceAll(v, ",", "."), 64)
if err != nil {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "query param `min_amount` must be numeric")
return facets, false
}
facets.MinAmount = &f
}
if v := strings.TrimSpace(c.Query("max_amount")); v != "" {
f, err := strconv.ParseFloat(strings.ReplaceAll(v, ",", "."), 64)
if err != nil {
api.Error(c, http.StatusBadRequest, "INVALID_REQUEST", "query param `max_amount` must be numeric")
return facets, false
}
facets.MaxAmount = &f
}
return facets, true
}