feat: hive setup data model and API (Beute L1)
Backend Image / build-and-push (push) Successful in 5m5s
Frontend Image / build-and-push (push) Successful in 11m2s

Each colony can now hold its hive setup (Ist-Zustand) as validated
JSON with an append-only change log:

- catalog: hive systems and part types with dimensions, placement
  rules and state fields; Liebig-Zander 10 seeded with fixed ids
  (owner's equipment incl. Bausperre, Futterzarge, Nassenheider)
- pure domain module (operations, validator, derived facts) with
  shared JSON fixtures the frontend runs too
- API: catalog (hive-systems:manage), setup create/change/history/
  state at a day (colonies:read/update), 409 HIVE_CONFLICT with the
  current state, idempotent writes, HiveChanged event
- inspections can carry hive ops saved in the same transaction
- backup export/import of the new tables (backup wins per colony)
- docs: ARCHITECTURE section 13, Annahmen 95-100

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Nick SzaunigandClaude Opus 5.5 committed 2026-10-15 21:23:23 +02:00
1 parent 8982d0796a
commit b48fb157c8
141 files changed
+15211 -17

No files matched your search

@@ -2,6 +2,7 @@ import { BadRequestException, Logger } from '@nestjs/common';
import * as path from 'node:path';
import { Prisma } from '../../generated/prisma';
import {
BackupBundle,
BackupService,
LEGACY_UNSEALED_TABLES,
MODELS_EXCLUDED_FROM_BACKUP,
@@ -113,7 +114,15 @@ describe('BackupService', () => {
document: { findMany: jest.Mock; count: jest.Mock };
$transaction: jest.Mock;
};
let tx: Record<string, { upsert: jest.Mock; update?: jest.Mock }> & {
let tx: Record<
string,
{
upsert: jest.Mock;
update?: jest.Mock;
create?: jest.Mock;
deleteMany?: jest.Mock;
}
> & {
permission: { findUnique: jest.Mock };
user: { upsert: jest.Mock; findMany: jest.Mock };
queen: { upsert: jest.Mock; update: jest.Mock; findMany: jest.Mock };
@@ -139,6 +148,10 @@ describe('BackupService', () => {
(tx as unknown as { $queryRaw: jest.Mock }).$queryRaw = jest
.fn()
.mockResolvedValue([]);
for (const key of ['hiveChange', 'hiveSetup']) {
tx[key].create = jest.fn().mockResolvedValue({});
tx[key].deleteMany = jest.fn().mockResolvedValue({ count: 0 });
}
tx.queen.update = jest.fn().mockResolvedValue({});
tx.queen.findMany = jest.fn().mockResolvedValue([]);
tx.document.findUnique = jest.fn().mockResolvedValue(null);
@@ -1948,6 +1961,80 @@ describe('BackupService', () => {
});
});
describe('importAll hive models', () => {
const hiveBundle = (): BackupBundle => ({
version: 3,
exportedAt: '2026-01-01T00:00:00.000Z',
data: {
hiveSystem: [{ id: 'hive-system-1', name: 'System' }],
hivePartType: [{ id: 'hive-part-1', systemId: 'hive-system-1' }],
colony: [{ id: 'colony-1' }, { id: 'colony-2' }],
hiveSetup: [
{ colonyId: 'colony-1', systemId: 'hive-system-1', version: 2 },
{ colonyId: 'colony-other', systemId: 'hive-system-1', version: 1 },
],
hiveChange: [
{ id: 'change-1', colonyId: 'colony-1', userId: 'known-user' },
{ id: 'change-2', colonyId: 'colony-1', userId: 'gone-user' },
{ id: 'change-3', colonyId: 'colony-other', userId: 'known-user' },
],
},
});
it('upserts the catalog by id so seeded rows are neither duplicated nor rejected', async () => {
await service.importAll(hiveBundle(), 'admin-1', TRUSTED);
expect(tx.hiveSystem.upsert).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: 'hive-system-1' } }),
);
expect(tx.hivePartType.upsert).toHaveBeenCalledWith(
expect.objectContaining({ where: { id: 'hive-part-1' } }),
);
});
it('replaces setup and history of each restored colony, remapping the history user', async () => {
const summary = await service.importAll(hiveBundle(), 'admin-1', TRUSTED);
expect(tx.hiveChange.deleteMany).toHaveBeenCalledWith({
where: { colonyId: { in: ['colony-1'] } },
});
expect(tx.hiveSetup.deleteMany).toHaveBeenCalledWith({
where: { colonyId: { in: ['colony-1'] } },
});
expect(tx.hiveSetup.create).toHaveBeenCalledTimes(1);
const created = tx.hiveChange.create!.mock.calls.map(
([arg]: [{ data: { id: string; userId: string } }]) => arg.data,
);
expect(created).toEqual([
expect.objectContaining({ id: 'change-1', userId: 'known-user' }),
expect.objectContaining({ id: 'change-2', userId: 'admin-1' }),
]);
expect(summary.imported).toMatchObject({
hiveSystem: 1,
hivePartType: 1,
hiveSetup: 2,
hiveChange: 3,
});
});
it('takes no hive table from an unsealed file and reports them', async () => {
const summary = await service.importAll(hiveBundle(), 'admin-1', {
trusted: false,
});
expect(tx.hiveSetup.create).not.toHaveBeenCalled();
expect(tx.hiveSystem.upsert).not.toHaveBeenCalled();
expect(summary.skipped).toEqual(
expect.arrayContaining([
'hiveSystem',
'hivePartType',
'hiveSetup',
'hiveChange',
]),
);
});
});
// Drift guard: a model added to the schema has to be backed up or listed
// in MODELS_EXCLUDED_FROM_BACKUP with its reason - never silently missing.
describe('model coverage', () => {
@@ -329,9 +329,13 @@ export class BackupService {
data.colony = await this.prisma.colony.findMany();
data.colonyApiaryHistory = await this.prisma.colonyApiaryHistory.findMany();
data.colonyLineage = await this.prisma.colonyLineage.findMany();
data.hiveSystem = await this.prisma.hiveSystem.findMany();
data.hivePartType = await this.prisma.hivePartType.findMany();
data.hiveSetup = await this.prisma.hiveSetup.findMany();
data.queenEvaluation = await this.prisma.queenEvaluation.findMany();
data.queenColonyHistory = await this.prisma.queenColonyHistory.findMany();
data.inspection = await this.prisma.inspection.findMany();
data.hiveChange = await this.prisma.hiveChange.findMany();
data.taskTemplate = await this.prisma.taskTemplate.findMany();
data.suggestion = await this.prisma.suggestion.findMany();
data.task = await this.prisma.task.findMany();
@@ -608,6 +612,26 @@ export class BackupService {
}
imported.queen = rowsOf('queen').length;
// Catalog first: a fresh install already carries the seeded rows with
// the same fixed ids, so upsert by id neither fails nor duplicates.
for (const row of rowsOf('hiveSystem')) {
await tx.hiveSystem.upsert({
where: { id: row.id as string },
create: row as never,
update: updateWith(row) as never,
});
}
imported.hiveSystem = rowsOf('hiveSystem').length;
for (const row of rowsOf('hivePartType')) {
await tx.hivePartType.upsert({
where: { id: row.id as string },
create: row as never,
update: updateWith(row) as never,
});
}
imported.hivePartType = rowsOf('hivePartType').length;
// Restore deliberately emits no ColonyCreated (no domain events).
for (const row of rowsOf('colony')) {
await tx.colony.upsert({
@@ -618,6 +642,33 @@ export class BackupService {
}
imported.colony = rowsOf('colony').length;
// A restore replaces, never merges: the backup's setup wins, so the
// existing setup and history of each restored colony go first (the
// history rows reference the setup). Their backup history follows
// after the inspections.
const hiveSetupRows = rowsOf('hiveSetup');
const restoredColonyIds = new Set(
rowsOf('colony').map((row) => row.id as string),
);
const setupsToReplace = hiveSetupRows.filter((row) =>
restoredColonyIds.has(row.colonyId as string),
);
const replacedColonyIds = setupsToReplace.map(
(row) => row.colonyId as string,
);
if (replacedColonyIds.length > 0) {
await tx.hiveChange.deleteMany({
where: { colonyId: { in: replacedColonyIds } },
});
await tx.hiveSetup.deleteMany({
where: { colonyId: { in: replacedColonyIds } },
});
}
for (const row of setupsToReplace) {
await tx.hiveSetup.create({ data: row as never });
}
imported.hiveSetup = hiveSetupRows.length;
for (const row of rowsOf('queen')) {
if (row.motherQueenId && !preexistingQueenIds.has(row.id as string)) {
await tx.queen.update({
@@ -692,6 +743,21 @@ export class BackupService {
}
imported.inspection = rowsOf('inspection').length;
const replacedColonies = new Set(replacedColonyIds);
const hiveChangeRows = rowsOf('hiveChange');
for (const row of hiveChangeRows) {
if (!replacedColonies.has(row.colonyId as string)) {
continue;
}
await tx.hiveChange.create({
data: {
...row,
userId: resolveUserId(asString(row, 'userId')),
} as never,
});
}
imported.hiveChange = hiveChangeRows.length;
for (const row of rowsOf('taskTemplate')) {
await tx.taskTemplate.upsert({
where: { id: row.id as string },