- Treatments book their dose from a medicine lot (delta booking on edit, bulk all-or-nothing, idempotent); Bestandsbuch columns from the lot, FEHLT exactly where treatmentLogGaps reports a gap; Bestandsbuch export needs veterinary-medicines:read. - Label printing: 409 LABEL_PARTICULARS_MISSING on gaps, proof print with watermark, PRINT audit before the PDF, check endpoints; digit rules only from the seeded ComplianceSettings row (fail closed). - Restricted zone (Berlin day): create, update, move, merge and CSV import blocked inside an active restriction; override with reason and compliance:manage, audited, never stored on the colony; split, harvest and dissolve stay free; restriction details only with compliance:read. - Authority notices: settings, herd snapshot, registration/herd change/TSK notices with one open draft per kind under the settings lock. - Label check refinements (geometric reading order, number|unit pairs). - ARCHITECTURE.md §12.6–12.8, Annahmen 71–77; spec §5.6 Berlin day. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
241 lines
7.9 KiB
TypeScript
241 lines
7.9 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 ImportRowBody {
|
|
row: number;
|
|
status: 'created' | 'skipped' | 'error';
|
|
message?: string;
|
|
id?: string;
|
|
}
|
|
|
|
interface ImportReportBody {
|
|
entity: string;
|
|
totalRows: number;
|
|
created: number;
|
|
skipped: number;
|
|
errors: number;
|
|
rows: ImportRowBody[];
|
|
}
|
|
|
|
function csvFile(content: string) {
|
|
return Buffer.from(content, 'utf-8');
|
|
}
|
|
|
|
describe('Import (e2e)', () => {
|
|
let app: INestApplication<App>;
|
|
let prisma: PrismaService;
|
|
const adminEmail = `import-e2e-admin-${Date.now()}@example.com`;
|
|
const staffEmail = `import-e2e-staff-${Date.now()}@example.com`;
|
|
const password = 'SuperSecret123!';
|
|
let adminId: string;
|
|
let staffId: string;
|
|
let adminToken: string;
|
|
let staffToken: string;
|
|
let apiaryId: string;
|
|
const apiaryName = `Import-Stand-${Date.now()}`;
|
|
|
|
beforeAll(async () => {
|
|
app = await createTestApp();
|
|
prisma = app.get(PrismaService);
|
|
|
|
const passwordHash = await bcrypt.hash(password, 12);
|
|
const admin = await prisma.user.create({
|
|
data: {
|
|
email: adminEmail,
|
|
passwordHash,
|
|
name: 'Import E2E Admin',
|
|
role: { connect: { key: 'ADMIN' } },
|
|
},
|
|
});
|
|
adminId = admin.id;
|
|
const staff = await prisma.user.create({
|
|
data: {
|
|
email: staffEmail,
|
|
passwordHash,
|
|
name: 'Import E2E Staff',
|
|
role: { connect: { key: 'STAFF' } },
|
|
},
|
|
});
|
|
staffId = staff.id;
|
|
adminToken = (await login(app, adminEmail, password)).accessToken;
|
|
staffToken = (await login(app, staffEmail, password)).accessToken;
|
|
|
|
const apiary = await prisma.apiary.create({ data: { name: apiaryName } });
|
|
apiaryId = apiary.id;
|
|
});
|
|
|
|
afterAll(async () => {
|
|
const colonyIds = (
|
|
await prisma.colony.findMany({
|
|
where: { apiaryId },
|
|
select: { id: true },
|
|
})
|
|
).map((colony) => colony.id);
|
|
await prisma.domainEvent.deleteMany({
|
|
where: { aggregateType: 'Colony', aggregateId: { in: colonyIds } },
|
|
});
|
|
await prisma.colony.deleteMany({ where: { apiaryId } });
|
|
await prisma.apiary.deleteMany({ where: { id: apiaryId } });
|
|
await prisma.apiary.deleteMany({
|
|
where: { name: { startsWith: 'CSV-Bienenstand-' } },
|
|
});
|
|
await prisma.queen.deleteMany({
|
|
where: { code: { startsWith: 'CSV-Q-' } },
|
|
});
|
|
await prisma.refreshToken.deleteMany({
|
|
where: { userId: { in: [adminId, staffId] } },
|
|
});
|
|
await prisma.auditLog.deleteMany({
|
|
where: { userId: { in: [adminId, staffId] } },
|
|
});
|
|
await prisma.user.deleteMany({ where: { id: { in: [adminId, staffId] } } });
|
|
await app.close();
|
|
});
|
|
|
|
it('rejects a non-admin', () => {
|
|
return request(app.getHttpServer())
|
|
.post('/api/v1/import/apiaries')
|
|
.set('Authorization', `Bearer ${staffToken}`)
|
|
.attach('file', csvFile('name\nTest'), {
|
|
filename: 'apiaries.csv',
|
|
contentType: 'text/csv',
|
|
})
|
|
.expect(403);
|
|
});
|
|
|
|
it('rejects a file without a .csv extension', () => {
|
|
return request(app.getHttpServer())
|
|
.post('/api/v1/import/apiaries')
|
|
.set('Authorization', `Bearer ${adminToken}`)
|
|
.attach('file', csvFile('name\nTest'), {
|
|
filename: 'apiaries.txt',
|
|
contentType: 'text/plain',
|
|
})
|
|
.expect(400);
|
|
});
|
|
|
|
it('imports apiaries, reporting one created and one validation error', async () => {
|
|
const csv = `name,location\nCSV-Bienenstand-${Date.now()},Garten\n,Ohne Namen`;
|
|
const response = await request(app.getHttpServer())
|
|
.post('/api/v1/import/apiaries')
|
|
.set('Authorization', `Bearer ${adminToken}`)
|
|
.attach('file', csvFile(csv), {
|
|
filename: 'apiaries.csv',
|
|
contentType: 'text/csv',
|
|
})
|
|
.expect(201);
|
|
const report = response.body as ImportReportBody;
|
|
expect(report.entity).toBe('apiaries');
|
|
expect(report.totalRows).toBe(2);
|
|
expect(report.created).toBe(1);
|
|
expect(report.errors).toBe(1);
|
|
expect(report.rows[1].status).toBe('error');
|
|
});
|
|
|
|
it('imports colonies, resolving the apiary by name and skipping duplicate codes on re-import', async () => {
|
|
const code = `CSV-V-${Date.now()}`;
|
|
const csv = `code,apiaryName,colonyType\n${code},${apiaryName},PRODUCTION_COLONY`;
|
|
|
|
const firstResponse = await request(app.getHttpServer())
|
|
.post('/api/v1/import/colonies')
|
|
.set('Authorization', `Bearer ${adminToken}`)
|
|
.attach('file', csvFile(csv), {
|
|
filename: 'colonies.csv',
|
|
contentType: 'text/csv',
|
|
})
|
|
.expect(201);
|
|
const firstReport = firstResponse.body as ImportReportBody;
|
|
expect(firstReport.created).toBe(1);
|
|
|
|
const colony = await prisma.colony.findUniqueOrThrow({ where: { code } });
|
|
const events = await prisma.domainEvent.findMany({
|
|
where: { type: 'ColonyCreated', aggregateId: colony.id },
|
|
});
|
|
expect(events).toHaveLength(1);
|
|
expect(events[0].payload).toEqual({ apiaryId });
|
|
|
|
const secondResponse = await request(app.getHttpServer())
|
|
.post('/api/v1/import/colonies')
|
|
.set('Authorization', `Bearer ${adminToken}`)
|
|
.attach('file', csvFile(csv), {
|
|
filename: 'colonies.csv',
|
|
contentType: 'text/csv',
|
|
})
|
|
.expect(201);
|
|
const secondReport = secondResponse.body as ImportReportBody;
|
|
expect(secondReport.created).toBe(0);
|
|
expect(secondReport.skipped).toBe(1);
|
|
// The skipped re-import leaves no second event.
|
|
expect(
|
|
await prisma.domainEvent.count({
|
|
where: { type: 'ColonyCreated', aggregateId: colony.id },
|
|
}),
|
|
).toBe(1);
|
|
});
|
|
|
|
it('reports an error when the referenced apiary is unknown', async () => {
|
|
const csv = `code,apiaryName,colonyType\nCSV-V-Unknown,Nicht Vorhanden,PRODUCTION_COLONY`;
|
|
const response = await request(app.getHttpServer())
|
|
.post('/api/v1/import/colonies')
|
|
.set('Authorization', `Bearer ${adminToken}`)
|
|
.attach('file', csvFile(csv), {
|
|
filename: 'colonies.csv',
|
|
contentType: 'text/csv',
|
|
})
|
|
.expect(201);
|
|
const report = response.body as ImportReportBody;
|
|
expect(report.errors).toBe(1);
|
|
expect(report.rows[0].message).toContain('nicht gefunden');
|
|
});
|
|
|
|
it('refuses to import a colony into an apiary in a restricted zone', async () => {
|
|
const code = `CSV-V-Zone-${Date.now()}`;
|
|
const csv = `code,apiaryName,colonyType
|
|
${code},${apiaryName},PRODUCTION_COLONY`;
|
|
const restriction = await prisma.apiaryRestriction.create({
|
|
data: {
|
|
apiaryId,
|
|
disease: 'Faulbrut',
|
|
startsOn: new Date('2000-01-01T00:00:00.000Z'),
|
|
},
|
|
});
|
|
try {
|
|
const response = await request(app.getHttpServer())
|
|
.post('/api/v1/import/colonies')
|
|
.set('Authorization', `Bearer ${adminToken}`)
|
|
.attach('file', csvFile(csv), {
|
|
filename: 'colonies.csv',
|
|
contentType: 'text/csv',
|
|
})
|
|
.expect(201);
|
|
const report = response.body as ImportReportBody;
|
|
expect(report.created).toBe(0);
|
|
expect(report.errors).toBe(1);
|
|
expect(report.rows[0].message).toContain('Sperrbezirk');
|
|
expect(await prisma.colony.count({ where: { code } })).toBe(0);
|
|
} finally {
|
|
await prisma.apiaryRestriction.delete({ where: { id: restriction.id } });
|
|
}
|
|
});
|
|
|
|
it('imports queens', async () => {
|
|
const code = `CSV-Q-${Date.now()}`;
|
|
const csv = `code,breed\n${code},Carnica`;
|
|
const response = await request(app.getHttpServer())
|
|
.post('/api/v1/import/queens')
|
|
.set('Authorization', `Bearer ${adminToken}`)
|
|
.attach('file', csvFile(csv), {
|
|
filename: 'queens.csv',
|
|
contentType: 'text/csv',
|
|
})
|
|
.expect(201);
|
|
const report = response.body as ImportReportBody;
|
|
expect(report.created).toBe(1);
|
|
});
|
|
});
|