Platform backbone (plan 2026-10-13-plattform-rueckgrat), all tasks reviewed: - webhooks with delivery table, retries and stable delivery id - calendar handlers; a finished task removes its Outlook event - tasks, automations, inspections, varroa, treatments, feedings, harvests, colonies, wintering, stock and bottling record domain events in the same transaction; legacy post-commit calls removed - row locks through one helper (lockRowForUpdate, lockRowsForShare, lockRowsForUpdate) - job framework with JobRun, cli exit codes, cleanup, task templates, daily evaluation, hourly app-backup and the rekey job - system API and page "Verwaltung > System" with retry - @nestjs/schedule removed, guard tests against in-process schedulers Field capture T3 (plan 2026-10-13-t3-erfassung-am-stand), all tasks reviewed: - inspection photo offline without metadata - bulk capture for treatments, feedings and varroa (backend + frontend) - offline stand mode with service worker, offline pages and packs - offline session, cold start and logout on shared devices Docs: ARCHITECTURE.md assumptions and sections updated, TASKS.md. Gates: backend lint, typecheck, 1770 unit, 420 e2e, build, no schema drift; frontend lint, typecheck, 913 tests, build. Not rolled out. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
225 lines
6.8 KiB
TypeScript
225 lines
6.8 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 }[];
|
|
}
|
|
|
|
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);
|
|
});
|
|
|
|
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 () => {
|
|
await request(app.getHttpServer())
|
|
.patch(`/api/v1/harvests/${harvestId}`)
|
|
.set('Authorization', `Bearer ${staffToken}`)
|
|
.send({ colonyIds: [colonyOneId] })
|
|
.expect(200);
|
|
|
|
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],
|
|
});
|
|
});
|
|
});
|