feat(plantare): reproduction-commitment data layer (schema v9)

The Plantare — a promise to reproduce seed and return some (data-model §2.7,
the seed-domain Pledge with return_kind=similar). NOT a sale. Local-first
v1: your honest ledger of commitments (from/to a person by name); the
bilateral signed cross-party form is a later social-layer phase.

- New Plantares table (SyncColumns): varietyId, direction (iReturn/owedToMe),
  counterparty, owedDescription, madeOn, dueBy, status (open/returned/
  forgiven), settledOn, note. schemaVersion 8 -> 9 with a guarded createTable
  migration; schema exported + migration-test helper regenerated.
- VarietyRepository: createPlantare / watchPlantares / watchPlantaresForVariety
  / setPlantareStatus / deletePlantare (soft-delete, CRDT-stamped).
- Included in backups + sync: InventorySnapshot + JSON codec (round-trips
  isDeleted) + exportInventory/exportForSync/importInventory, so commitments
  survive restore and replicate LWW like every other row.

Tests: v1..v8 -> v9 migration + fresh v9; repo create/list/settle/reopen/
delete; and a backup round-trip preserving a commitment. 13 green.

UI (detail section + Plantares screen) follows.
This commit is contained in:
vjrj 2026-07-11 02:01:25 +02:00
parent 0e41293de5
commit 81094f25a8
12 changed files with 5418 additions and 60 deletions

File diff suppressed because it is too large Load diff

View file

@ -208,6 +208,28 @@ class InventoryJsonCodec {
'sortOrder': a.sortOrder,
},
],
'plantares': [
for (final p in snapshot.plantares)
{
..._syncMeta(
id: p.id,
createdAt: p.createdAt,
updatedAt: p.updatedAt,
lastAuthor: p.lastAuthor,
schemaRowVersion: p.schemaRowVersion,
isDeleted: p.isDeleted,
),
'varietyId': p.varietyId,
'direction': p.direction.name,
'counterparty': p.counterparty,
'owedDescription': p.owedDescription,
'madeOn': p.madeOn,
'dueBy': p.dueBy,
'status': p.status.name,
'settledOn': p.settledOn,
'note': p.note,
},
],
});
}
@ -418,6 +440,28 @@ class InventoryJsonCodec {
sortOrder: _int(m, 'sortOrder', fallback: 0),
);
}),
plantares: _rows(root, 'plantares', (m) {
return Plantare(
id: _string(m, 'id'),
createdAt: _int(m, 'createdAt'),
updatedAt: _string(m, 'updatedAt'),
lastAuthor: _string(m, 'lastAuthor'),
isDeleted: _bool(m, 'isDeleted'),
schemaRowVersion: _int(m, 'schemaRowVersion', fallback: 1),
varietyId: m['varietyId'] as String?,
direction:
_enumOr(PlantareDirection.values, m['direction'],
PlantareDirection.iReturn),
counterparty: m['counterparty'] as String?,
owedDescription: m['owedDescription'] as String?,
madeOn: _int(m, 'madeOn'),
dueBy: m['dueBy'] as int?,
status:
_enumOr(PlantareStatus.values, m['status'], PlantareStatus.open),
settledOn: m['settledOn'] as int?,
note: m['note'] as String?,
);
}),
);
}

View file

@ -30,6 +30,7 @@ class InventorySnapshot {
this.movements = const [],
this.parties = const [],
this.attachments = const [],
this.plantares = const [],
this.speciesNamesById = const {},
});
@ -42,6 +43,7 @@ class InventorySnapshot {
final List<Movement> movements;
final List<Party> parties;
final List<Attachment> attachments;
final List<Plantare> plantares;
/// speciesId scientificName, for the species referenced by [varieties].
final Map<String, String> speciesNamesById;

View file

@ -1707,6 +1707,80 @@ class VarietyRepository {
return id;
}
// --- Plantares: reproduction commitments (data-model §2.7) ----------------
/// Records a Plantare a promise to reproduce seed and return some (or a
/// promise made TO you). Returns the new commitment id.
Future<String> createPlantare({
required PlantareDirection direction,
String? varietyId,
String? counterparty,
String? owedDescription,
int? dueBy,
String? note,
}) async {
final (created, updated) = await _stamp();
final id = idGen.newId();
await _db.into(_db.plantares).insert(
PlantaresCompanion.insert(
id: id,
createdAt: created,
updatedAt: updated,
lastAuthor: nodeId,
direction: direction,
varietyId: Value(varietyId),
counterparty: Value(counterparty),
owedDescription: Value(owedDescription),
madeOn: created,
dueBy: Value(dueBy),
note: Value(note),
),
);
return id;
}
/// All live commitments, newest first (for the Plantares screen).
Stream<List<Plantare>> watchPlantares() => (_db.select(_db.plantares)
..where((p) => p.isDeleted.equals(false))
..orderBy([(p) => OrderingTerm.desc(p.madeOn)]))
.watch();
/// The commitments recorded against one variety.
Stream<List<Plantare>> watchPlantaresForVariety(String varietyId) =>
(_db.select(_db.plantares)
..where(
(p) => p.varietyId.equals(varietyId) & p.isDeleted.equals(false),
)
..orderBy([(p) => OrderingTerm.desc(p.madeOn)]))
.watch();
/// Moves a commitment to [status]; stamps the settle time for returned/
/// forgiven, clears it when reopened.
Future<void> setPlantareStatus(String id, PlantareStatus status) async {
final (now, updated) = await _stamp();
await (_db.update(_db.plantares)..where((p) => p.id.equals(id))).write(
PlantaresCompanion(
status: Value(status),
settledOn:
Value(status == PlantareStatus.open ? null : now),
updatedAt: Value(updated),
lastAuthor: Value(nodeId),
),
);
}
/// Soft-deletes a commitment (tombstone, so it syncs as a removal).
Future<void> deletePlantare(String id) async {
final (_, updated) = await _stamp();
await (_db.update(_db.plantares)..where((p) => p.id.equals(id))).write(
PlantaresCompanion(
isDeleted: const Value(true),
updatedAt: Value(updated),
lastAuthor: Value(nodeId),
),
);
}
/// Snapshots the live inventory (tombstones excluded) for the interchange
/// export data-model §7. Includes photo bytes; the JSON codec embeds them
/// as base64 and the CSV codec ignores them.
@ -1742,6 +1816,9 @@ class VarietyRepository {
attachments: await (_db.select(
_db.attachments,
)..where((a) => a.isDeleted.equals(false))).get(),
plantares: await (_db.select(
_db.plantares,
)..where((p) => p.isDeleted.equals(false))).get(),
);
}
@ -1764,6 +1841,7 @@ class VarietyRepository {
conditionChecks: await _db.select(_db.conditionChecks).get(),
movements: await _db.select(_db.movements).get(),
parties: await _db.select(_db.parties).get(),
plantares: await _db.select(_db.plantares).get(),
// attachments intentionally omitted photos don't ride the sync wire.
);
}
@ -1856,6 +1934,14 @@ class VarietyRepository {
updatedAtOf: (r) => r.updatedAt,
reconciler: reconciler,
);
summary += await _importMutableRows(
table: _db.plantares,
idColumn: _db.plantares.id,
rows: snapshot.plantares,
idOf: (r) => r.id,
updatedAtOf: (r) => r.updatedAt,
reconciler: reconciler,
);
summary += await _importMovements(snapshot.movements, reconciler);
});
@ -1868,6 +1954,7 @@ class VarietyRepository {
for (final c in snapshot.conditionChecks) c.updatedAt,
for (final p in snapshot.parties) p.updatedAt,
for (final a in snapshot.attachments) a.updatedAt,
for (final pl in snapshot.plantares) pl.updatedAt,
]);
if (maxIncoming != null) {
_clock = _clock.receiveEvent(maxIncoming, _now());

View file

@ -22,6 +22,7 @@ part 'database.g.dart';
Parties,
Attachments,
ExternalLinks,
Plantares,
],
)
class AppDatabase extends _$AppDatabase {
@ -29,7 +30,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 = 8;
static const int currentSchemaVersion = 9;
@override
int get schemaVersion => currentSchemaVersion;
@ -138,6 +139,13 @@ class AppDatabase extends _$AppDatabase {
await m.createTable(conditionChecks);
}
}
// v9: Plantares reproduction commitments (data-model §2.7). Guarded so a
// half-migrated dev database re-runs cleanly (see the v7 note above).
if (from < 9) {
if (!await _hasTable('plantares')) {
await m.createTable(plantares);
}
}
},
);

File diff suppressed because it is too large Load diff

View file

@ -86,3 +86,18 @@ enum AttachmentKind { photo, doc }
/// Polymorphic parent of an Attachment / ExternalLink.
enum ParentType { variety, lot, movement }
/// Whose reproduction promise a Plantare is, seen from this app's owner
/// (data-model §2.7). A Plantare is a commitment to REPRODUCE and return seed
/// not a sale.
enum PlantareDirection {
/// I received seed and promised to grow it out and return some.
iReturn,
/// I gave seed and the other person promised to return some.
owedToMe,
}
/// Lifecycle of a Plantare. Framed as a promise, not a debt (data-model §2.7):
/// `forgiven` (not "defaulted") when it's let go.
enum PlantareStatus { open, returned, forgiven }

View file

@ -173,6 +173,45 @@ class Attachments extends Table with SyncColumns {
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<PlantareDirection>()();
/// 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<PlantareStatus>().withDefault(const Constant('open'))();
/// When it was returned or forgiven (ms since epoch).
IntColumn get settledOn => integer().nullable()();
TextColumn get note => text().nullable()();
}
/// Any pasted URL (Wikipedia, forum). Polymorphic parent.
class ExternalLinks extends Table with SyncColumns {
TextColumn get parentType => textEnum<ParentType>()();

View file

@ -0,0 +1,86 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/db/database.dart';
import 'package:tane/db/enums.dart';
import '../support/test_support.dart';
/// A Plantare is a reproduction commitment (data-model §2.7): create it, list
/// it, mark it returned/forgiven, and remove it (soft-delete).
void main() {
late AppDatabase db;
setUp(() => db = newTestDatabase());
tearDown(() => db.close());
test('records a commitment and lists it (globally and per variety)', () async {
final repo = newTestRepository(db);
final vid = await repo.addQuickVariety(label: 'Tomate rosa');
final id = await repo.createPlantare(
direction: PlantareDirection.iReturn,
varietyId: vid,
counterparty: 'Ana',
owedDescription: 'un puñado la próxima temporada',
);
final all = await repo.watchPlantares().first;
expect(all, hasLength(1));
expect(all.single.id, id);
expect(all.single.direction, PlantareDirection.iReturn);
expect(all.single.counterparty, 'Ana');
expect(all.single.status, PlantareStatus.open);
expect(all.single.madeOn, greaterThan(0));
final forVariety = await repo.watchPlantaresForVariety(vid).first;
expect(forVariety.single.id, id);
// A different variety has none.
final other = await repo.addQuickVariety(label: 'Judía');
expect(await repo.watchPlantaresForVariety(other).first, isEmpty);
});
test('marking it returned stamps the settle time; forgiving keeps it settled',
() async {
final repo = newTestRepository(db);
final id = await repo.createPlantare(direction: PlantareDirection.owedToMe);
await repo.setPlantareStatus(id, PlantareStatus.returned);
var row = (await repo.watchPlantares().first).single;
expect(row.status, PlantareStatus.returned);
expect(row.settledOn, isNotNull);
// Reopening clears the settle stamp.
await repo.setPlantareStatus(id, PlantareStatus.open);
row = (await repo.watchPlantares().first).single;
expect(row.status, PlantareStatus.open);
expect(row.settledOn, isNull);
});
test('deleting a commitment tombstones it (drops from the list)', () async {
final repo = newTestRepository(db);
final id = await repo.createPlantare(direction: PlantareDirection.iReturn);
expect(await repo.watchPlantares().first, hasLength(1));
await repo.deletePlantare(id);
expect(await repo.watchPlantares().first, isEmpty);
});
test('commitments survive a backup round-trip (in exportInventory/import)',
() async {
final repoA = newTestRepository(db);
final vid = await repoA.addQuickVariety(label: 'Maíz');
await repoA.createPlantare(
direction: PlantareDirection.iReturn,
varietyId: vid,
counterparty: 'Colectivo semillero',
owedDescription: 'una mazorca',
);
final snapshot = await repoA.exportInventory();
expect(snapshot.plantares, hasLength(1));
final dbB = newTestDatabase();
addTearDown(dbB.close);
final repoB = newTestRepository(dbB);
await repoB.importInventory(snapshot);
final onB = await repoB.watchPlantares().first;
expect(onB.single.counterparty, 'Colectivo semillero');
expect(onB.single.owedDescription, 'una mazorca');
});
}

View file

@ -11,68 +11,20 @@ void main() {
verifier = SchemaVerifier(GeneratedHelper());
});
test('freshly created database matches the exported schema v8', () async {
final schema = await verifier.schemaAt(8);
test('freshly created database matches the exported schema v9', () async {
final schema = await verifier.schemaAt(9);
final db = AppDatabase(schema.newConnection());
await verifier.migrateAndValidate(db, 8);
await verifier.migrateAndValidate(db, 9);
await db.close();
});
test('upgrades v1 → v8 (Lot.type, harvestMonth, presentation, '
'Attachment.sortOrder, Variety.isDraft/isOrganic, Species.viabilityYears, '
'v8 provenance/calendar/abundance/condition-checks) and matches the fresh '
'schema', () async {
final connection = await verifier.startAt(1);
final db = AppDatabase(connection);
await verifier.migrateAndValidate(db, 8);
await db.close();
});
test('upgrades v2 → v8 and matches the fresh schema', () async {
final connection = await verifier.startAt(2);
final db = AppDatabase(connection);
await verifier.migrateAndValidate(db, 8);
await db.close();
});
test('upgrades v3 → v8 and matches the fresh schema', () async {
final connection = await verifier.startAt(3);
final db = AppDatabase(connection);
await verifier.migrateAndValidate(db, 8);
await db.close();
});
test('upgrades v4 → v8 and matches the fresh schema', () async {
final connection = await verifier.startAt(4);
final db = AppDatabase(connection);
await verifier.migrateAndValidate(db, 8);
await db.close();
});
test(
'upgrades v5 → v8 (adds Variety.isDraft) and matches the fresh schema',
() async {
final connection = await verifier.startAt(5);
// Every historical version upgrades cleanly to the current schema (v9).
for (var from = 1; from <= 8; from++) {
test('upgrades v$from → v9 and matches the fresh schema', () async {
final connection = await verifier.startAt(from);
final db = AppDatabase(connection);
await verifier.migrateAndValidate(db, 8);
await verifier.migrateAndValidate(db, 9);
await db.close();
},
);
test('upgrades v6 → v8 (adds Variety.isOrganic, Species.viabilityYears) and '
'matches the fresh schema', () async {
final connection = await verifier.startAt(6);
final db = AppDatabase(connection);
await verifier.migrateAndValidate(db, 8);
await db.close();
});
test('upgrades v7 → v8 (adds Variety.needsReproduction + crop calendar, '
'Lot.origin/abundance/preservationFormat, ConditionChecks) and matches '
'the fresh schema', () async {
final connection = await verifier.startAt(7);
final db = AppDatabase(connection);
await verifier.migrateAndValidate(db, 8);
await db.close();
});
});
}
}

View file

@ -12,6 +12,7 @@ import 'schema_v5.dart' as v5;
import 'schema_v6.dart' as v6;
import 'schema_v7.dart' as v7;
import 'schema_v8.dart' as v8;
import 'schema_v9.dart' as v9;
class GeneratedHelper implements SchemaInstantiationHelper {
@override
@ -33,10 +34,12 @@ class GeneratedHelper implements SchemaInstantiationHelper {
return v7.DatabaseAtV7(db);
case 8:
return v8.DatabaseAtV8(db);
case 9:
return v9.DatabaseAtV9(db);
default:
throw MissingSchemaException(version, versions);
}
}
static const versions = const [1, 2, 3, 4, 5, 6, 7, 8];
static const versions = const [1, 2, 3, 4, 5, 6, 7, 8, 9];
}

File diff suppressed because it is too large Load diff