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; 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', legacyRole: 'ADMIN', role: { connect: { key: 'ADMIN' } }, }, }); adminId = admin.id; const staff = await prisma.user.create({ data: { email: staffEmail, passwordHash, name: 'Import E2E Staff', legacyRole: '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 () => { 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 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); }); 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('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); }); });