Files
ApiCore/ApiCore-Backend/test/harvests.e2e-spec.ts
T
Nick SzaunigandClaude Opus 5.5 ef33e5549b feat: T4 wave 5 - colony end cleanup, withdrawal chain, next steps, inspection takeover UI
- Colony end releases the queen in the same transaction; open
  suggestions become obsolete and a CLEANUP suggestion lists open
  tasks and the queen; apply-cleanup validates evidence and blocks
  reactivated colonies
- Withdrawal chain: plausibility warnings on harvest and bottling,
  conflict notifications also when a treatment is entered or corrected
  after the harvest (naming bottled lots), withdrawal spans in the
  calendar and M365 sync, Berlin-day end events
- Next 3 steps per colony and the "Heute" endpoint with ranking and an
  explicit merge table by intent
- Inspection-triggered rule suggestions follow the colony's latest
  inspection (resolve when the finding is gone, refresh when it stays)
- Frontend: colony card takeover in the inspection form, feed status as
  condition, occupied frames 0-40; legacy offline entries keep syncing
- Notifications and preferences are deleted with their user

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

229 lines
7.0 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';
import { drainDomainEvents } from './utils/domain-events';
interface HarvestBody {
id: string;
apiaryId: string;
colonies: { colonyId: string }[];
warnings: unknown[];
}
describe('Harvests (e2e)', () => {
let app: INestApplication<App>;
let prisma: PrismaService;
const staffEmail = `harvests-e2e-staff-${Date.now()}@example.com`;
const readonlyEmail = `harvests-e2e-readonly-${Date.now()}@example.com`;
const password = 'SuperSecret123!';
let staffId: string;
let readonlyId: string;
let staffToken: string;
let readonlyToken: string;
let apiaryId: string;
let colonyOneId: string;
let colonyTwoId: string;
let harvestId: string;
let subscriptionId: string;
beforeAll(async () => {
app = await createTestApp();
prisma = app.get(PrismaService);
const passwordHash = await bcrypt.hash(password, 12);
const staff = await prisma.user.create({
data: {
email: staffEmail,
passwordHash,
name: 'Staff',
role: { connect: { key: 'STAFF' } },
},
});
staffId = staff.id;
const readonly = await prisma.user.create({
data: {
email: readonlyEmail,
passwordHash,
name: 'Readonly',
role: { connect: { key: 'READONLY' } },
},
});
readonlyId = readonly.id;
staffToken = (await login(app, staffEmail, password)).accessToken;
readonlyToken = (await login(app, readonlyEmail, password)).accessToken;
const apiary = await prisma.apiary.create({
data: { name: `Stand ${Date.now()}` },
});
apiaryId = apiary.id;
const colonyOne = await prisma.colony.create({
data: {
code: `V-${Date.now()}-A`,
apiaryId,
colonyType: 'PRODUCTION_COLONY',
},
});
colonyOneId = colonyOne.id;
const colonyTwo = await prisma.colony.create({
data: {
code: `V-${Date.now()}-B`,
apiaryId,
colonyType: 'PRODUCTION_COLONY',
},
});
colonyTwoId = colonyTwo.id;
});
afterAll(async () => {
if (subscriptionId) {
// Its deliveries go with it, ON DELETE CASCADE.
await prisma.webhookSubscription.deleteMany({
where: { id: subscriptionId },
});
}
if (harvestId) {
await prisma.domainEvent.deleteMany({
where: { aggregateType: 'Harvest', aggregateId: harvestId },
});
await prisma.harvestColony.deleteMany({ where: { harvestId } });
await prisma.harvest.deleteMany({ where: { id: harvestId } });
}
await prisma.colony.deleteMany({
where: { id: { in: [colonyOneId, colonyTwoId] } },
});
await prisma.apiary.deleteMany({ where: { id: apiaryId } });
await prisma.refreshToken.deleteMany({
where: { userId: { in: [staffId, readonlyId] } },
});
await prisma.auditLog.deleteMany({
where: { userId: { in: [staffId, readonlyId] } },
});
await prisma.user.deleteMany({
where: { id: { in: [staffId, readonlyId] } },
});
await app.close();
});
it('rejects create for a READONLY user', () => {
return request(app.getHttpServer())
.post('/api/v1/harvests')
.set('Authorization', `Bearer ${readonlyToken}`)
.send({
apiaryId,
date: new Date().toISOString(),
colonyIds: [colonyOneId],
})
.expect(403);
});
it('lets a STAFF user record a harvest across multiple colonies', async () => {
const response = await request(app.getHttpServer())
.post('/api/v1/harvests')
.set('Authorization', `Bearer ${staffToken}`)
.send({
apiaryId,
date: new Date().toISOString(),
colonyIds: [colonyOneId, colonyTwoId],
netWeight: 18.5,
})
.expect(201);
const harvest = response.body as HarvestBody;
harvestId = harvest.id;
expect(harvest.colonies).toHaveLength(2);
// No treatment with a withdrawal period: the list is there, and empty.
expect(harvest.warnings).toEqual([]);
});
it('wrote the audit entry and HarvestRecorded with the colony ids together with the harvest', async () => {
expect(
await prisma.auditLog.count({
where: {
entityType: 'Harvest',
entityId: harvestId,
action: 'CREATE',
userId: staffId,
},
}),
).toBe(1);
const events = await prisma.domainEvent.findMany({
where: { aggregateType: 'Harvest', aggregateId: harvestId },
});
expect(events).toHaveLength(1);
expect(events[0].type).toBe('HarvestRecorded');
expect(events[0].actorUserId).toBe(staffId);
const payload = events[0].payload as {
apiaryId: string;
colonyIds: string[];
};
expect(payload.apiaryId).toBe(apiaryId);
expect([...payload.colonyIds].sort()).toEqual(
[colonyOneId, colonyTwoId].sort(),
);
});
it('queues harvest.created from the event handler, once', async () => {
subscriptionId = (
await prisma.webhookSubscription.create({
data: {
url: 'https://hooks.example.com/harvests-e2e',
events: ['harvest.created'],
secret: `harvests-e2e-${Date.now()}`,
createdByUserId: staffId,
},
})
).id;
// The request itself queued nothing.
expect(
await prisma.webhookDelivery.count({ where: { subscriptionId } }),
).toBe(0);
await drainDomainEvents(app, [harvestId]);
await drainDomainEvents(app, [harvestId]);
const deliveries = await prisma.webhookDelivery.findMany({
where: { subscriptionId },
});
expect(deliveries).toHaveLength(1);
expect(deliveries[0].event).toBe('harvest.created');
expect(deliveries[0].body).toContain(harvestId);
});
it('returns the harvest with its colonies on lookup', async () => {
const response = await request(app.getHttpServer())
.get(`/api/v1/harvests/${harvestId}`)
.set('Authorization', `Bearer ${readonlyToken}`)
.expect(200);
const harvest = response.body as HarvestBody;
const colonyIds = harvest.colonies.map((entry) => entry.colonyId);
expect(colonyIds).toEqual(
expect.arrayContaining([colonyOneId, colonyTwoId]),
);
});
it('records HarvestCorrected with the new colony set on an edit', async () => {
const edited = await request(app.getHttpServer())
.patch(`/api/v1/harvests/${harvestId}`)
.set('Authorization', `Bearer ${staffToken}`)
.send({ colonyIds: [colonyOneId] })
.expect(200);
expect((edited.body as HarvestBody).warnings).toEqual([]);
const corrections = await prisma.domainEvent.findMany({
where: {
aggregateType: 'Harvest',
aggregateId: harvestId,
type: 'HarvestCorrected',
},
});
expect(corrections).toHaveLength(1);
expect(corrections[0].payload).toEqual({
apiaryId,
colonyIds: [colonyOneId],
});
});
});