feat(inventory): photo-first drafts + on-device OCR (digitization R2+R4)

Lower the bulk-digitization cliff with two more routes on top of the
already-landed CSV import and "save and add another":

- Photo-first drafts (capture now, catalogue later): burst-capture
  photos (camera or multi-gallery) into unnamed draft varieties, shown
  in a "to catalogue" tray, hidden from the main list until named.
  Adds Variety.isDraft (schema), addDraftVariety/watchDrafts/nameDraft,
  the triage sheet and the inventory banner.
- On-device OCR label suggestion (Tesseract, offline, no Google): a
  "Suggest name from photo" button in the naming dialog behind a
  LabelTextExtractor interface (Tesseract on Android/iOS, no-op
  elsewhere). Reads the largest print via hOCR bounding boxes, drops
  boilerplate/low-confidence noise, preprocesses (grayscale, contrast,
  upscale) and sweeps rotations (0-315 deg) so tilted packets still
  read. Bundles tessdata_fast eng+spa; validated on-device against real
  packets. The photo is written to a temp file deleted immediately in a
  finally block (the plugin needs a path) - a bounded, documented
  exception to no-plaintext-at-rest.

This commit also carries the co-developed schema evolution v5 to v8 that
shares these files (organic flag, species viability years, crop
calendar, lot provenance/abundance/preservation format, condition
checks) plus their exports/migrations and i18n.

Tests: CSV/draft/OCR unit + widget + migration green in isolation.
Note: the full widget suite currently hangs (>10 min) - under investigation.
This commit is contained in:
vjrj 2026-07-09 21:23:46 +02:00
parent 12a2ee2d64
commit 6809dc6143
89 changed files with 17141 additions and 228 deletions

View file

@ -17,6 +17,7 @@ part 'database.g.dart';
SpeciesCommonNames,
Lots,
GerminationTests,
ConditionChecks,
Movements,
Parties,
Attachments,
@ -28,7 +29,7 @@ class AppDatabase extends _$AppDatabase {
/// Current schema version; also stamped into interchange exports so an
/// importer knows which app generation wrote the file (data-model §7).
static const int currentSchemaVersion = 5;
static const int currentSchemaVersion = 8;
@override
int get schemaVersion => currentSchemaVersion;
@ -53,6 +54,110 @@ class AppDatabase extends _$AppDatabase {
if (from < 5) {
await m.addColumn(attachments, attachments.sortOrder);
}
// v6: photo-first draft varieties awaiting a name ("to catalogue" tray).
if (from < 6) {
await m.addColumn(varieties, varieties.isDraft);
}
// v7: organic ("eco") self-declaration on varieties; per-species seed
// viability (years) reference data for expiry warnings. Guarded by a
// column-existence check so a dev database left half-migrated (column
// added but user_version not bumped) re-runs cleanly instead of failing
// on "duplicate column".
if (from < 7) {
if (!await _hasColumn('varieties', 'is_organic')) {
await m.addColumn(varieties, varieties.isOrganic);
}
if (!await _hasColumn('species', 'viability_years')) {
await m.addColumn(species, species.viabilityYears);
}
}
// v8: absorbs fields from a real seed-bank inventory. Varieties gain a
// "needs reproducing" intent and an advisory crop calendar; Lots gain
// provenance (origin name/place), a qualitative abundance level and a
// preservation format; a new ConditionChecks table logs container count +
// drying-agent state. Every step is guarded so a half-migrated dev
// database re-runs cleanly (see the v7 note above).
if (from < 8) {
Future<void> addIfMissing(
String table,
String column,
GeneratedColumn<Object> definition,
TableInfo<Table, dynamic> tableInfo,
) async {
if (!await _hasColumn(table, column)) {
await m.addColumn(tableInfo, definition);
}
}
await addIfMissing(
'varieties',
'needs_reproduction',
varieties.needsReproduction,
varieties,
);
await addIfMissing(
'varieties',
'sow_months',
varieties.sowMonths,
varieties,
);
await addIfMissing(
'varieties',
'transplant_months',
varieties.transplantMonths,
varieties,
);
await addIfMissing(
'varieties',
'flowering_months',
varieties.floweringMonths,
varieties,
);
await addIfMissing(
'varieties',
'fruiting_months',
varieties.fruitingMonths,
varieties,
);
await addIfMissing(
'varieties',
'seed_harvest_months',
varieties.seedHarvestMonths,
varieties,
);
await addIfMissing('lots', 'origin_name', lots.originName, lots);
await addIfMissing('lots', 'origin_place', lots.originPlace, lots);
await addIfMissing('lots', 'abundance', lots.abundance, lots);
await addIfMissing(
'lots',
'preservation_format',
lots.preservationFormat,
lots,
);
if (!await _hasTable('condition_checks')) {
await m.createTable(conditionChecks);
}
}
},
);
/// Whether a table named [table] already exists. Keeps the additive v8
/// table creation idempotent against partially-migrated databases.
Future<bool> _hasTable(String table) async {
final rows = await customSelect(
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?",
variables: [Variable.withString(table)],
).get();
return rows.isNotEmpty;
}
/// Whether [table] already has a column named [column]. Used to keep additive
/// migrations idempotent against partially-migrated databases.
Future<bool> _hasColumn(String table, String column) async {
final rows = await customSelect(
'SELECT 1 FROM pragma_table_info(?) WHERE name = ?',
variables: [Variable.withString(table), Variable.withString(column)],
).get();
return rows.isNotEmpty;
}
}

File diff suppressed because it is too large Load diff

View file

@ -27,6 +27,46 @@ enum Presentation { pot, tray, plug, bareRoot, rootBall }
/// Per-lot visibility (data-model §2.3). Used by the future sharing layer.
enum OfferStatus { private, shared, exchange, sell }
/// A coarse, offline-friendly "how much do I have" that fuses amount with
/// shareability the way a seed saver actually thinks, without weighing or
/// counting. Modelled on the qualitative scale a real seed bank used
/// (mucha/bastante/suficiente/poca), where each level is defined by what you
/// can do with it. Optional alternative to a precise Quantity. Append-only by
/// name.
///
/// - `plentyToShare` surplus, free to give away (mucha).
/// - `enoughToShare` can share a little, sparingly (bastante).
/// - `enoughForMe` enough for my own use, not to share (suficiente).
/// - `runningLow` only enough to keep the variety alive (poca).
enum Abundance { plentyToShare, enoughToShare, enoughForMe, runningLow }
/// How dry seed is physically conserved affects longevity, kept separate from
/// *where* it is stored. Optional attribute of a seed [Lot]. Append-only by name.
///
/// - `jarWithDesiccant` sealed jar with a drying agent (bote con sílice).
/// - `glassJar` plain glass jar (bote de cristal).
/// - `paperEnvelope` paper envelope (sobre de papel).
/// - `paperBag` paper bag (bolsa de papel).
/// - `plasticBag` plastic bag (bolsa de plástico).
enum PreservationFormat {
jarWithDesiccant,
glassJar,
paperEnvelope,
paperBag,
plasticBag,
}
/// State of the drying agent (silica gel) in a stored seed container, recorded
/// at a periodic condition check. The colour is a proxy for moisture: a
/// saturated agent means the seed is at risk. Append-only by name.
///
/// - `none` no drying agent present (no tiene).
/// - `add` should add some (se pone).
/// - `replace` saturated, replace it (se cambia).
/// - `dry` indicating dry (azul/blue).
/// - `fresh` just renewed (lila/violet).
enum DesiccantState { none, add, replace, dry, fresh }
/// Append-only event kinds on a Lot (data-model §2.4).
enum MovementType {
received,

View file

@ -12,6 +12,35 @@ class Varieties extends Table with SyncColumns {
TextColumn get category =>
text().nullable()(); // free text, prefilled from family
TextColumn get notes => text().nullable()();
/// A draft captured photo-first ("capture now, catalogue later"): it holds a
/// photo but not yet a real name, and lives in the "to catalogue" tray until
/// the user labels it. A plain LWW scalar, so it merges like any other field.
BoolColumn get isDraft => boolean().withDefault(const Constant(false))();
/// Grower-declared organic ("eco") provenance. A self-declaration, not a
/// third-party certification (that would be a separate flag). Surfaced as a
/// badge and an inventory filter. A plain LWW scalar.
BoolColumn get isOrganic => boolean().withDefault(const Constant(false))();
/// A stewardship intent set by the grower: "regrow this variety this season"
/// before its stock or vitality runs out. Complements the automatic viability
/// warning (which is age-derived) with an explicit human decision. Surfaced
/// as a badge and an inventory filter. A plain LWW scalar.
BoolColumn get needsReproduction =>
boolean().withDefault(const Constant(false))();
/// Advisory crop-calendar months, typical for this variety when to sow,
/// transplant, expect flowers/fruit, and harvest seed. Each phase usually
/// spans several months (e.g. sow in spring *and* autumn), so each is a set
/// of months packed as a 12-bit mask (see `domain/crop_calendar.dart`), an
/// optional LWW scalar; null means "not recorded". Guidance, not a per-year
/// actuals log (that path stays available via Movements).
IntColumn get sowMonths => integer().nullable()();
IntColumn get transplantMonths => integer().nullable()();
IntColumn get floweringMonths => integer().nullable()();
IntColumn get fruitingMonths => integer().nullable()();
IntColumn get seedHarvestMonths => integer().nullable()();
}
/// The multiple common names of a Variety (separate table so concurrent adds
@ -30,6 +59,13 @@ class Species extends Table with SyncColumns {
IntColumn get gbifKey => integer().nullable()();
TextColumn get family => text().nullable()();
BoolColumn get isBundled => boolean().withDefault(const Constant(false))();
/// Typical seed longevity in years under normal home storage public-domain
/// reference data bundled with the catalog (agricultural-extension viability
/// tables). Drives the "expiring / past viability" warning on aging lots by
/// comparing against a lot's [Lots.harvestYear]. Nullable: unknown for
/// species without a bundled figure.
IntColumn get viabilityYears => integer().nullable()();
}
/// Localized common names for the catalog (bundled).
@ -56,6 +92,23 @@ class Lots extends Table with SyncColumns {
TextColumn get offerStatus =>
textEnum<OfferStatus>().withDefault(const Constant('private'))();
TextColumn get seedbankId => text().nullable()();
/// Provenance of this batch, kept as lightweight free text so it needs no
/// Party/Movement to record (the rigorous exchange path stays via Movements).
/// [originName] = who grew or gave the seeds; [originPlace] = where they come
/// from (with region/province). Both optional LWW scalars.
TextColumn get originName => text().nullable()();
TextColumn get originPlace => text().nullable()();
/// Optional coarse "how much I have" for this lot see [Abundance]. An
/// offline alternative to the precise Quantity columns; either, both, or
/// neither may be set.
TextColumn get abundance => textEnum<Abundance>().nullable()();
/// How the (seed) lot is physically conserved see [PreservationFormat].
/// Distinct from [storageLocation]. Optional.
TextColumn get preservationFormat =>
textEnum<PreservationFormat>().nullable()();
}
/// Optional germination history for a Lot; percent is derived in code.
@ -67,6 +120,17 @@ class GerminationTests extends Table with SyncColumns {
TextColumn get notes => text().nullable()();
}
/// Optional storage-condition history for a seed Lot: periodic physical checks
/// of how many containers hold it and the state of the drying agent. Mirrors
/// [GerminationTests] a dated log under a Lot, newest shown first.
class ConditionChecks extends Table with SyncColumns {
TextColumn get lotId => text()();
IntColumn get checkedOn => integer().nullable()(); // date, ms since epoch
IntColumn get containerCount => integer().nullable()(); // "botes"
TextColumn get desiccantState => textEnum<DesiccantState>().nullable()();
TextColumn get notes => text().nullable()();
}
/// The append-only event log on a Lot history + provenance DAG.
class Movements extends Table with AppendOnlyColumns {
TextColumn get lotId => text()();