Files
ApiCore/ApiCore-Backend/src/compliance/herd-snapshot.ts
T
Nick SzaunigandClaude Opus 5.5 edc193f128
Backend Image / build-and-push (push) Successful in 5m13s
Frontend Image / build-and-push (push) Successful in 8m54s
feat: T6 wave 3 – treatment books from lot, label print lock, restricted zone, authority notices
- Treatments book their dose from a medicine lot (delta booking on edit,
  bulk all-or-nothing, idempotent); Bestandsbuch columns from the lot,
  FEHLT exactly where treatmentLogGaps reports a gap; Bestandsbuch export
  needs veterinary-medicines:read.
- Label printing: 409 LABEL_PARTICULARS_MISSING on gaps, proof print with
  watermark, PRINT audit before the PDF, check endpoints; digit rules only
  from the seeded ComplianceSettings row (fail closed).
- Restricted zone (Berlin day): create, update, move, merge and CSV import
  blocked inside an active restriction; override with reason and
  compliance:manage, audited, never stored on the colony; split, harvest
  and dissolve stay free; restriction details only with compliance:read.
- Authority notices: settings, herd snapshot, registration/herd change/TSK
  notices with one open draft per kind under the settings lock.
- Label check refinements (geometric reading order, number|unit pairs).
- ARCHITECTURE.md §12.6–12.8, Annahmen 71–77; spec §5.6 Berlin day.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-15 14:18:41 +02:00

162 lines
4.5 KiB
TypeScript

import { ColonyType, ComplianceSettings } from '../../generated/prisma';
import { LIVING_COLONY_WHERE } from '../colonies/colony-status';
import { DbClient } from '../prisma/db-client';
export const HERD_SNAPSHOT_VERSION = 1;
export interface HerdApiarySnapshot {
apiaryId: string;
name: string;
address: string | null;
location: string | null;
latitude: number | null;
longitude: number | null;
livingColonies: number;
byType: Partial<Record<ColonyType, number>>;
}
export interface HerdSnapshot {
version: 1;
takenAt: string;
apiaries: HerdApiarySnapshot[];
totalLiving: number;
}
/** An active apiary with the colony type of each living colony standing there. */
export interface HerdApiaryRow {
apiaryId: string;
name: string;
address: string | null;
location: string | null;
latitude: number | null;
longitude: number | null;
colonyTypes: ColonyType[];
}
export interface HerdDeviation {
triggered: boolean;
colonyCountChanged: boolean;
apiariesAdded: string[];
apiariesRemoved: string[];
apiariesRelocated: string[];
}
type DeviationSettings = Pick<
ComplianceSettings,
'noticeOnColonyCountChange' | 'noticeOnApiaryChange'
>;
/** Pure: counts the living colonies per apiary and per type. */
export function buildHerdSnapshot(
rows: readonly HerdApiaryRow[],
takenAt: Date,
excludedTypes: readonly ColonyType[] = [],
): HerdSnapshot {
const apiaries = rows.map((row): HerdApiarySnapshot => {
const byType: Partial<Record<ColonyType, number>> = {};
let livingColonies = 0;
for (const type of row.colonyTypes) {
if (excludedTypes.includes(type)) {
continue;
}
byType[type] = (byType[type] ?? 0) + 1;
livingColonies += 1;
}
return {
apiaryId: row.apiaryId,
name: row.name,
address: row.address,
location: row.location,
latitude: row.latitude,
longitude: row.longitude,
livingColonies,
byType,
};
});
return {
version: HERD_SNAPSHOT_VERSION,
takenAt: takenAt.toISOString(),
apiaries,
totalLiving: apiaries.reduce(
(sum, apiary) => sum + apiary.livingColonies,
0,
),
};
}
/** Active apiaries with their living colonies (LIVING_COLONY_WHERE). */
export async function loadHerdApiaryRows(
db: DbClient,
): Promise<HerdApiaryRow[]> {
const apiaries = await db.apiary.findMany({
where: { status: 'ACTIVE' },
select: {
id: true,
name: true,
address: true,
location: true,
latitude: true,
longitude: true,
colonies: { where: LIVING_COLONY_WHERE, select: { colonyType: true } },
},
orderBy: [{ name: 'asc' }, { id: 'asc' }],
});
return apiaries.map((apiary) => ({
apiaryId: apiary.id,
name: apiary.name,
address: apiary.address,
location: apiary.location,
latitude: apiary.latitude,
longitude: apiary.longitude,
colonyTypes: apiary.colonies.map((colony) => colony.colonyType),
}));
}
function sameSite(a: HerdApiarySnapshot, b: HerdApiarySnapshot): boolean {
return (
a.address === b.address &&
a.location === b.location &&
a.latitude === b.latitude &&
a.longitude === b.longitude
);
}
/**
* How the current herd differs from the baseline. The count is compared with
* the corrected `totalColonies` of the notice, not with its snapshot. A move
* between apiaries keeps the total and triggers nothing.
*/
export function herdDeviation(
baseline: { snapshot: HerdSnapshot; totalColonies: number },
current: HerdSnapshot,
settings: DeviationSettings,
): HerdDeviation {
const before = new Map(
baseline.snapshot.apiaries.map((apiary) => [apiary.apiaryId, apiary]),
);
const now = new Map(
current.apiaries.map((apiary) => [apiary.apiaryId, apiary]),
);
const apiariesAdded = [...now.keys()].filter((id) => !before.has(id));
const apiariesRemoved = [...before.keys()].filter((id) => !now.has(id));
const apiariesRelocated = [...now.entries()]
.filter(([id, apiary]) => {
const old = before.get(id);
return old !== undefined && !sameSite(old, apiary);
})
.map(([id]) => id);
const colonyCountChanged = baseline.totalColonies !== current.totalLiving;
const apiaryChanged =
apiariesAdded.length + apiariesRemoved.length + apiariesRelocated.length >
0;
return {
triggered:
(settings.noticeOnColonyCountChange && colonyCountChanged) ||
(settings.noticeOnApiaryChange && apiaryChanged),
colonyCountChanged,
apiariesAdded,
apiariesRemoved,
apiariesRelocated,
};
}