import { AuthorityNotice, ComplianceSettings } from '../../generated/prisma'; import { DbClient } from '../prisma/db-client'; import { buildHerdSnapshot, herdDeviation, HerdDeviation, HerdSnapshot, loadHerdApiaryRows, } from './herd-snapshot'; export const COMPLIANCE_SETTINGS_ID = 'singleton'; export interface HerdStatus { settings: ComplianceSettings; baseline: AuthorityNotice | null; current: HerdSnapshot; /** null without a baseline: there is nothing to deviate from. */ deviation: HerdDeviation | null; } /** The settings row, created with its defaults when it does not exist yet. */ export async function complianceSettingsIn( db: DbClient, ): Promise { const existing = await db.complianceSettings.findUnique({ where: { id: COMPLIANCE_SETTINGS_ID }, }); if (existing) { return existing; } return db.complianceSettings.upsert({ where: { id: COMPLIANCE_SETTINGS_ID }, update: {}, create: { id: COMPLIANCE_SETTINGS_ID }, }); } /** * The baseline is the newest SENT registration or herd change (by sentOn); * TSK reports go to another recipient and do not count. */ export function findBaselineIn(db: DbClient): Promise { return db.authorityNotice.findFirst({ where: { status: 'SENT', kind: { in: ['REGISTRATION', 'HERD_CHANGE'] } }, orderBy: [{ sentOn: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }], }); } export async function herdStatusIn( db: DbClient, now: Date, ): Promise { const settings = await complianceSettingsIn(db); const baseline = await findBaselineIn(db); const current = buildHerdSnapshot(await loadHerdApiaryRows(db), now); return { settings, baseline, current, deviation: baseline ? herdDeviation( { snapshot: baseline.snapshot as unknown as HerdSnapshot, totalColonies: baseline.totalColonies, }, current, settings, ) : null, }; }