feat(inventory): CSV/JSON export and JSON import with LWW reconciliation

Interchange export/import for Phase 1 (data-model §7):

- JSON: canonical, versioned envelope (formatVersion 1) with all sync
  metadata verbatim, photos embedded as base64, tombstones excluded.
  Species are re-resolved on import by scientific name (catalog ids are
  per-install). Reader tolerates unknown fields/enum values (§5.2) and
  rejects newer format versions with a clear error.
- CSV: export-only spreadsheet flatten, one row per lot, RFC 4180
  escaping, never any photo bytes.
- Import merges by UUIDv7 id in one transaction: insert-if-unknown
  preserving original stamps, last-writer-wins by packed HLC for known
  mutable rows, append-only movements; afterwards the local clock
  receiveEvent()s the newest imported stamp so it never runs behind.
- Settings gains a Backup section (export CSV/JSON, import JSON with
  confirmation); file dialogs behind a FileService interface backed by
  file_picker (MIT).
- Tests: codec round-trip and tolerance, reconciler LWW, repository
  export→import round-trip (fresh DB, idempotent re-import, newer-local
  wins, clock monotonicity, species re-resolution), backup widget flows.
This commit is contained in:
vjrj 2026-07-09 12:46:53 +02:00
parent 136ed701a7
commit 2812c99280
25 changed files with 2207 additions and 7 deletions

View file

@ -0,0 +1,63 @@
import 'dart:convert';
import '../data/export_import/inventory_csv_codec.dart';
import '../data/export_import/inventory_json_codec.dart';
import '../data/export_import/inventory_snapshot.dart';
import '../data/variety_repository.dart';
import 'file_service.dart';
/// End-to-end export/import flows: repository snapshot codec the file the
/// user picked. UI-free screens call these and render the outcome.
class ExportImportService {
ExportImportService({
required VarietyRepository repository,
required FileService files,
DateTime Function()? now,
}) : _repository = repository,
_files = files,
_now = now ?? DateTime.now;
final VarietyRepository _repository;
final FileService _files;
final DateTime Function() _now;
static const _jsonCodec = InventoryJsonCodec();
static const _csvCodec = InventoryCsvCodec();
/// Exports the inventory as interchange JSON (data-model §7). Returns true
/// when saved, false when the user cancelled the save dialog.
Future<bool> exportJson() async {
final snapshot = await _repository.exportInventory();
final path = await _files.saveFile(
suggestedName: _fileName('json'),
bytes: utf8.encode(_jsonCodec.encode(snapshot)),
);
return path != null;
}
/// Exports the inventory as flat CSV (export-only). Returns true when
/// saved, false when the user cancelled the save dialog.
Future<bool> exportCsv() async {
final snapshot = await _repository.exportInventory();
final path = await _files.saveFile(
suggestedName: _fileName('csv'),
bytes: utf8.encode(_csvCodec.encode(snapshot)),
);
return path != null;
}
/// Imports an interchange JSON file, merging by id (LWW). Returns the
/// summary, or null when the user cancelled the file dialog. Throws
/// [FormatException] when the file is not a readable inventory export.
Future<ImportSummary?> importJson() async {
final bytes = await _files.pickFileBytes(allowedExtensions: ['json']);
if (bytes == null) return null;
final snapshot = _jsonCodec.decode(utf8.decode(bytes));
return _repository.importInventory(snapshot);
}
String _fileName(String extension) {
final date = _now().toIso8601String().substring(0, 10);
return 'tanemaki-inventory-$date.$extension';
}
}

View file

@ -0,0 +1,47 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'file_service.dart';
/// [FileService] backed by the `file_picker` plugin (one plugin covers the
/// save and open dialogs on Android, iOS and desktop).
class FilePickerFileService implements FileService {
const FilePickerFileService();
@override
Future<String?> saveFile({
required String suggestedName,
required Uint8List bytes,
}) async {
final path = await FilePicker.platform.saveFile(
fileName: suggestedName,
bytes: bytes,
);
if (path == null) return null;
// On mobile the plugin writes [bytes] itself; on desktop it only returns
// the chosen path, so write them here.
if (!Platform.isAndroid && !Platform.isIOS) {
await File(path).writeAsBytes(bytes, flush: true);
}
return path;
}
@override
Future<Uint8List?> pickFileBytes({List<String>? allowedExtensions}) async {
final result = await FilePicker.platform.pickFiles(
type: allowedExtensions == null ? FileType.any : FileType.custom,
allowedExtensions: allowedExtensions,
withData: true,
);
final file = result?.files.singleOrNull;
if (file == null) return null;
// withData should populate bytes; fall back to the path just in case.
final bytes = file.bytes;
if (bytes != null) return bytes;
final path = file.path;
if (path == null) return null;
return File(path).readAsBytes();
}
}

View file

@ -0,0 +1,19 @@
import 'dart:typed_data';
/// Cross-platform "save a file / open a file" boundary, so everything above
/// it (services, tests) stays free of platform channels. Implementations must
/// never leave plaintext temp copies behind bytes go straight between
/// memory and the destination the user picked (security-privacy.md).
abstract class FileService {
/// Asks the user where to save [bytes] (suggesting [suggestedName]) and
/// writes them there. Returns the chosen path, or null if they cancelled.
Future<String?> saveFile({
required String suggestedName,
required Uint8List bytes,
});
/// Asks the user to pick a file (optionally restricted to
/// [allowedExtensions], without dots) and returns its bytes, or null if
/// they cancelled.
Future<Uint8List?> pickFileBytes({List<String>? allowedExtensions});
}