targo-backend/prisma/mock-seeds-scripts/09-timesheets.ts
2025-10-14 13:28:42 -04:00

63 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 = true; // true si tu veux aussi la semaine courante
// Dimanche (UTC) de la semaine courante
function sundayOfThisWeekUTC(now = new Date()) {
// normalise à minuit UTC du jour courant
const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
const day = d.getUTCDay(); // 0=Dim, 1=Lun, ... 6=Sam
// recule jusqu'au dimanche de cette semaine
d.setUTCDate(d.getUTCDate() - day);
d.setUTCHours(0, 0, 0, 0);
return d;
}
function sundayNWeeksBefore(sunday: Date, n: number) {
const d = new Date(sunday);
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 dimanches (1 par semaine)
const sundays: Date[] = [];
const sundayThisWeek = sundayOfThisWeekUTC();
if (INCLUDE_CURRENT) sundays.push(sundayThisWeek);
for (let n = 1; n <= PREVIOUS_WEEKS; n++) {
sundays.push(sundayNWeeksBefore(sundayThisWeek, n));
}
// Prépare les lignes (1 timesheet / employé / semaine)
const rows: Prisma.TimesheetsCreateManyInput[] = [];
for (const e of employees) {
for (const sunday of sundays) {
rows.push({
employee_id: e.id,
start_date: sunday,
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());