mirror of
https://github.com/bleackstorm/satiea.git
synced 2026-12-03 07:41:56 +01:00
- Tighten Firestore validation rules (data size and limits) - Pass context to `deletePhotoFile` for safer file management - Cleanup unused dependencies in build configuration - Update Robolectric SDK target for tests
117 lines
5.2 KiB
Kotlin
117 lines
5.2 KiB
Kotlin
package com.example.util
|
|
|
|
import android.content.Context
|
|
import android.content.Intent
|
|
import android.net.Uri
|
|
import androidx.core.content.FileProvider
|
|
import com.example.data.model.HungerSatietyScale
|
|
import com.example.data.model.MealEntry
|
|
import com.example.data.model.MealType
|
|
import kotlinx.coroutines.Dispatchers
|
|
import kotlinx.coroutines.withContext
|
|
import java.io.File
|
|
import java.time.Instant
|
|
import java.time.LocalDate
|
|
import java.time.ZoneId
|
|
import java.time.format.DateTimeFormatter
|
|
import java.util.Locale
|
|
|
|
object CsvExporter {
|
|
|
|
private val fileDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.FRENCH)
|
|
private val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.FRENCH)
|
|
private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH)
|
|
|
|
fun buildDefaultFileName(): String {
|
|
val dateStr = fileDateFormatter.format(LocalDate.now())
|
|
return "satiea_repas_$dateStr.csv"
|
|
}
|
|
|
|
fun generateCsvContent(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): String {
|
|
val sb = StringBuilder()
|
|
// UTF-8 BOM for proper French accent display in Excel / LibreOffice / Google Sheets
|
|
sb.append('\uFEFF')
|
|
sb.appendLine("Date,Heure,Type de repas,Faim avant (/10),Ressenti faim,Satiété après (/10),Ressenti satiété,Aliments & Poids,Note globale,Photos jointes")
|
|
|
|
val sortedMeals = meals.sortedByDescending { it.mealTimestamp }
|
|
for (meal in sortedMeals) {
|
|
val zonedDateTime = Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId)
|
|
val dateStr = dateFormatter.format(zonedDateTime)
|
|
val timeStr = timeFormatter.format(zonedDateTime)
|
|
val mealTypeLabel = MealType.fromString(meal.mealType).displayName
|
|
val hungerLabel = HungerSatietyScale.getHungerLabel(meal.hungerBefore)
|
|
val satietyLabel = HungerSatietyScale.getSatietyLabel(meal.satietyAfter)
|
|
val foodsFormatted = meal.parsedFoodItems().joinToString(" ; ") { it.displayCsv() }
|
|
val cleanNote = escapeCsvField(meal.note)
|
|
val photoCount = meal.displayPhotoUris.size
|
|
|
|
sb.append(escapeCsvField(dateStr)).append(',')
|
|
sb.append(escapeCsvField(timeStr)).append(',')
|
|
sb.append(escapeCsvField(mealTypeLabel)).append(',')
|
|
sb.append(meal.hungerBefore).append(',')
|
|
sb.append(escapeCsvField(hungerLabel)).append(',')
|
|
sb.append(meal.satietyAfter).append(',')
|
|
sb.append(escapeCsvField(satietyLabel)).append(',')
|
|
sb.append(escapeCsvField(foodsFormatted)).append(',')
|
|
sb.append(cleanNote).append(',')
|
|
sb.append(photoCount)
|
|
sb.appendLine()
|
|
}
|
|
return sb.toString()
|
|
}
|
|
|
|
fun escapeCsvField(value: String): String {
|
|
val rawWithoutNewlines = value.replace("\r\n", " ").replace("\n", " ")
|
|
val trimmed = rawWithoutNewlines.trim()
|
|
val formulaProtected = if (rawWithoutNewlines.isNotEmpty() && rawWithoutNewlines[0] in listOf('=', '+', '-', '@', '\t', '\r')) {
|
|
"'$rawWithoutNewlines"
|
|
} else if (trimmed.isNotEmpty() && trimmed[0] in listOf('=', '+', '-', '@')) {
|
|
"'$trimmed"
|
|
} else {
|
|
trimmed
|
|
}
|
|
return if (formulaProtected.contains(",") || formulaProtected.contains("\"") || formulaProtected.contains(";")) {
|
|
"\"${formulaProtected.replace("\"", "\"\"")}\""
|
|
} else {
|
|
formulaProtected
|
|
}
|
|
}
|
|
|
|
suspend fun writeCsvToUri(context: Context, targetUri: Uri, meals: List<MealEntry>): Result<Int> =
|
|
withContext(Dispatchers.IO) {
|
|
try {
|
|
val csvContent = generateCsvContent(meals)
|
|
context.contentResolver.openOutputStream(targetUri)?.use { outputStream ->
|
|
outputStream.write(csvContent.toByteArray(Charsets.UTF_8))
|
|
outputStream.flush()
|
|
} ?: return@withContext Result.failure(IllegalStateException("Impossible d'ouvrir le fichier de destination"))
|
|
Result.success(meals.size)
|
|
} catch (e: Exception) {
|
|
Result.failure(e)
|
|
}
|
|
}
|
|
|
|
suspend fun shareCsvFile(context: Context, meals: List<MealEntry>): Result<Intent> =
|
|
withContext(Dispatchers.IO) {
|
|
try {
|
|
val csvContent = generateCsvContent(meals)
|
|
val exportDir = File(context.cacheDir, "exports").apply { mkdirs() }
|
|
val csvFile = File(exportDir, buildDefaultFileName())
|
|
csvFile.writeText(csvContent, Charsets.UTF_8)
|
|
|
|
val authority = "${context.packageName}.fileprovider"
|
|
val contentUri = FileProvider.getUriForFile(context, authority, csvFile)
|
|
|
|
val shareIntent = Intent(Intent.ACTION_SEND).apply {
|
|
type = "text/csv"
|
|
putExtra(Intent.EXTRA_SUBJECT, "Export Satiéa — Journal des repas")
|
|
putExtra(Intent.EXTRA_STREAM, contentUri)
|
|
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
|
}
|
|
Result.success(Intent.createChooser(shareIntent, "Partager le fichier CSV"))
|
|
} catch (e: Exception) {
|
|
Result.failure(e)
|
|
}
|
|
}
|
|
}
|