V3 S3 : correction des faits (fiche document + correct_facts)

Backend : CorrectFacts (editor+, validation Go -> 400 jamais 500),
op outbox correct_facts (full-replace jeu user), PATCH
/files/:id/facts (renvoie jeu complet). Tests service + sync + handlers.

Mobile (Room v20) : table resource_facts + FactsDao, FactsRepository
(sync remplace-en-bloc, correction optimiste + outbox atomique),
fiche « Ce qu'on a compris » sur le viewer (chips, suggéré grisé,
édition par type, reset auto), bouton viewer si processed, FR/EN.

Contrat docs/api-v1.md, V3.md (S1-S3 livrés, FTS -> v21).
This commit is contained in:
venture
2026-09-26 10:28:33 +02:00
parent 95b4cf79cf
commit ac8bd9acb4
45 changed files with 2554 additions and 15 deletions
@@ -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
@@ -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<List<ResourceFact>>
@Query("SELECT * FROM resource_facts WHERE resource_id = :resourceId ORDER BY fact_type ASC, value_text ASC")
suspend fun getForResource(resourceId: String): List<ResourceFact>
@Insert
suspend fun insertAll(facts: List<ResourceFact>)
/** 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)
}
@@ -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"
}
@@ -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<ResourceFact>): List<ResourceFact> {
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
}
@@ -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<Migration> = arrayOf(
MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_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,
)
}
@@ -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<VersionDto> =
unwrap({ apiService.listVersions(fileId) })
/** Faits génériques V3 — `GET /files/:id/facts` (`[]` si vide). */
suspend fun listFacts(fileId: String): List<FactDto> =
unwrap({ apiService.listFacts(fileId) })
/** Remplace le jeu `user` — `PATCH /files/:id/facts` (full-replace). */
suspend fun correctFacts(fileId: String, facts: List<FactDto>): List<FactDto> =
unwrap({ apiService.correctFacts(fileId, CorrectFactsDto(facts)) })
/** Recherche serveur paginée — `GET /files/search?q=…` (+ `meta`). */
suspend fun searchFilesPaged(
query: String,
@@ -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<ApiEnvelope<FileDto>>
/**
* 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<ApiEnvelope<List<FactDto>>>
/**
* 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<ApiEnvelope<List<FactDto>>>
/**
* Recherche serveur (`GET /files/search?q=…`, paginé `meta`). Non consommée
* en V1 (recherche 100 % locale via Room) — exposée pour parité contrat.
@@ -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<FactDto>,
)
@@ -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<List<ResourceFact>> =
factsDao.observeForResource(resourceId)
suspend fun getFacts(resourceId: String): List<ResourceFact> =
factsDao.getForResource(resourceId)
/** Rapatrie le jeu serveur (auto + user) et remplace le miroir local. */
suspend fun syncFromServer(resourceId: String): List<ResourceFact> {
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<ResourceFact>) {
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<String, Any?> = buildMap {
put("factType", factType)
valueText?.let { put("valueText", it) }
valueNum?.let { put("valueNum", it) }
valueDate?.let { put("valueDate", it) }
put("confidence", confidence)
}
}
@@ -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<Map<String, Any?>>,
): 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.
@@ -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()
}
@@ -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(
@@ -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<String?>(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
}
}
@@ -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<String?>(null)
@OptIn(ExperimentalCoroutinesApi::class)
val facts: StateFlow<List<ResourceFact>> = 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<Boolean> = _syncing.asStateFlow()
private val _error = MutableStateFlow<String?>(null)
val error: StateFlow<String?> = _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<ResourceFact>): List<ResourceFact> = 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
}
}
}
}
@@ -392,4 +392,30 @@
<string name="trash_purge_confirm_title">Delete forever?</string>
<string name="trash_purge_confirm_message">This action cannot be undone. The item will be destroyed everywhere.</string>
<string name="trash_purge_confirm">Delete</string>
<!-- Facts V3 S3 -->
<string name="facts_action">Understood</string>
<string name="facts_title">What we understood</string>
<string name="facts_empty">Nothing extracted yet — analysis runs after OCR.</string>
<string name="facts_suggested">%1$s (suggested)</string>
<string name="facts_corrected">corrected</string>
<string name="facts_edit">Correct</string>
<string name="facts_edit_title">Correct: %1$s</string>
<string name="facts_edit_auto_hint">Your correction will replace the suggestion and be sent to the server.</string>
<string name="facts_hint_text">Value</string>
<string name="facts_hint_amount">Amount in € (e.g. 84.20)</string>
<string name="facts_hint_date">Date YYYY-MM-DD (e.g. 2026-03-12)</string>
<string name="facts_invalid_value">Invalid value</string>
<string name="facts_save">Save</string>
<string name="facts_reset">Reset to auto</string>
<string name="facts_reset_confirm_title">Clear my corrections?</string>
<string name="facts_reset_confirm_message">Automatic suggestions will reappear.</string>
<string name="facts_reset_confirm">Clear</string>
<string name="facts_type_issuer">Issuer</string>
<string name="facts_type_amount">Amount</string>
<string name="facts_type_due_date">Due date</string>
<string name="facts_type_date">Date</string>
<string name="facts_type_period">Period</string>
<string name="facts_type_reference">Reference</string>
<string name="facts_type_doc_type">Document type</string>
<string name="facts_type_other">Info</string>
</resources>
@@ -393,4 +393,30 @@
<string name="trash_purge_confirm_title">Supprimer définitivement ?</string>
<string name="trash_purge_confirm_message">Cette action est irréversible. L\'élément sera détruit partout.</string>
<string name="trash_purge_confirm">Supprimer</string>
<!-- Faits V3 S3 -->
<string name="facts_action">Compris</string>
<string name="facts_title">Ce qu\'on a compris</string>
<string name="facts_empty">Rien d\'extrait pour l\'instant — l\'analyse tourne après l\'OCR.</string>
<string name="facts_suggested">%1$s (suggéré)</string>
<string name="facts_corrected">corrigé</string>
<string name="facts_edit">Corriger</string>
<string name="facts_edit_title">Corriger : %1$s</string>
<string name="facts_edit_auto_hint">Votre correction remplacera la suggestion et sera envoyée au serveur.</string>
<string name="facts_hint_text">Valeur</string>
<string name="facts_hint_amount">Montant en € (ex. 84,20)</string>
<string name="facts_hint_date">Date AAAA-MM-JJ (ex. 2026-03-12)</string>
<string name="facts_invalid_value">Valeur invalide</string>
<string name="facts_save">Enregistrer</string>
<string name="facts_reset">Rétablir auto</string>
<string name="facts_reset_confirm_title">Effacer mes corrections ?</string>
<string name="facts_reset_confirm_message">Les suggestions automatiques réapparaîtront.</string>
<string name="facts_reset_confirm">Effacer</string>
<string name="facts_type_issuer">Émetteur</string>
<string name="facts_type_amount">Montant</string>
<string name="facts_type_due_date">Échéance</string>
<string name="facts_type_date">Date</string>
<string name="facts_type_period">Période</string>
<string name="facts_type_reference">Référence</string>
<string name="facts_type_doc_type">Type de document</string>
<string name="facts_type_other">Info</string>
</resources>
@@ -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<Context>()
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<String, String>()
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
}
}
@@ -332,6 +332,17 @@ class Auth401Test {
versionNo: Int,
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
override suspend fun listFacts(
fileId: String,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun correctFacts(
fileId: String,
body: com.kazier.mobile.data.remote.dto.CorrectFactsDto,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun searchFiles(
query: String,
page: Int?,
@@ -206,6 +206,17 @@ class PaginationTest {
versionNo: Int,
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
override suspend fun listFacts(
fileId: String,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun correctFacts(
fileId: String,
body: com.kazier.mobile.data.remote.dto.CorrectFactsDto,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun searchFiles(
query: String,
page: Int?,
@@ -144,6 +144,12 @@ class RemoteContentTest {
override suspend fun restoreVersion(fileId: String, versionNo: Int): Response<ApiEnvelope<FileDto>> =
Response.success(ApiEnvelope())
override suspend fun listFacts(fileId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
@@ -350,6 +350,12 @@ class SessionReloginTest {
override suspend fun restoreVersion(fileId: String, versionNo: Int): Response<ApiEnvelope<FileDto>> =
Response.success(ApiEnvelope())
override suspend fun listFacts(fileId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
@@ -183,6 +183,12 @@ class ShareManagementTest {
override suspend fun restoreVersion(fileId: String, versionNo: Int): Response<ApiEnvelope<FileDto>> =
Response.success(ApiEnvelope())
override suspend fun listFacts(fileId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
@@ -277,6 +277,12 @@ class BytesUploadTest {
override suspend fun restoreVersion(fileId: String, versionNo: Int): Response<ApiEnvelope<FileDto>> =
Response.success(ApiEnvelope())
override suspend fun listFacts(fileId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
@@ -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<Context>()
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<FactDto> = emptyList()
override suspend fun listFacts(fileId: String): Response<ApiEnvelope<List<FactDto>>> =
Response.success(ApiEnvelope(data = facts))
override suspend fun listFolders(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FolderDto>>> = TODO()
override suspend fun listFiles(folderId: String?, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FileDto>>> = TODO()
override suspend fun registerDevice(body: com.kazier.mobile.data.remote.dto.DeviceRegistrationDto): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.DeviceRegistrationDto>> = TODO()
override suspend fun login(body: com.kazier.mobile.data.remote.dto.LoginRequestDto): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.LoginResponseDto>> = TODO()
override suspend fun syncOps(body: com.kazier.mobile.data.remote.dto.SyncOpsRequest): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.SyncOpsResult>> = TODO()
override suspend fun resolveUser(username: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.ResolvedUserDto>> = TODO()
override suspend fun syncPermissions(after: Long?): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ResourcePermissionDto>>> = TODO()
override suspend fun uploadFile(file: okhttp3.MultipartBody.Part, resourceId: okhttp3.RequestBody?, folderId: okhttp3.RequestBody?): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileDto>> = TODO()
override suspend fun submitOcr(body: com.kazier.mobile.data.remote.dto.OcrSubmitDto): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.OcrJobDto>> = TODO()
override suspend fun getOcrJob(jobId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.OcrJobDto>> = TODO()
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileOcrDto>> = TODO()
override suspend fun getFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileDto>> = TODO()
override suspend fun downloadContent(fileId: String): Response<okhttp3.ResponseBody> = TODO()
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun listTrash(page: Int?, pageSize: Int?): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.TrashDto>>> = TODO()
override suspend fun restoreFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun listVersions(fileId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.VersionDto>>> = TODO()
override suspend fun restoreVersion(fileId: String, versionNo: Int): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileDto>> = TODO()
override suspend fun correctFacts(fileId: String, body: CorrectFactsDto): Response<ApiEnvelope<List<FactDto>>> = TODO()
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FileDto>>> = TODO()
override suspend fun changePassword(body: com.kazier.mobile.data.remote.dto.ChangePasswordDto): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun getShareLink(token: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.ShareLinkDto>> = TODO()
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ShareGrantDto>>> = TODO()
override suspend fun listLinks(fileId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ShareLinkDto>>> = TODO()
override suspend fun listPlacements(fileId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.PlacementDto>>> = TODO()
override suspend fun createGroup(body: com.kazier.mobile.data.remote.dto.CreateGroupDto): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.GroupDto>> = TODO()
override suspend fun listGroups(): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.GroupDto>>> = TODO()
override suspend fun addGroupMember(groupId: String, body: com.kazier.mobile.data.remote.dto.AddGroupMemberDto): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun listGroupMembers(groupId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.GroupMemberDto>>> = TODO()
override suspend fun removeGroupMember(groupId: String, userId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun deleteGroup(groupId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
}
companion object {
private const val RESOURCE_ID = "facts-res-1"
private const val NOW = 1_700_000_000_000L
}
}
@@ -392,6 +392,17 @@ private class FolderMergeApiService : ApiService {
versionNo: Int,
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
override suspend fun listFacts(
fileId: String,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun correctFacts(
fileId: String,
body: com.kazier.mobile.data.remote.dto.CorrectFactsDto,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun searchFiles(
query: String,
page: Int?,
@@ -481,6 +481,17 @@ private class MoveProtectionApiService : ApiService {
versionNo: Int,
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
override suspend fun listFacts(
fileId: String,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun correctFacts(
fileId: String,
body: com.kazier.mobile.data.remote.dto.CorrectFactsDto,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun searchFiles(
query: String,
page: Int?,
@@ -393,6 +393,17 @@ private class OcrApiServiceFake : ApiService {
versionNo: Int,
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
override suspend fun listFacts(
fileId: String,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun correctFacts(
fileId: String,
body: com.kazier.mobile.data.remote.dto.CorrectFactsDto,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun searchFiles(
query: String,
page: Int?,
@@ -285,6 +285,12 @@ class OfflineDownloadTest {
override suspend fun restoreVersion(fileId: String, versionNo: Int): Response<ApiEnvelope<FileDto>> =
Response.success(ApiEnvelope())
override suspend fun listFacts(fileId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
@@ -248,6 +248,17 @@ private class RefreshVsMoveApiService : ApiService {
versionNo: Int,
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
override suspend fun listFacts(
fileId: String,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun correctFacts(
fileId: String,
body: com.kazier.mobile.data.remote.dto.CorrectFactsDto,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun searchFiles(
query: String,
page: Int?,
@@ -502,6 +502,17 @@ private class FakeApiService : ApiService {
versionNo: Int,
): Response<ApiEnvelope<FileDto>> = Response.success(ApiEnvelope())
override suspend fun listFacts(
fileId: String,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun correctFacts(
fileId: String,
body: com.kazier.mobile.data.remote.dto.CorrectFactsDto,
): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
override suspend fun searchFiles(
query: String,
page: Int?,
@@ -159,6 +159,8 @@ class ReleaseLocalCopyTest {
override suspend fun restoreFile(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun listVersions(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.VersionDto>>> = TODO()
override suspend fun restoreVersion(fileId: String, versionNo: Int): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.FileDto>> = TODO()
override suspend fun listFacts(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> = TODO()
override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> = TODO()
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FileDto>>> = TODO()
override suspend fun changePassword(body: com.kazier.mobile.data.remote.dto.ChangePasswordDto): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun getShareLink(token: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.ShareLinkDto>> = TODO()
@@ -507,6 +507,12 @@ class OutboxSyncWorkerTest {
override suspend fun restoreVersion(fileId: String, versionNo: Int): Response<ApiEnvelope<FileDto>> =
throw UnsupportedOperationException()
override suspend fun listFacts(fileId: String): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
throw UnsupportedOperationException()
override suspend fun correctFacts(fileId: String, body: com.kazier.mobile.data.remote.dto.CorrectFactsDto): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.FactDto>>> =
throw UnsupportedOperationException()
override suspend fun searchFiles(
query: String,
page: Int?,