import 'package:drift/drift.dart'; import 'enums.dart'; import 'sync_columns.dart'; /// The identity/accession — one row per distinct thing in the inventory. /// Only [label] is mandatory (progressive disclosure). /// /// The index covers the inventory list's hot filter — non-deleted, non-draft /// rows — so it stays fast with a large catalogue. @TableIndex(name: 'idx_varieties_deleted_draft', columns: {#isDeleted, #isDraft}) class Varieties extends Table with SyncColumns { TextColumn get label => text()(); TextColumn get speciesId => text().nullable()(); // → Species TextColumn get cultivarName => text().nullable()(); 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 /// merge as a set). class VarietyVernacularNames extends Table with SyncColumns { TextColumn get varietyId => text()(); TextColumn get name => text()(); TextColumn get language => text().nullable()(); TextColumn get region => text().nullable()(); } /// Bundled, mostly read-only name catalog (Wikidata CC0 + GBIF CC-BY). class Species extends Table with SyncColumns { TextColumn get scientificName => text()(); TextColumn get wikidataQid => text().nullable()(); 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). class SpeciesCommonNames extends Table with SyncColumns { TextColumn get speciesId => text()(); TextColumn get name => text()(); TextColumn get language => text().nullable()(); } /// A homogeneous batch held for a Variety — its own year and its own unit. /// Quantity (commons_core value type) is flattened into columns here. /// /// Indexed by [varietyId] — the inventory list joins lots per variety (types, /// shared status, viability), so this avoids a full scan per reload. @TableIndex(name: 'idx_lots_variety', columns: {#varietyId}) class Lots extends Table with SyncColumns { TextColumn get varietyId => text()(); TextColumn get type => textEnum().withDefault(const Constant('seed'))(); IntColumn get harvestYear => integer().nullable()(); IntColumn get harvestMonth => integer().nullable()(); // 1..12, optional TextColumn get quantityKind => text().nullable()(); // QuantityKind.name RealColumn get quantityPrecise => real().nullable()(); TextColumn get quantityLabel => text().nullable()(); // How living (non-seed) material is packaged; null for seed lots or unset. TextColumn get presentation => textEnum().nullable()(); TextColumn get storageLocation => text().nullable()(); TextColumn get offerStatus => textEnum().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().nullable()(); /// How the (seed) lot is physically conserved — see [PreservationFormat]. /// Distinct from [storageLocation]. Optional. TextColumn get preservationFormat => textEnum().nullable()(); /// Asking price when [offerStatus] is `sell` (data-model §2.8 puts price on /// the Offer; with offer state collapsed onto the Lot, it lives here and is /// published with the market offer). Informational only — money changes /// hands off-platform, never in-app. Null amount on a sell lot means /// "price to be agreed" (the offer publishes without a price). RealColumn get priceAmount => real().nullable()(); /// Free-text currency, like [Sales.currency]: "€", "Ğ1", a local/time /// currency. Never assumed (sharing-model §6). TextColumn get priceCurrency => text().nullable()(); } /// Optional germination history for a Lot; percent is derived in code. class GerminationTests extends Table with SyncColumns { TextColumn get lotId => text()(); IntColumn get testedOn => integer().nullable()(); // date, ms since epoch IntColumn get sampleSize => integer().nullable()(); IntColumn get germinatedCount => integer().nullable()(); 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().nullable()(); TextColumn get notes => text().nullable()(); } /// "How did it do in MY garden" — one optional, skippable answer per season /// (v13). Captured at the natural moment (recording a harvest), shown as one /// more line of the lot's story. Deliberately minimal — a coarse rating plus a /// free note; the note carries any nuance. Mirrors [GerminationTests]: a dated /// log under a Lot. class GardenOutcomes extends Table with SyncColumns { TextColumn get lotId => text()(); IntColumn get year => integer().nullable()(); // season, e.g. 2026 TextColumn get rating => textEnum().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()(); TextColumn get type => textEnum()(); IntColumn get occurredOn => integer().nullable()(); // date, ms since epoch TextColumn get counterpartyId => text().nullable()(); // → Party TextColumn get quantityKind => text().nullable()(); RealColumn get quantityPrecise => real().nullable()(); TextColumn get quantityLabel => text().nullable()(); TextColumn get parentMovementId => text().nullable()(); // provenance DAG TextColumn get plantareId => text().nullable()(); // reserved (social layer) TextColumn get notes => text().nullable()(); } /// A person or collective you exchange with. class Parties extends Table with SyncColumns { TextColumn get displayName => text()(); TextColumn get publicKey => text().nullable()(); TextColumn get kind => textEnum().withDefault(const Constant('person'))(); TextColumn get note => text().nullable()(); } /// Photos/docs. Polymorphic parent. Photo bytes are stored in-DB (encrypted at /// rest by SQLCipher) via [bytes]; external files use [uri]. Storing bytes here /// keeps the "no plaintext at rest" rule for photos in Block 1; an external /// encrypted file store is a later optimization. /// /// Indexed by (parentType, parentId, kind) — the list's "first photo per /// variety" lookup filters on exactly these. @TableIndex( name: 'idx_attachments_parent', columns: {#parentType, #parentId, #kind}, ) class Attachments extends Table with SyncColumns { TextColumn get parentType => textEnum()(); TextColumn get parentId => text()(); TextColumn get kind => textEnum()(); TextColumn get uri => text().nullable()(); BlobColumn get bytes => blob().nullable()(); /// A small JPEG thumbnail of [bytes] (photos only), decoded once on save so /// the inventory list never has to decode the full-resolution photo for a /// 48px avatar. Purely derived, local and regenerable — it is EXCLUDED from /// CRDT sync payloads and backups (see [SyncColumns] usage); a peer or a /// restored backup regenerates it lazily via `backfillThumbnails`. BlobColumn get thumbnail => blob().nullable()(); TextColumn get mimeType => text().nullable()(); /// Display order among sibling attachments (lower first). The lowest-ordered /// photo is the "preferred"/cover — used as the variety avatar and shown /// first. New photos append at the end; "set as cover" moves one to the /// front. A plain int (not a bool flag) so it generalizes to full reordering. IntColumn get sortOrder => integer().withDefault(const Constant(0))(); } /// A Plantare — a REPRODUCTION commitment (data-model §2.7), the seed-domain /// name for the generic `Pledge` (`return_kind = similar`). Seed changes hands /// and the receiver promises to grow it out and return some. NOT a sale. /// /// Local-first v1: your own honest ledger of commitments (from/to a person by /// name). The bilateral, cryptographically SIGNED, cross-party form /// (debtor/creditor keys + both signatures, tied to a shared `Movement`) is a /// later social-layer phase — those columns are deferred, not invented now. class Plantares extends Table with SyncColumns { /// The seed the commitment is about — what gets reproduced. Nullable so a /// commitment can be jotted before it's linked to a catalogued variety. TextColumn get varietyId => text().nullable()(); // → Variety /// Whose promise it is (I return / owed to me). TextColumn get direction => textEnum()(); /// The other party as a human name (v1). A key/Party link arrives with the /// signed cross-party form. TextColumn get counterparty => text().nullable()(); /// What's promised back, in the grower's own words /// ("un puñado la próxima temporada"). TextColumn get owedDescription => text().nullable()(); /// When the promise was made (ms since epoch). IntColumn get madeOn => integer()(); /// Optional return-by date (ms since epoch) — a gentle reminder, not a deadline. IntColumn get dueBy => integer().nullable()(); TextColumn get status => textEnum().withDefault(const Constant('open'))(); /// When it was returned or forgiven (ms since epoch). IntColumn get settledOn => integer().nullable()(); TextColumn get note => text().nullable()(); // --- Bilateral signed form (plantare-bilateral.md). Nullable so v1 local rows // (both keys/signatures null, remoteState null) coexist untouched. --- /// The shared pledge id both parties agree on (the proposer's id). Distinct /// from [id] (each side keeps its own local row). Null for a v1 local note. TextColumn get pledgeId => text().nullable()(); /// Pubkey (hex) of who received the seed and owes a return. TextColumn get debtorKey => text().nullable()(); /// Pubkey (hex) of who gave the seed. TextColumn get creditorKey => text().nullable()(); /// The debtor's Schnorr stub over the canonical pledge core. TextColumn get debtorSignature => text().nullable()(); /// The creditor's Schnorr stub over the canonical pledge core. TextColumn get creditorSignature => text().nullable()(); /// The shared hand-over `Movement` this Plantare accompanies (provenance DAG). TextColumn get movementId => text().nullable()(); // → Movement /// The handshake state (proposed/accepted/declined), null for a v1 local row. TextColumn get remoteState => textEnum().nullable()(); /// How it's promised back (default `similar`: open-pollinated · non-GMO · /// organically grown), mirroring the paper form's checkboxes. TextColumn get returnKind => textEnum().withDefault(const Constant('similar'))(); /// Hours for the `workHours` return option (time-as-currency). Null otherwise. RealColumn get workHours => real().nullable()(); } /// A recorded seed Sale — seed for money (data-model §2.8/sharing-model §6). A /// SEPARATE model from a gift or a Plantare: a completed exchange with a price /// in ANY currency (€, Ğ1, a local/time currency). Local-first ledger; the /// cross-party/receipt form is a later social-layer concern. class Sales extends Table with SyncColumns { /// The seed sold/bought. Nullable so a sale can be jotted before it's linked /// to a catalogued variety. TextColumn get varietyId => text().nullable()(); // → Variety /// Whether I sold or I bought. TextColumn get direction => textEnum()(); /// The other party as a human name (v1). TextColumn get counterparty => text().nullable()(); /// Price paid. Nullable — a barter-ish "sale" recorded before a figure is set. RealColumn get amount => real().nullable()(); /// The currency, free text: "€", "Ğ1", "horas", a local currency name. Never /// assumed — the seed world uses many (sharing-model §6). TextColumn get currency => text().nullable()(); /// When the sale happened (ms since epoch). IntColumn get soldOn => integer()(); TextColumn get note => text().nullable()(); } /// Any pasted URL (Wikipedia, forum…). Polymorphic parent. class ExternalLinks extends Table with SyncColumns { TextColumn get parentType => textEnum()(); TextColumn get parentId => text()(); TextColumn get url => text()(); TextColumn get title => text().nullable()(); }