targo-backend/prisma/mock-seeds-scripts/09-timesheets.ts
2025-08-29 11:44:04 -04:00

61 lines
2.0 KiB
TypeScript

import { PrismaClient, Prisma } from '@prisma/client';
const prisma = new PrismaClient();
// ====== Config ======
const PREVIOUS_WEEKS = 16; // nombre de semaines à créer (passé)
const INCLUDE_CURRENT = false; // true si tu veux aussi la semaine courante
// Lundi (UTC) de la semaine courante
function mondayOfThisWeekUTC(now = new Date()) {
const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
const day = d.getUTCDay(); // 0=Dim, 1=Lun, ...
const diffToMonday = (day + 6) % 7; // 0 si lundi
d.setUTCDate(d.getUTCDate() - diffToMonday);
d.setUTCHours(0, 0, 0, 0);
return d;
}
function mondayNWeeksBefore(monday: Date, n: number) {
const d = new Date(monday);
d.setUTCDate(d.getUTCDate() - n * 7);
return d;
}
async function main() {
const employees = await prisma.employees.findMany({ select: { id: true } });
if (!employees.length) {
console.warn('Aucun employé — rien à insérer.');
return;
}
// Construit la liste des lundis (1 par semaine)
const mondays: Date[] = [];
const mondayThisWeek = mondayOfThisWeekUTC();
if (INCLUDE_CURRENT) mondays.push(mondayThisWeek);
for (let n = 1; n <= PREVIOUS_WEEKS; n++) {
mondays.push(mondayNWeeksBefore(mondayThisWeek, n));
}
// Prépare les lignes (1 timesheet / employé / semaine)
const rows: Prisma.TimesheetsCreateManyInput[] = [];
for (const e of employees) {
for (const monday of mondays) {
rows.push({
employee_id: e.id,
start_date: monday,
is_approved: Math.random() < 0.3,
} as Prisma.TimesheetsCreateManyInput);
}
}
// Insert en bulk et ignore les doublons si déjà présents
if (rows.length) {
await prisma.timesheets.createMany({ data: rows, skipDuplicates: true });
}
const total = await prisma.timesheets.count();
console.log(`✓ Timesheets: ${total} rows (ajout potentiel: ${rows.length}, ${INCLUDE_CURRENT ? 'courante +' : ''}${PREVIOUS_WEEKS} semaines)`);
}
main().finally(() => prisma.$disconnect());