- Schema III: per-user notifications (broadcast fan-out migration, category, link, requiredPermissions filter), notification preferences and settings endpoints, calendar withdrawal switch, occupiedFrames - Suggestions API: list/summary with permission visibility and paging, accept/dismiss/reopen incl. bulk, SuggestionView on all responses - Varroa traffic light by season and method, young colonies, treatment effect window, sample-based percentage; shared withdrawal-window helper on Berlin calendar days; GET /varroa-measurements/thresholds - ColonySplit and QueenAssigned domain events with calendar and webhook handlers - Outbox claims compare against now() rounded to timestamp(3); fixes the flaky e2e claims of rows written with SQL now() Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
449 lines
14 KiB
TypeScript
449 lines
14 KiB
TypeScript
import { INestApplication } from '@nestjs/common';
|
|
import * as bcrypt from 'bcryptjs';
|
|
import request from 'supertest';
|
|
import { App } from 'supertest/types';
|
|
import { PrismaService } from '../src/prisma/prisma.service';
|
|
import { createTestApp } from './utils/create-test-app';
|
|
import { login } from './utils/api';
|
|
|
|
interface VarroaMeasurementBody {
|
|
id: string;
|
|
colonyId: string;
|
|
calculatedValue: number | null;
|
|
}
|
|
|
|
interface BulkVarroaBody {
|
|
bulkId: string;
|
|
records: (VarroaMeasurementBody & {
|
|
miteCount: number | null;
|
|
durationMinutes: number | null;
|
|
assessment: string | null;
|
|
})[];
|
|
}
|
|
|
|
describe('Varroa measurements (e2e)', () => {
|
|
let app: INestApplication<App>;
|
|
let prisma: PrismaService;
|
|
const beekeeperEmail = `varroa-e2e-beekeeper-${Date.now()}@example.com`;
|
|
const staffEmail = `varroa-e2e-staff-${Date.now()}@example.com`;
|
|
const password = 'SuperSecret123!';
|
|
let beekeeperId: string;
|
|
let staffId: string;
|
|
let beekeeperToken: string;
|
|
let staffToken: string;
|
|
let apiaryId: string;
|
|
let colonyId: string;
|
|
let measurementId: string;
|
|
let noVarroaRoleId: string;
|
|
let noVarroaUserId: string;
|
|
let noVarroaToken: string;
|
|
|
|
beforeAll(async () => {
|
|
app = await createTestApp();
|
|
prisma = app.get(PrismaService);
|
|
|
|
const passwordHash = await bcrypt.hash(password, 12);
|
|
const beekeeper = await prisma.user.create({
|
|
data: {
|
|
email: beekeeperEmail,
|
|
passwordHash,
|
|
name: 'Beekeeper',
|
|
role: { connect: { key: 'BEEKEEPER' } },
|
|
},
|
|
});
|
|
beekeeperId = beekeeper.id;
|
|
const staff = await prisma.user.create({
|
|
data: {
|
|
email: staffEmail,
|
|
passwordHash,
|
|
name: 'Staff',
|
|
role: { connect: { key: 'STAFF' } },
|
|
},
|
|
});
|
|
staffId = staff.id;
|
|
beekeeperToken = (await login(app, beekeeperEmail, password)).accessToken;
|
|
staffToken = (await login(app, staffEmail, password)).accessToken;
|
|
|
|
const apiary = await prisma.apiary.create({
|
|
data: { name: `Stand ${Date.now()}` },
|
|
});
|
|
apiaryId = apiary.id;
|
|
const colony = await prisma.colony.create({
|
|
data: {
|
|
code: `V-${Date.now()}`,
|
|
apiaryId,
|
|
colonyType: 'PRODUCTION_COLONY',
|
|
},
|
|
});
|
|
colonyId = colony.id;
|
|
|
|
const noVarroaRole = await prisma.role.create({
|
|
data: {
|
|
key: `NO_VARROA_${Date.now()}`,
|
|
name: 'Ohne Varroa',
|
|
permissions: {
|
|
create: [{ permission: { connect: { key: 'apiaries:read' } } }],
|
|
},
|
|
},
|
|
});
|
|
noVarroaRoleId = noVarroaRole.id;
|
|
const noVarroaEmail = `varroa-e2e-novarroa-${Date.now()}@example.com`;
|
|
const noVarroaUser = await prisma.user.create({
|
|
data: {
|
|
email: noVarroaEmail,
|
|
passwordHash,
|
|
name: 'Ohne Varroa',
|
|
role: { connect: { id: noVarroaRoleId } },
|
|
},
|
|
});
|
|
noVarroaUserId = noVarroaUser.id;
|
|
noVarroaToken = (await login(app, noVarroaEmail, password)).accessToken;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
const measurementIds = (
|
|
await prisma.varroaMeasurement.findMany({
|
|
where: { colonyId },
|
|
select: { id: true },
|
|
})
|
|
).map((measurement) => measurement.id);
|
|
// Deliveries go with their event (ON DELETE CASCADE).
|
|
await prisma.domainEvent.deleteMany({
|
|
where: {
|
|
aggregateType: 'VarroaMeasurement',
|
|
aggregateId: { in: measurementIds },
|
|
},
|
|
});
|
|
await prisma.varroaMeasurement.deleteMany({ where: { colonyId } });
|
|
await prisma.colony.deleteMany({ where: { id: colonyId } });
|
|
await prisma.apiary.deleteMany({ where: { id: apiaryId } });
|
|
await prisma.refreshToken.deleteMany({
|
|
where: { userId: { in: [beekeeperId, staffId, noVarroaUserId] } },
|
|
});
|
|
await prisma.auditLog.deleteMany({
|
|
where: { userId: { in: [beekeeperId, staffId, noVarroaUserId] } },
|
|
});
|
|
await prisma.user.deleteMany({
|
|
where: { id: { in: [beekeeperId, staffId, noVarroaUserId] } },
|
|
});
|
|
await prisma.role.deleteMany({ where: { id: noVarroaRoleId } });
|
|
await app.close();
|
|
});
|
|
|
|
it('rejects create for a STAFF user', () => {
|
|
return request(app.getHttpServer())
|
|
.post('/api/v1/varroa-measurements')
|
|
.set('Authorization', `Bearer ${staffToken}`)
|
|
.send({
|
|
colonyId,
|
|
date: new Date().toISOString(),
|
|
method: 'NATURAL_MITE_FALL',
|
|
})
|
|
.expect(403);
|
|
});
|
|
|
|
it('lets a BEEKEEPER user record a measurement', async () => {
|
|
const response = await request(app.getHttpServer())
|
|
.post('/api/v1/varroa-measurements')
|
|
.set('Authorization', `Bearer ${beekeeperToken}`)
|
|
.send({
|
|
colonyId,
|
|
date: new Date().toISOString(),
|
|
method: 'NATURAL_MITE_FALL',
|
|
miteCount: 12,
|
|
durationMinutes: 4320,
|
|
})
|
|
.expect(201);
|
|
const created = response.body as VarroaMeasurementBody;
|
|
measurementId = created.id;
|
|
expect(measurementId).toEqual(expect.any(String));
|
|
expect(created.calculatedValue).toBe(4);
|
|
|
|
// Committed with the measurement and its audit entry; the threshold
|
|
// rule and the varroa.measured webhook follow from the event.
|
|
await expect(
|
|
prisma.auditLog.count({
|
|
where: {
|
|
entityType: 'VarroaMeasurement',
|
|
entityId: measurementId,
|
|
action: 'CREATE',
|
|
userId: beekeeperId,
|
|
},
|
|
}),
|
|
).resolves.toBe(1);
|
|
const events = await prisma.domainEvent.findMany({
|
|
where: { aggregateType: 'VarroaMeasurement', aggregateId: measurementId },
|
|
});
|
|
expect(events).toEqual([
|
|
expect.objectContaining({
|
|
type: 'VarroaMeasured',
|
|
actorUserId: beekeeperId,
|
|
payload: { colonyId },
|
|
status: 'PENDING',
|
|
}),
|
|
]);
|
|
});
|
|
|
|
it('recomputes mites/day when the count is corrected', async () => {
|
|
// The edit dialog sends the whole form, the stored rate included.
|
|
const response = await request(app.getHttpServer())
|
|
.patch(`/api/v1/varroa-measurements/${measurementId}`)
|
|
.set('Authorization', `Bearer ${beekeeperToken}`)
|
|
.send({
|
|
colonyId,
|
|
date: new Date().toISOString(),
|
|
method: 'NATURAL_MITE_FALL',
|
|
miteCount: 30,
|
|
durationMinutes: 4320,
|
|
calculatedValue: 4,
|
|
})
|
|
.expect(200);
|
|
expect((response.body as VarroaMeasurementBody).calculatedValue).toBe(10);
|
|
|
|
// A corrected count can cross the threshold: the rule re-evaluates it
|
|
// from VarroaCorrected.
|
|
await expect(
|
|
prisma.auditLog.count({
|
|
where: {
|
|
entityType: 'VarroaMeasurement',
|
|
entityId: measurementId,
|
|
action: 'UPDATE',
|
|
userId: beekeeperId,
|
|
},
|
|
}),
|
|
).resolves.toBe(1);
|
|
await expect(
|
|
prisma.domainEvent.findFirst({
|
|
where: { aggregateId: measurementId, type: 'VarroaCorrected' },
|
|
}),
|
|
).resolves.toMatchObject({
|
|
aggregateType: 'VarroaMeasurement',
|
|
actorUserId: beekeeperId,
|
|
payload: { colonyId },
|
|
});
|
|
});
|
|
|
|
it('lists measurements for the colony', async () => {
|
|
const response = await request(app.getHttpServer())
|
|
.get(`/api/v1/colonies/${colonyId}/varroa-measurements`)
|
|
.set('Authorization', `Bearer ${staffToken}`)
|
|
.expect(200);
|
|
const measurements = response.body as VarroaMeasurementBody[];
|
|
expect(measurements.some((entry) => entry.id === measurementId)).toBe(true);
|
|
});
|
|
|
|
describe('GET /varroa-measurements/thresholds', () => {
|
|
const thresholdsBody = (token: string, query = '') =>
|
|
request(app.getHttpServer())
|
|
.get(`/api/v1/varroa-measurements/thresholds${query}`)
|
|
.set('Authorization', `Bearer ${token}`);
|
|
|
|
it('returns the bands shape and is not shadowed by :id', async () => {
|
|
const response = await thresholdsBody(staffToken).expect(200);
|
|
|
|
const body = response.body as { day: string; active: boolean };
|
|
expect(Object.keys(body).sort()).toEqual(
|
|
['active', 'bands', 'day', 'postTreatmentUntil'].sort(),
|
|
);
|
|
expect(typeof body.active).toBe('boolean');
|
|
});
|
|
|
|
// The shared rule is never written here (parallel e2e workers); the
|
|
// inactive / custom value cases are covered by the unit specs.
|
|
|
|
it('rejects a role without any varroa permission', () =>
|
|
thresholdsBody(noVarroaToken).expect(403));
|
|
});
|
|
|
|
describe('POST /varroa-measurements/bulk', () => {
|
|
const suffix = Date.now();
|
|
const shared = {
|
|
date: '2026-09-10',
|
|
method: 'NATURAL_MITE_FALL',
|
|
durationMinutes: 4320,
|
|
notes: 'Windel nach Ameisensäure',
|
|
};
|
|
let bulkColonyIds: string[];
|
|
let endedColonyId: string;
|
|
|
|
const postBulk = (token: string, body: object) =>
|
|
request(app.getHttpServer())
|
|
.post('/api/v1/varroa-measurements/bulk')
|
|
.set('Authorization', `Bearer ${token}`)
|
|
.send(body);
|
|
|
|
const storedMeasurements = () =>
|
|
prisma.varroaMeasurement.count({
|
|
where: { colonyId: { in: [...bulkColonyIds, endedColonyId] } },
|
|
});
|
|
|
|
beforeAll(async () => {
|
|
const colonyAt = async (
|
|
code: string,
|
|
status: 'ACTIVE' | 'MERGED' = 'ACTIVE',
|
|
) =>
|
|
(
|
|
await prisma.colony.create({
|
|
data: {
|
|
code: `${code}-${suffix}`,
|
|
apiaryId,
|
|
colonyType: 'PRODUCTION_COLONY',
|
|
status,
|
|
},
|
|
})
|
|
).id;
|
|
bulkColonyIds = [await colonyAt('VB-1'), await colonyAt('VB-2')];
|
|
endedColonyId = await colonyAt('VB-X', 'MERGED');
|
|
});
|
|
|
|
afterAll(async () => {
|
|
const colonyIds = [...bulkColonyIds, endedColonyId];
|
|
const measurementIds = (
|
|
await prisma.varroaMeasurement.findMany({
|
|
where: { colonyId: { in: colonyIds } },
|
|
select: { id: true },
|
|
})
|
|
).map((measurement) => measurement.id);
|
|
await prisma.domainEvent.deleteMany({
|
|
where: {
|
|
aggregateType: 'VarroaMeasurement',
|
|
aggregateId: { in: measurementIds },
|
|
},
|
|
});
|
|
await prisma.varroaMeasurement.deleteMany({
|
|
where: { colonyId: { in: colonyIds } },
|
|
});
|
|
await prisma.colony.deleteMany({ where: { id: { in: colonyIds } } });
|
|
});
|
|
|
|
it('bulk derives mites per day per entry', async () => {
|
|
const response = await postBulk(beekeeperToken, {
|
|
...shared,
|
|
entries: [
|
|
{ colonyId: bulkColonyIds[0], miteCount: 30, assessment: 'hoch' },
|
|
{ colonyId: bulkColonyIds[1], miteCount: 6 },
|
|
],
|
|
}).expect(201);
|
|
|
|
const { bulkId, records } = response.body as BulkVarroaBody;
|
|
expect(
|
|
records.map((record) => ({
|
|
colonyId: record.colonyId,
|
|
miteCount: record.miteCount,
|
|
durationMinutes: record.durationMinutes,
|
|
calculatedValue: record.calculatedValue,
|
|
assessment: record.assessment,
|
|
})),
|
|
).toEqual([
|
|
{
|
|
colonyId: bulkColonyIds[0],
|
|
miteCount: 30,
|
|
durationMinutes: 4320,
|
|
calculatedValue: 10,
|
|
assessment: 'hoch',
|
|
},
|
|
{
|
|
colonyId: bulkColonyIds[1],
|
|
miteCount: 6,
|
|
durationMinutes: 4320,
|
|
calculatedValue: 2,
|
|
assessment: null,
|
|
},
|
|
]);
|
|
expect(
|
|
await prisma.domainEvent.count({
|
|
where: {
|
|
type: 'VarroaMeasured',
|
|
payload: { path: ['bulkId'], equals: bulkId },
|
|
},
|
|
}),
|
|
).toBe(2);
|
|
expect(
|
|
await prisma.auditLog.count({
|
|
where: {
|
|
entityType: 'VarroaMeasurement',
|
|
action: 'CREATE',
|
|
userId: beekeeperId,
|
|
entityId: { in: records.map((record) => record.id) },
|
|
},
|
|
}),
|
|
).toBe(2);
|
|
});
|
|
|
|
it('bulk rejects duplicate colonyId in entries', async () => {
|
|
const before = await storedMeasurements();
|
|
|
|
const response = await postBulk(beekeeperToken, {
|
|
...shared,
|
|
entries: [
|
|
{ colonyId: bulkColonyIds[0], miteCount: 3 },
|
|
{ colonyId: bulkColonyIds[0], miteCount: 4 },
|
|
],
|
|
}).expect(400);
|
|
|
|
expect(JSON.stringify(response.body)).toContain(
|
|
'entries enthält ein Volk doppelt',
|
|
);
|
|
expect(await storedMeasurements()).toBe(before);
|
|
});
|
|
|
|
it('bulk rejects the whole batch when one colony has ended and names it', async () => {
|
|
const before = await storedMeasurements();
|
|
|
|
const response = await postBulk(beekeeperToken, {
|
|
...shared,
|
|
entries: [
|
|
{ colonyId: bulkColonyIds[0], miteCount: 3 },
|
|
{ colonyId: endedColonyId, miteCount: 4 },
|
|
],
|
|
}).expect(400);
|
|
|
|
expect(
|
|
(response.body as { invalidColonyIds: string[] }).invalidColonyIds,
|
|
).toEqual([endedColonyId]);
|
|
expect(await storedMeasurements()).toBe(before);
|
|
});
|
|
|
|
it.each([
|
|
['no entry', {}, () => []],
|
|
[
|
|
'a shared mite count instead of one per entry',
|
|
{ miteCount: 5 },
|
|
() => [{ colonyId: bulkColonyIds[0] }],
|
|
],
|
|
[
|
|
'an invalid entry',
|
|
{},
|
|
() => [{ colonyId: bulkColonyIds[0], miteCount: -1 }],
|
|
],
|
|
])('bulk rejects %s', (_label, extra: object, entries: () => object[]) =>
|
|
postBulk(beekeeperToken, {
|
|
...shared,
|
|
...extra,
|
|
entries: entries(),
|
|
}).expect(400),
|
|
);
|
|
|
|
it('bulk rejects an empty colonyId in entries as invalid input, not as an unknown colony', async () => {
|
|
const response = await postBulk(beekeeperToken, {
|
|
...shared,
|
|
entries: [
|
|
{ colonyId: bulkColonyIds[0], miteCount: 3 },
|
|
{ colonyId: '', miteCount: 4 },
|
|
],
|
|
}).expect(400);
|
|
|
|
expect(JSON.stringify(response.body)).toContain(
|
|
'entries.1.colonyId enthält eine leere Volk-ID',
|
|
);
|
|
expect(response.body).not.toHaveProperty('invalidColonyIds');
|
|
});
|
|
|
|
it('bulk rejects a role without varroa:create', () =>
|
|
postBulk(staffToken, {
|
|
...shared,
|
|
entries: [{ colonyId: bulkColonyIds[0], miteCount: 1 }],
|
|
}).expect(403));
|
|
});
|
|
});
|