Files
ApiCore/ApiCore-Backend/test/import.e2e-spec.ts
T
Nick Szaunig 4f2f31c05f feat(backend): CSV-Import für Stammdaten (Modul 33)
Neues ImportModule mit einem abhängigkeitsfreien CSV-Parser
(src/import/csv.ts, RFC4180-artig: Quoting, escapte Anführungszeichen,
CRLF/LF) passend zum bereits im ExportModule verwendeten
Schreibformat, sodass exportierte CSVs unverändert wieder importierbar
sind.

Endpunkt: POST /import/:entity (multipart, nur Administrator) für
apiaries, colonies, queens. Jede Zeile wird über die exakt gleichen
class-validator-DTOs geprüft, die auch die regulären POST-Endpunkte
nutzen (CreateApiaryDto/CreateColonyDto/CreateQueenDto) – keine
duplizierte Validierungslogik.

Ergebnisbericht pro Zeile (erstellt/übersprungen/Fehler + Meldung):
- Colonies/Queens: Zeilen mit bereits existierendem Code werden
  übersprungen statt einen Fehler zu werfen (idempotenter Re-Import)
- Colonies lösen den Bienenstand über eine "apiaryName"-Spalte auf
  (case-insensitive), da eine CSV keine internen IDs kennen kann;
  unbekannter Name → Fehlerzeile statt Abbruch des gesamten Imports

Unit-Tests für den CSV-Parser (Quoting, escapte Anführungszeichen,
CRLF, leere Zeilen) und den ImportService (alle drei Entitäten,
Validierungsfehler, Duplikat-Skip, unbekannter Bienenstand). E2E-Tests
über echten multipart-Upload (Rollenprüfung, Dateiendungsprüfung, alle
drei Entitäten, Re-Import-Idempotenz).
2026-08-24 23:00:46 +02:00

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