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 HoneyBatchBody { amount: number | null; status: string; } interface BottlingBatchBody { id: string; totalAmount: number; lotNumber: string; warnings: unknown[]; } interface RecordedEvent { type: string; payload: unknown; actorUserId: string | null; } describe('Bottling (e2e)', () => { let app: INestApplication; let prisma: PrismaService; const beekeeperEmail = `bottling-e2e-beekeeper-${Date.now()}@example.com`; const password = 'SuperSecret123!'; let beekeeperId: string; let beekeeperToken: string; // Removing a bottling needs bottling-batch:delete, which BEEKEEPER lacks. const adminEmail = `bottling-e2e-admin-${Date.now()}@example.com`; let adminId: string; let adminToken: string; let apiaryId: string; let colonyId: string; let harvestId: string; let extractionId: string; let honeyBatchId: string; let bottlingBatchId: string; const seenEventIds = new Set(); /** * The events recorded on the bottling since the last call, by type - one * request's events share a correlation id. */ async function newEventsOf(id: string): Promise { const events = ( await prisma.domainEvent.findMany({ where: { aggregateType: 'BottlingBatch', aggregateId: id }, select: { id: true, type: true, payload: true, actorUserId: true, correlationId: true, }, }) ).filter((event) => !seenEventIds.has(event.id)); events.forEach((event) => seenEventIds.add(event.id)); expect(new Set(events.map((event) => event.correlationId)).size).toBe(1); return events .map(({ type, payload, actorUserId }) => ({ type, payload, actorUserId })) .sort((a, b) => a.type.localeCompare(b.type)); } async function honeyBatchAmount(): Promise { const response = await request(app.getHttpServer()) .get(`/api/v1/honey-batches/${honeyBatchId}`) .set('Authorization', `Bearer ${beekeeperToken}`) .expect(200); return (response.body as HoneyBatchBody).amount; } 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; beekeeperToken = (await login(app, beekeeperEmail, password)).accessToken; const admin = await prisma.user.create({ data: { email: adminEmail, passwordHash, name: 'Admin', role: { connect: { key: 'ADMIN' } }, }, }); adminId = admin.id; adminToken = (await login(app, adminEmail, 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 harvest = await prisma.harvest.create({ data: { apiaryId, date: new Date(), userId: beekeeperId }, }); harvestId = harvest.id; await prisma.harvestColony.create({ data: { harvestId, colonyId } }); const extraction = await prisma.extraction.create({ data: { date: new Date(), userId: beekeeperId }, }); extractionId = extraction.id; await prisma.extractionHarvest.create({ data: { extractionId, harvestId }, }); const honeyBatch = await prisma.honeyBatch.create({ data: { batchNumber: `HC-${Date.now()}`, extractionId, amount: 25, // The movement book keeps this batch: bookings need a start amount. initialAmount: 25, // Below the warning limit: this file expects no quality warning. waterContent: 17, }, }); honeyBatchId = honeyBatch.id; }); afterAll(async () => { if (bottlingBatchId) { await prisma.domainEvent.deleteMany({ where: { aggregateType: 'BottlingBatch', aggregateId: bottlingBatchId, }, }); await prisma.bottlingBatch.deleteMany({ where: { id: bottlingBatchId } }); } await prisma.batchMovement.deleteMany({ where: { honeyBatchId } }); await prisma.honeyBatch.deleteMany({ where: { id: honeyBatchId } }); await prisma.extractionHarvest.deleteMany({ where: { extractionId } }); await prisma.extraction.deleteMany({ where: { id: extractionId } }); await prisma.harvestColony.deleteMany({ where: { harvestId } }); await prisma.harvest.deleteMany({ where: { id: harvestId } }); await prisma.colony.deleteMany({ where: { id: colonyId } }); await prisma.apiary.deleteMany({ where: { id: apiaryId } }); const userIds = [beekeeperId, adminId].filter(Boolean); await prisma.refreshToken.deleteMany({ where: { userId: { in: userIds } }, }); await prisma.auditLog.deleteMany({ where: { userId: { in: userIds } } }); await prisma.user.deleteMany({ where: { id: { in: userIds } } }); await app.close(); }); it('rejects a bottling amount exceeding the available honey batch amount', () => { return request(app.getHttpServer()) .post('/api/v1/bottling-batches') .set('Authorization', `Bearer ${beekeeperToken}`) .send({ honeyBatchId, date: new Date().toISOString(), jarSize: 500, jarCount: 1000, bestBeforeDate: new Date().toISOString(), lotNumber: `L-${Date.now()}`, }) .expect(400); }); it('bottles a honey batch and reduces its remaining amount', async () => { const response = await request(app.getHttpServer()) .post('/api/v1/bottling-batches') .set('Authorization', `Bearer ${beekeeperToken}`) .send({ honeyBatchId, date: new Date().toISOString(), jarSize: 500, jarCount: 50, bestBeforeDate: new Date().toISOString(), lotNumber: `L-${Date.now()}`, }) .expect(201); const bottlingBatch = response.body as BottlingBatchBody; bottlingBatchId = bottlingBatch.id; expect(bottlingBatch.totalAmount).toBe(25); // The harvest behind the honey batch has no withdrawal window. expect(bottlingBatch.warnings).toEqual([]); const honeyBatchResponse = await request(app.getHttpServer()) .get(`/api/v1/honey-batches/${honeyBatchId}`) .set('Authorization', `Bearer ${beekeeperToken}`) .expect(200); const honeyBatch = honeyBatchResponse.body as HoneyBatchBody; expect(honeyBatch.amount).toBe(0); expect(honeyBatch.status).toBe('BOTTLED'); // The booking in the movement book, in grams, with its bottling. const movements = await prisma.batchMovement.findMany({ where: { honeyBatchId }, }); expect(movements).toEqual([ expect.objectContaining({ type: 'BOTTLING', quantity: -25000, sourceBottlingBatchId: bottlingBatchId, userId: beekeeperId, }), ]); }); it('bottling create records BatchBottled and StockChanged together', async () => { expect(await newEventsOf(bottlingBatchId)).toEqual([ { type: 'BatchBottled', payload: { honeyBatchId }, actorUserId: beekeeperId, }, { type: 'StockChanged', payload: { bottlingBatchIds: [bottlingBatchId], productIds: [], rawMaterialKinds: [], }, actorUserId: beekeeperId, }, ]); }); it('a correction records BottlingCorrected and StockChanged together', async () => { const corrected = await request(app.getHttpServer()) .patch(`/api/v1/bottling-batches/${bottlingBatchId}`) .set('Authorization', `Bearer ${beekeeperToken}`) .send({ jarCount: 40 }) .expect(200); expect((corrected.body as BottlingBatchBody).warnings).toEqual([]); // 10 jars of 500 g fewer: 5 kg go back to the honey batch. expect(await honeyBatchAmount()).toBe(5); expect(await newEventsOf(bottlingBatchId)).toEqual([ { type: 'BottlingCorrected', payload: { honeyBatchId, removed: false }, actorUserId: beekeeperId, }, { type: 'StockChanged', payload: { bottlingBatchIds: [bottlingBatchId], productIds: [], rawMaterialKinds: [], }, actorUserId: beekeeperId, }, ]); }); it('a removal records BottlingCorrected { removed: true } and StockChanged together', async () => { await request(app.getHttpServer()) .delete(`/api/v1/bottling-batches/${bottlingBatchId}`) .set('Authorization', `Bearer ${adminToken}`) .expect(200); expect(await honeyBatchAmount()).toBe(25); expect(await newEventsOf(bottlingBatchId)).toEqual([ { type: 'BottlingCorrected', payload: { honeyBatchId, removed: true }, actorUserId: adminId, }, { type: 'StockChanged', payload: { bottlingBatchIds: [bottlingBatchId], productIds: [], rawMaterialKinds: [], }, actorUserId: adminId, }, ]); }); });