targo-backend/test/pay-periods-approval.e2e-spec.ts

144 lines
5.0 KiB
TypeScript

// test/pay-periods-approval.e2e-spec.ts
const supertest = require('supertest');
import { INestApplication } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { createApp } from './utils/testing-app';
import { makeEmployee } from './factories/employee.factory';
import { makeTimesheet } from './factories/timesheet.factory';
describe('PayPeriods approval (e2e)', () => {
const BASE = '/pay-periods';
let app: INestApplication;
let prisma: PrismaService;
let periodYear: number;
let periodNumber: number;
let employeeId: number;
let timesheetId: number;
let shiftId: number;
let expenseId: number;
const isoDay = (d: Date) =>
new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate())).toISOString();
const isoTime = (h: number, m = 0) =>
new Date(Date.UTC(1970, 0, 1, h, m, 0)).toISOString();
beforeAll(async () => {
app = await createApp();
prisma = app.get(PrismaService);
// 1) Récupère un pay period existant
const period = await prisma.payPeriods.findFirst({ orderBy: { period_number: 'asc' } });
if (!period) throw new Error('Aucun pay period en DB (seed requis).');
periodYear = period.year;
periodNumber = period.period_number;
// 2) Crée un employé + timesheet (non approuvé)
const empRes = await supertest(app.getHttpServer())
.post('/employees')
.send(makeEmployee());
if (empRes.status !== 201) {
// eslint-disable-next-line no-console
console.warn('Create employee error:', empRes.body || empRes.text);
throw new Error('Impossible de créer un employé pour le test pay-periods.');
}
employeeId = empRes.body.id;
const tsRes = await supertest(app.getHttpServer())
.post('/timesheets')
.send(makeTimesheet(employeeId, { is_approved: false }));
if (tsRes.status !== 201) {
// eslint-disable-next-line no-console
console.warn('Create timesheet error:', tsRes.body || tsRes.text);
throw new Error('Impossible de créer un timesheet pour le test pay-periods.');
}
timesheetId = tsRes.body.id;
// 3) Bank codes
const bcShift = await prisma.bankCodes.findFirst({
where: { categorie: 'SHIFT' },
select: { id: true },
});
if (!bcShift) throw new Error('Aucun bank code SHIFT trouvé.');
const bcExpense = await prisma.bankCodes.findFirst({
where: { categorie: 'EXPENSE' },
select: { id: true },
});
if (!bcExpense) throw new Error('Aucun bank code EXPENSE trouvé.');
// 4) Crée 1 shift + 1 expense DANS la période choisie
const dateISO = isoDay(period.start_date);
const shiftRes = await supertest(app.getHttpServer())
.post('/shifts')
.send({
timesheet_id: timesheetId,
bank_code_id: bcShift.id,
date: dateISO,
start_time: isoTime(9),
end_time: isoTime(17),
description: 'PP approval shift',
});
if (shiftRes.status !== 201) {
// eslint-disable-next-line no-console
console.warn('Create shift error:', shiftRes.body || shiftRes.text);
throw new Error('Création shift échouée.');
}
shiftId = shiftRes.body.id;
const expenseRes = await supertest(app.getHttpServer())
.post('/Expenses') // <- respecte ta casse de route
.send({
timesheet_id: timesheetId,
bank_code_id: bcExpense.id,
date: dateISO,
amount: 42,
description: 'PP approval expense',
is_approved: false,
});
if (expenseRes.status !== 201) {
// eslint-disable-next-line no-console
console.warn('Create expense error:', expenseRes.body || expenseRes.text);
throw new Error('Création expense échouée.');
}
expenseId = expenseRes.body.id;
});
afterAll(async () => {
await app.close();
await prisma.$disconnect();
});
it(`PATCH ${BASE}/:year/:periodNumber/approval → 200 (cascade approval)`, async () => {
const res = await supertest(app.getHttpServer())
.patch(`${BASE}/${periodYear}/${periodNumber}/approval`)
.send(); // aucun body requis par ton contrôleur
expect([200, 204]).toContain(res.status);
if (res.body?.message) {
expect(String(res.body.message)).toContain(`${periodYear}-${periodNumber}`);
}
// Vérifie cascade:
const tsCheck = await supertest(app.getHttpServer()).get(`/timesheets/${timesheetId}`);
expect(tsCheck.status).toBe(200);
expect(tsCheck.body?.is_approved).toBe(true);
const shiftCheck = await supertest(app.getHttpServer()).get(`/shifts/${shiftId}`);
expect(shiftCheck.status).toBe(200);
expect(shiftCheck.body?.is_approved).toBe(true);
const expCheck = await supertest(app.getHttpServer()).get(`/Expenses/${expenseId}`);
expect(expCheck.status).toBe(200);
expect(expCheck.body?.is_approved).toBe(true);
});
it(`PATCH ${BASE}/2099/999/approval → 404 (period not found)`, async () => {
const bad = await supertest(app.getHttpServer())
.patch(`${BASE}/2099/999/approval`)
.send();
expect(bad.status).toBe(404);
});
});