fix(migration): commented migration scripts
This commit is contained in:
parent
5b778943a1
commit
41efccac17
|
|
@ -1,272 +1,272 @@
|
|||
// src/scripts/import-employees-from-csv.ts
|
||||
import { PrismaClient, Roles } from '@prisma/client';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
// // src/scripts/import-employees-from-csv.ts
|
||||
// import { PrismaClient, Roles } from '@prisma/client';
|
||||
// import * as fs from 'fs';
|
||||
// import * as path from 'path';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
// const prisma = new PrismaClient();
|
||||
|
||||
// Chemin vers ton CSV employees
|
||||
const CSV_PATH = path.resolve(__dirname, 'data/export_new_employee_table.csv');
|
||||
// // Chemin vers ton CSV employees
|
||||
// const CSV_PATH = path.resolve(__dirname, 'data/export_new_employee_table.csv');
|
||||
|
||||
// Rôles éligibles pour la table Employees
|
||||
const ELIGIBLE_ROLES: Roles[] = [
|
||||
Roles.EMPLOYEE,
|
||||
Roles.SUPERVISOR,
|
||||
Roles.HR,
|
||||
Roles.ACCOUNTING,
|
||||
Roles.ADMIN,
|
||||
];
|
||||
// // Rôles éligibles pour la table Employees
|
||||
// const ELIGIBLE_ROLES: Roles[] = [
|
||||
// Roles.EMPLOYEE,
|
||||
// Roles.SUPERVISOR,
|
||||
// Roles.HR,
|
||||
// Roles.ACCOUNTING,
|
||||
// Roles.ADMIN,
|
||||
// ];
|
||||
|
||||
// Type correspondant EXACT aux colonnes de ton CSV
|
||||
type EmployeeCsvRow = {
|
||||
employee_number: string;
|
||||
email: string;
|
||||
job_title: string;
|
||||
company: string; // sera converti en number
|
||||
is_supervisor: string; // "True"/"False" (ou variantes)
|
||||
onboarding: string; // millis
|
||||
offboarding: string; // millis ou "NULL"
|
||||
};
|
||||
// // Type correspondant EXACT aux colonnes de ton CSV
|
||||
// type EmployeeCsvRow = {
|
||||
// employee_number: string;
|
||||
// email: string;
|
||||
// job_title: string;
|
||||
// company: string; // sera converti en number
|
||||
// is_supervisor: string; // "True"/"False" (ou variantes)
|
||||
// onboarding: string; // millis
|
||||
// offboarding: string; // millis ou "NULL"
|
||||
// };
|
||||
|
||||
// Représentation minimale d'un user
|
||||
type UserSummary = {
|
||||
id: string; // UUID
|
||||
email: string;
|
||||
role: Roles;
|
||||
};
|
||||
// // Représentation minimale d'un user
|
||||
// type UserSummary = {
|
||||
// id: string; // UUID
|
||||
// email: string;
|
||||
// role: Roles;
|
||||
// };
|
||||
|
||||
// ============ Helpers CSV ============
|
||||
// // ============ Helpers CSV ============
|
||||
|
||||
function splitCsvLine(line: string): string[] {
|
||||
const result: string[] = [];
|
||||
let current = '';
|
||||
let inQuotes = false;
|
||||
// function splitCsvLine(line: string): string[] {
|
||||
// const result: string[] = [];
|
||||
// let current = '';
|
||||
// let inQuotes = false;
|
||||
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const char = line[i];
|
||||
// for (let i = 0; i < line.length; i++) {
|
||||
// const char = line[i];
|
||||
|
||||
if (char === '"') {
|
||||
// guillemet échappé ""
|
||||
if (inQuotes && line[i + 1] === '"') {
|
||||
current += '"';
|
||||
i++;
|
||||
} else {
|
||||
inQuotes = !inQuotes;
|
||||
}
|
||||
} else if (char === ',' && !inQuotes) {
|
||||
result.push(current);
|
||||
current = '';
|
||||
} else {
|
||||
current += char;
|
||||
}
|
||||
}
|
||||
// if (char === '"') {
|
||||
// // guillemet échappé ""
|
||||
// if (inQuotes && line[i + 1] === '"') {
|
||||
// current += '"';
|
||||
// i++;
|
||||
// } else {
|
||||
// inQuotes = !inQuotes;
|
||||
// }
|
||||
// } else if (char === ',' && !inQuotes) {
|
||||
// result.push(current);
|
||||
// current = '';
|
||||
// } else {
|
||||
// current += char;
|
||||
// }
|
||||
// }
|
||||
|
||||
result.push(current);
|
||||
return result.map((v) => v.trim());
|
||||
}
|
||||
// result.push(current);
|
||||
// return result.map((v) => v.trim());
|
||||
// }
|
||||
|
||||
// ============ Helpers de parsing ============
|
||||
// // ============ Helpers de parsing ============
|
||||
|
||||
function parseBoolean(value: string): boolean {
|
||||
const v = value.trim().toLowerCase();
|
||||
return v === 'true' || v === '1' || v === 'yes' || v === 'y' || v === 'oui';
|
||||
}
|
||||
// function parseBoolean(value: string): boolean {
|
||||
// const v = value.trim().toLowerCase();
|
||||
// return v === 'true' || v === '1' || v === 'yes' || v === 'y' || v === 'oui';
|
||||
// }
|
||||
|
||||
function parseIntSafe(value: string, fieldName: string): number | null {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed || trimmed.toUpperCase() === 'NULL') return null;
|
||||
// function parseIntSafe(value: string, fieldName: string): number | null {
|
||||
// const trimmed = value.trim();
|
||||
// if (!trimmed || trimmed.toUpperCase() === 'NULL') return null;
|
||||
|
||||
const n = Number.parseInt(trimmed, 10);
|
||||
if (Number.isNaN(n)) {
|
||||
console.warn(` Impossible de parser "${value}" en entier pour le champ ${fieldName}`);
|
||||
return null;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
// const n = Number.parseInt(trimmed, 10);
|
||||
// if (Number.isNaN(n)) {
|
||||
// console.warn(` Impossible de parser "${value}" en entier pour le champ ${fieldName}`);
|
||||
// return null;
|
||||
// }
|
||||
// return n;
|
||||
// }
|
||||
|
||||
function millisToDate(value: string): Date | null {
|
||||
const trimmed = value.trim().toUpperCase();
|
||||
if (!trimmed || trimmed === 'NULL') return null;
|
||||
// function millisToDate(value: string): Date | null {
|
||||
// const trimmed = value.trim().toUpperCase();
|
||||
// if (!trimmed || trimmed === 'NULL') return null;
|
||||
|
||||
const ms = Number(trimmed);
|
||||
if (!Number.isFinite(ms)) {
|
||||
console.warn(` Impossible de parser "${value}" en millis pour une Date`);
|
||||
return null;
|
||||
}
|
||||
// const ms = Number(trimmed);
|
||||
// if (!Number.isFinite(ms)) {
|
||||
// console.warn(` Impossible de parser "${value}" en millis pour une Date`);
|
||||
// return null;
|
||||
// }
|
||||
|
||||
const d = new Date(ms);
|
||||
// On normalise au jour (minuit UTC)
|
||||
const normalized = new Date(Date.UTC(
|
||||
d.getUTCFullYear(),
|
||||
d.getUTCMonth(),
|
||||
d.getUTCDate(),
|
||||
));
|
||||
// const d = new Date(ms);
|
||||
// // On normalise au jour (minuit UTC)
|
||||
// const normalized = new Date(Date.UTC(
|
||||
// d.getUTCFullYear(),
|
||||
// d.getUTCMonth(),
|
||||
// d.getUTCDate(),
|
||||
// ));
|
||||
|
||||
return normalized;
|
||||
}
|
||||
// return normalized;
|
||||
// }
|
||||
|
||||
// ============ MAIN ============
|
||||
// // ============ MAIN ============
|
||||
|
||||
async function main() {
|
||||
// 1. Lecture du CSV
|
||||
const fileContent = fs.readFileSync(CSV_PATH, 'utf-8');
|
||||
// async function main() {
|
||||
// // 1. Lecture du CSV
|
||||
// const fileContent = fs.readFileSync(CSV_PATH, 'utf-8');
|
||||
|
||||
const lines = fileContent
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l.length > 0);
|
||||
// const lines = fileContent
|
||||
// .split(/\r?\n/)
|
||||
// .map((l) => l.trim())
|
||||
// .filter((l) => l.length > 0);
|
||||
|
||||
if (lines.length <= 1) {
|
||||
console.error('CSV vide ou seulement un header');
|
||||
return;
|
||||
}
|
||||
// if (lines.length <= 1) {
|
||||
// console.error('CSV vide ou seulement un header');
|
||||
// return;
|
||||
// }
|
||||
|
||||
const header = splitCsvLine(lines[0]); // ["employee_number","email",...]
|
||||
const dataLines = lines.slice(1);
|
||||
// const header = splitCsvLine(lines[0]); // ["employee_number","email",...]
|
||||
// const dataLines = lines.slice(1);
|
||||
|
||||
const csvRows: EmployeeCsvRow[] = dataLines.map((line) => {
|
||||
const values = splitCsvLine(line);
|
||||
const row: any = {};
|
||||
// const csvRows: EmployeeCsvRow[] = dataLines.map((line) => {
|
||||
// const values = splitCsvLine(line);
|
||||
// const row: any = {};
|
||||
|
||||
header.forEach((col, idx) => {
|
||||
row[col] = values[idx] ?? '';
|
||||
});
|
||||
// header.forEach((col, idx) => {
|
||||
// row[col] = values[idx] ?? '';
|
||||
// });
|
||||
|
||||
return row as EmployeeCsvRow;
|
||||
});
|
||||
// return row as EmployeeCsvRow;
|
||||
// });
|
||||
|
||||
console.log(` ${csvRows.length} lignes trouvées dans le CSV employees`);
|
||||
// console.log(` ${csvRows.length} lignes trouvées dans le CSV employees`);
|
||||
|
||||
// 2. Récupérer tous les emails du CSV
|
||||
const emails = Array.from(
|
||||
new Set(
|
||||
csvRows
|
||||
.map((r) => r.email.trim())
|
||||
.filter((e) => e.length > 0),
|
||||
),
|
||||
);
|
||||
// // 2. Récupérer tous les emails du CSV
|
||||
// const emails = Array.from(
|
||||
// new Set(
|
||||
// csvRows
|
||||
// .map((r) => r.email.trim())
|
||||
// .filter((e) => e.length > 0),
|
||||
// ),
|
||||
// );
|
||||
|
||||
console.log(` ${emails.length} emails uniques trouvés dans le CSV`);
|
||||
// console.log(` ${emails.length} emails uniques trouvés dans le CSV`);
|
||||
|
||||
// 3. Charger les users correspondants avec les bons rôles
|
||||
const users = (await prisma.users.findMany({
|
||||
where: {
|
||||
email: { in: emails },
|
||||
role: { in: ELIGIBLE_ROLES },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
role: true,
|
||||
},
|
||||
})) as UserSummary[];
|
||||
// // 3. Charger les users correspondants avec les bons rôles
|
||||
// const users = (await prisma.users.findMany({
|
||||
// where: {
|
||||
// email: { in: emails },
|
||||
// role: { in: ELIGIBLE_ROLES },
|
||||
// },
|
||||
// select: {
|
||||
// id: true,
|
||||
// email: true,
|
||||
// role: true,
|
||||
// },
|
||||
// })) as UserSummary[];
|
||||
|
||||
console.log(` ${users.length} users éligibles trouvés dans la DB`);
|
||||
// console.log(` ${users.length} users éligibles trouvés dans la DB`);
|
||||
|
||||
// Map email → user
|
||||
const userByEmail = new Map<string, UserSummary>();
|
||||
for (const user of users) {
|
||||
const key = user.email.trim().toLowerCase();
|
||||
userByEmail.set(key, user);
|
||||
}
|
||||
// // Map email → user
|
||||
// const userByEmail = new Map<string, UserSummary>();
|
||||
// for (const user of users) {
|
||||
// const key = user.email.trim().toLowerCase();
|
||||
// userByEmail.set(key, user);
|
||||
// }
|
||||
|
||||
// 4. Construire les données pour employees.createMany
|
||||
const employeesToCreate: {
|
||||
user_id: string;
|
||||
external_payroll_id: number;
|
||||
company_code: number;
|
||||
first_work_day: Date;
|
||||
last_work_day: Date | null;
|
||||
job_title: string | null;
|
||||
is_supervisor: boolean;
|
||||
supervisor_id?: number | null;
|
||||
daily_expected_hours: number;
|
||||
}[] = [];
|
||||
// // 4. Construire les données pour employees.createMany
|
||||
// const employeesToCreate: {
|
||||
// user_id: string;
|
||||
// external_payroll_id: number;
|
||||
// company_code: number;
|
||||
// first_work_day: Date;
|
||||
// last_work_day: Date | null;
|
||||
// job_title: string | null;
|
||||
// is_supervisor: boolean;
|
||||
// supervisor_id?: number | null;
|
||||
// daily_expected_hours: number;
|
||||
// }[] = [];
|
||||
|
||||
const rowsWithoutUser: EmployeeCsvRow[] = [];
|
||||
const rowsWithInvalidNumbers: EmployeeCsvRow[] = [];
|
||||
// const rowsWithoutUser: EmployeeCsvRow[] = [];
|
||||
// const rowsWithInvalidNumbers: EmployeeCsvRow[] = [];
|
||||
|
||||
for (const row of csvRows) {
|
||||
const emailKey = row.email.trim().toLowerCase();
|
||||
const user = userByEmail.get(emailKey);
|
||||
// for (const row of csvRows) {
|
||||
// const emailKey = row.email.trim().toLowerCase();
|
||||
// const user = userByEmail.get(emailKey);
|
||||
|
||||
if (!user) {
|
||||
rowsWithoutUser.push(row);
|
||||
continue;
|
||||
}
|
||||
// if (!user) {
|
||||
// rowsWithoutUser.push(row);
|
||||
// continue;
|
||||
// }
|
||||
|
||||
const external_payroll_id = parseIntSafe(row.employee_number, 'external_payroll_id');
|
||||
const company_code = parseIntSafe(String(row.company), 'company_code');
|
||||
// const external_payroll_id = parseIntSafe(row.employee_number, 'external_payroll_id');
|
||||
// const company_code = parseIntSafe(String(row.company), 'company_code');
|
||||
|
||||
if (external_payroll_id === null || company_code === null) {
|
||||
rowsWithInvalidNumbers.push(row);
|
||||
continue;
|
||||
}
|
||||
// if (external_payroll_id === null || company_code === null) {
|
||||
// rowsWithInvalidNumbers.push(row);
|
||||
// continue;
|
||||
// }
|
||||
|
||||
const first_work_day = millisToDate(row.onboarding);
|
||||
const last_work_day = millisToDate(row.offboarding);
|
||||
const is_supervisor = parseBoolean(row.is_supervisor);
|
||||
const job_title = row.job_title?.trim() || null;
|
||||
// const first_work_day = millisToDate(row.onboarding);
|
||||
// const last_work_day = millisToDate(row.offboarding);
|
||||
// const is_supervisor = parseBoolean(row.is_supervisor);
|
||||
// const job_title = row.job_title?.trim() || null;
|
||||
|
||||
if (!first_work_day) {
|
||||
console.warn(
|
||||
`WARNING: Date d'onboarding invalide pour ${row.email} (employee_number=${row.employee_number})`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
// if (!first_work_day) {
|
||||
// console.warn(
|
||||
// `WARNING: Date d'onboarding invalide pour ${row.email} (employee_number=${row.employee_number})`,
|
||||
// );
|
||||
// continue;
|
||||
// }
|
||||
|
||||
employeesToCreate.push({
|
||||
user_id: user.id,
|
||||
external_payroll_id,
|
||||
company_code,
|
||||
first_work_day,
|
||||
last_work_day,
|
||||
daily_expected_hours: 8,
|
||||
job_title,
|
||||
is_supervisor,
|
||||
supervisor_id: null, // on pourra gérer ça plus tard si tu as les infos
|
||||
});
|
||||
}
|
||||
// employeesToCreate.push({
|
||||
// user_id: user.id,
|
||||
// external_payroll_id,
|
||||
// company_code,
|
||||
// first_work_day,
|
||||
// last_work_day,
|
||||
// daily_expected_hours: 8,
|
||||
// job_title,
|
||||
// is_supervisor,
|
||||
// supervisor_id: null, // on pourra gérer ça plus tard si tu as les infos
|
||||
// });
|
||||
// }
|
||||
|
||||
console.log(` ${employeesToCreate.length} entrées Employees prêtes à être insérées`);
|
||||
// console.log(` ${employeesToCreate.length} entrées Employees prêtes à être insérées`);
|
||||
|
||||
if (rowsWithoutUser.length > 0) {
|
||||
console.warn(` ${rowsWithoutUser.length} lignes CSV sans user correspondant (email / rôle) :`);
|
||||
for (const row of rowsWithoutUser) {
|
||||
console.warn(
|
||||
` - email=${row.email}, employee_number=${row.employee_number}, company=${row.company}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
// if (rowsWithoutUser.length > 0) {
|
||||
// console.warn(` ${rowsWithoutUser.length} lignes CSV sans user correspondant (email / rôle) :`);
|
||||
// for (const row of rowsWithoutUser) {
|
||||
// console.warn(
|
||||
// ` - email=${row.email}, employee_number=${row.employee_number}, company=${row.company}`,
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
|
||||
if (rowsWithInvalidNumbers.length > 0) {
|
||||
console.warn(` ${rowsWithInvalidNumbers.length} lignes CSV avec ids/compagnies invalides :`);
|
||||
for (const row of rowsWithInvalidNumbers) {
|
||||
console.warn(
|
||||
` - email=${row.email}, employee_number="${row.employee_number}", company="${row.company}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
// if (rowsWithInvalidNumbers.length > 0) {
|
||||
// console.warn(` ${rowsWithInvalidNumbers.length} lignes CSV avec ids/compagnies invalides :`);
|
||||
// for (const row of rowsWithInvalidNumbers) {
|
||||
// console.warn(
|
||||
// ` - email=${row.email}, employee_number="${row.employee_number}", company="${row.company}"`,
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
|
||||
if (employeesToCreate.length === 0) {
|
||||
console.warn(' Aucun Employees à créer, arrêt.');
|
||||
return;
|
||||
}
|
||||
// if (employeesToCreate.length === 0) {
|
||||
// console.warn(' Aucun Employees à créer, arrêt.');
|
||||
// return;
|
||||
// }
|
||||
|
||||
// 5. Insert en batch
|
||||
const result = await prisma.employees.createMany({
|
||||
data: employeesToCreate,
|
||||
skipDuplicates: true, // évite les erreurs si tu relances le script
|
||||
});
|
||||
// // 5. Insert en batch
|
||||
// const result = await prisma.employees.createMany({
|
||||
// data: employeesToCreate,
|
||||
// skipDuplicates: true, // évite les erreurs si tu relances le script
|
||||
// });
|
||||
|
||||
console.log(` ${result.count} employees insérés dans la DB`);
|
||||
}
|
||||
// console.log(` ${result.count} employees insérés dans la DB`);
|
||||
// }
|
||||
|
||||
main()
|
||||
.catch((err) => {
|
||||
console.error(' Erreur pendant l’import CSV → Employees', err);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
// main()
|
||||
// .catch((err) => {
|
||||
// console.error(' Erreur pendant l’import CSV → Employees', err);
|
||||
// process.exit(1);
|
||||
// })
|
||||
// .finally(async () => {
|
||||
// await prisma.$disconnect();
|
||||
// });
|
||||
|
|
|
|||
|
|
@ -1,105 +1,105 @@
|
|||
// src/scripts/import-users-from-csv.ts
|
||||
import { PrismaClient, Roles } from '@prisma/client';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
// // src/scripts/import-users-from-csv.ts
|
||||
// import { PrismaClient, Roles } from '@prisma/client';
|
||||
// import * as fs from 'fs';
|
||||
// import * as path from 'path';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
// const prisma = new PrismaClient();
|
||||
|
||||
// ⚙️ Chemin vers ton CSV (à adapter selon où tu le mets)
|
||||
const CSV_PATH = path.resolve(__dirname, 'data/export_employee_table.csv');
|
||||
// // ⚙️ Chemin vers ton CSV (à adapter selon où tu le mets)
|
||||
// const CSV_PATH = path.resolve(__dirname, 'data/export_employee_table.csv');
|
||||
|
||||
// Type aligné sur les colonnes du CSV
|
||||
type CsvUserRow = {
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
phone_number: string;
|
||||
};
|
||||
// // Type aligné sur les colonnes du CSV
|
||||
// type CsvUserRow = {
|
||||
// email: string;
|
||||
// first_name: string;
|
||||
// last_name: string;
|
||||
// phone_number: string;
|
||||
// };
|
||||
|
||||
// Petit parseur de ligne CSV sans dépendance
|
||||
function splitCsvLine(line: string): string[] {
|
||||
const result: string[] = [];
|
||||
let current = '';
|
||||
let inQuotes = false;
|
||||
// // Petit parseur de ligne CSV sans dépendance
|
||||
// function splitCsvLine(line: string): string[] {
|
||||
// const result: string[] = [];
|
||||
// let current = '';
|
||||
// let inQuotes = false;
|
||||
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const char = line[i];
|
||||
// for (let i = 0; i < line.length; i++) {
|
||||
// const char = line[i];
|
||||
|
||||
if (char === '"') {
|
||||
// guillemet échappé ""
|
||||
if (inQuotes && line[i + 1] === '"') {
|
||||
current += '"';
|
||||
i++; // on saute le deuxième
|
||||
} else {
|
||||
inQuotes = !inQuotes;
|
||||
}
|
||||
} else if (char === ',' && !inQuotes) {
|
||||
result.push(current);
|
||||
current = '';
|
||||
} else {
|
||||
current += char;
|
||||
}
|
||||
}
|
||||
// if (char === '"') {
|
||||
// // guillemet échappé ""
|
||||
// if (inQuotes && line[i + 1] === '"') {
|
||||
// current += '"';
|
||||
// i++; // on saute le deuxième
|
||||
// } else {
|
||||
// inQuotes = !inQuotes;
|
||||
// }
|
||||
// } else if (char === ',' && !inQuotes) {
|
||||
// result.push(current);
|
||||
// current = '';
|
||||
// } else {
|
||||
// current += char;
|
||||
// }
|
||||
// }
|
||||
|
||||
result.push(current);
|
||||
return result.map((v) => v.trim());
|
||||
}
|
||||
// result.push(current);
|
||||
// return result.map((v) => v.trim());
|
||||
// }
|
||||
|
||||
async function main() {
|
||||
// 1. Lecture du fichier CSV
|
||||
const fileContent = fs.readFileSync(CSV_PATH, 'utf-8');
|
||||
// async function main() {
|
||||
// // 1. Lecture du fichier CSV
|
||||
// const fileContent = fs.readFileSync(CSV_PATH, 'utf-8');
|
||||
|
||||
const lines = fileContent
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l.length > 0);
|
||||
// const lines = fileContent
|
||||
// .split(/\r?\n/)
|
||||
// .map((l) => l.trim())
|
||||
// .filter((l) => l.length > 0);
|
||||
|
||||
if (lines.length <= 1) {
|
||||
console.error('CSV vide ou seulement un header');
|
||||
return;
|
||||
}
|
||||
// if (lines.length <= 1) {
|
||||
// console.error('CSV vide ou seulement un header');
|
||||
// return;
|
||||
// }
|
||||
|
||||
// 2. Header (noms de colonnes) -> ["email", "first_name", "last_name", "phone_number"]
|
||||
const header = splitCsvLine(lines[0]);
|
||||
const dataLines = lines.slice(1);
|
||||
// // 2. Header (noms de colonnes) -> ["email", "first_name", "last_name", "phone_number"]
|
||||
// const header = splitCsvLine(lines[0]);
|
||||
// const dataLines = lines.slice(1);
|
||||
|
||||
// 3. Conversion de chaque ligne en objet { email, first_name, last_name, phone_number }
|
||||
const records: CsvUserRow[] = dataLines.map((line) => {
|
||||
const values = splitCsvLine(line);
|
||||
const row: any = {};
|
||||
// // 3. Conversion de chaque ligne en objet { email, first_name, last_name, phone_number }
|
||||
// const records: CsvUserRow[] = dataLines.map((line) => {
|
||||
// const values = splitCsvLine(line);
|
||||
// const row: any = {};
|
||||
|
||||
header.forEach((col, idx) => {
|
||||
row[col] = values[idx] ?? '';
|
||||
});
|
||||
// header.forEach((col, idx) => {
|
||||
// row[col] = values[idx] ?? '';
|
||||
// });
|
||||
|
||||
return row as CsvUserRow;
|
||||
});
|
||||
// return row as CsvUserRow;
|
||||
// });
|
||||
|
||||
// 4. Mapping vers le format attendu par Prisma (model Users)
|
||||
const data = records.map((row) => ({
|
||||
email: row.email.trim(),
|
||||
first_name: row.first_name.trim(),
|
||||
last_name: row.last_name.trim(),
|
||||
phone_number: row.phone_number.trim(),
|
||||
role: Roles.EMPLOYEE,
|
||||
// residence: null,
|
||||
}));
|
||||
// // 4. Mapping vers le format attendu par Prisma (model Users)
|
||||
// const data = records.map((row) => ({
|
||||
// email: row.email.trim(),
|
||||
// first_name: row.first_name.trim(),
|
||||
// last_name: row.last_name.trim(),
|
||||
// phone_number: row.phone_number.trim(),
|
||||
// role: Roles.EMPLOYEE,
|
||||
// // residence: null,
|
||||
// }));
|
||||
|
||||
console.log(`➡️ ${data.length} lignes trouvées dans le CSV`);
|
||||
console.log('Exemple importé :', data[0]);
|
||||
// console.log(`➡️ ${data.length} lignes trouvées dans le CSV`);
|
||||
// console.log('Exemple importé :', data[0]);
|
||||
|
||||
const result = await prisma.users.createMany({
|
||||
data,
|
||||
});
|
||||
// const result = await prisma.users.createMany({
|
||||
// data,
|
||||
// });
|
||||
|
||||
console.log(`✅ ${result.count} utilisateurs insérés dans la DB`);
|
||||
}
|
||||
// console.log(`✅ ${result.count} utilisateurs insérés dans la DB`);
|
||||
// }
|
||||
|
||||
main()
|
||||
.catch((err) => {
|
||||
console.error('Erreur pendant l’import CSV → DB', err);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
// main()
|
||||
// .catch((err) => {
|
||||
// console.error('Erreur pendant l’import CSV → DB', err);
|
||||
// process.exit(1);
|
||||
// })
|
||||
// .finally(async () => {
|
||||
// await prisma.$disconnect();
|
||||
// });
|
||||
|
|
|
|||
|
|
@ -1,21 +1,21 @@
|
|||
import { PrismaClient } from "@prisma/client";
|
||||
// import { PrismaClient } from "@prisma/client";
|
||||
|
||||
const prisma = new PrismaClient({});
|
||||
// const prisma = new PrismaClient({});
|
||||
|
||||
export const initializePaidTimeOff = async () => {
|
||||
const list_of_employees = await prisma.employees.findMany();
|
||||
// export const initializePaidTimeOff = async () => {
|
||||
// const list_of_employees = await prisma.employees.findMany();
|
||||
|
||||
console.warn('Start of initialization of paid time off');
|
||||
for (let id = 1; id <= list_of_employees.length + 1; id++) {
|
||||
await prisma.paidTimeOff.create({
|
||||
data: {
|
||||
last_updated: new Date(),
|
||||
banked_hours: 0,
|
||||
employee_id: id,
|
||||
sick_hours: 0,
|
||||
vacation_hours: 0,
|
||||
},
|
||||
});
|
||||
console.log('paid time off initialized for employee ', id);
|
||||
}
|
||||
}
|
||||
// console.warn('Start of initialization of paid time off');
|
||||
// for (let id = 1; id <= list_of_employees.length + 1; id++) {
|
||||
// await prisma.paidTimeOff.create({
|
||||
// data: {
|
||||
// last_updated: new Date(),
|
||||
// banked_hours: 0,
|
||||
// employee_id: id,
|
||||
// sick_hours: 0,
|
||||
// vacation_hours: 0,
|
||||
// },
|
||||
// });
|
||||
// console.log('paid time off initialized for employee ', id);
|
||||
// }
|
||||
// }
|
||||
|
|
@ -1,63 +1,63 @@
|
|||
import { PrismaClient } from "@prisma/client"
|
||||
// import { PrismaClient } from "@prisma/client"
|
||||
|
||||
const prisma = new PrismaClient({});
|
||||
// const prisma = new PrismaClient({});
|
||||
|
||||
const admin_list: number[] = [2, 6, 8, 20, 27, 28, 43, 46, 60];
|
||||
// const admin_list: number[] = [2, 6, 8, 20, 27, 28, 43, 46, 60];
|
||||
|
||||
export const initializePreferences = async () => {
|
||||
console.log('start of preferences and Module Access initialization')
|
||||
for (let id = 1; id <= 61; id++) {
|
||||
const user = await prisma.employees.findUnique({
|
||||
where: { id },
|
||||
select: { user_id: true },
|
||||
});
|
||||
if (!user) {
|
||||
console.log(`user_id for employee ${id} not found`);
|
||||
continue;
|
||||
}
|
||||
console.log(`user_id for employee ${id} found`);
|
||||
// export const initializePreferences = async () => {
|
||||
// console.log('start of preferences and Module Access initialization')
|
||||
// for (let id = 1; id <= 61; id++) {
|
||||
// const user = await prisma.employees.findUnique({
|
||||
// where: { id },
|
||||
// select: { user_id: true },
|
||||
// });
|
||||
// if (!user) {
|
||||
// console.log(`user_id for employee ${id} not found`);
|
||||
// continue;
|
||||
// }
|
||||
// console.log(`user_id for employee ${id} found`);
|
||||
|
||||
await prisma.preferences.create({
|
||||
data: {
|
||||
display_language: 'fr-Fr',
|
||||
is_dark_mode: null,
|
||||
is_employee_list_grid: false,
|
||||
is_lefty_mode: false,
|
||||
is_timesheet_approval_grid: false,
|
||||
notifications: true,
|
||||
user_id: user.user_id,
|
||||
},
|
||||
});
|
||||
console.log(`Preferences for employee ${id} initiated`);
|
||||
// await prisma.preferences.create({
|
||||
// data: {
|
||||
// display_language: 'fr-Fr',
|
||||
// is_dark_mode: null,
|
||||
// is_employee_list_grid: false,
|
||||
// is_lefty_mode: false,
|
||||
// is_timesheet_approval_grid: false,
|
||||
// notifications: true,
|
||||
// user_id: user.user_id,
|
||||
// },
|
||||
// });
|
||||
// console.log(`Preferences for employee ${id} initiated`);
|
||||
|
||||
await prisma.userModuleAccess.create({
|
||||
data: {
|
||||
user_id: user.user_id,
|
||||
dashboard: true,
|
||||
employee_list: true,
|
||||
employee_management: false,
|
||||
personal_profile: true,
|
||||
timesheets: true,
|
||||
timesheets_approval: false,
|
||||
},
|
||||
});
|
||||
console.log(`Module Access for employee ${id} initiated`);
|
||||
// await prisma.userModuleAccess.create({
|
||||
// data: {
|
||||
// user_id: user.user_id,
|
||||
// dashboard: true,
|
||||
// employee_list: true,
|
||||
// employee_management: false,
|
||||
// personal_profile: true,
|
||||
// timesheets: true,
|
||||
// timesheets_approval: false,
|
||||
// },
|
||||
// });
|
||||
// console.log(`Module Access for employee ${id} initiated`);
|
||||
|
||||
if (id in admin_list) {
|
||||
console.log(`employee ${id} is and admin`)
|
||||
await prisma.userModuleAccess.update({
|
||||
where: { user_id: user.user_id },
|
||||
data: {
|
||||
dashboard: true,
|
||||
employee_list: true,
|
||||
employee_management: true,
|
||||
personal_profile: true,
|
||||
timesheets: true,
|
||||
timesheets_approval: true,
|
||||
},
|
||||
});
|
||||
console.log(`Module Access for employee ${id} updated`);
|
||||
}
|
||||
}
|
||||
}
|
||||
// if (id in admin_list) {
|
||||
// console.log(`employee ${id} is and admin`)
|
||||
// await prisma.userModuleAccess.update({
|
||||
// where: { user_id: user.user_id },
|
||||
// data: {
|
||||
// dashboard: true,
|
||||
// employee_list: true,
|
||||
// employee_management: true,
|
||||
// personal_profile: true,
|
||||
// timesheets: true,
|
||||
// timesheets_approval: true,
|
||||
// },
|
||||
// });
|
||||
// console.log(`Module Access for employee ${id} updated`);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
|
|
|
|||
|
|
@ -1,167 +1,167 @@
|
|||
import { PrismaClient as Prisma } from "@prisma/client";
|
||||
import { PrismaClient as PrismaLegacy } from "@prisma/client-legacy"
|
||||
import { toDateFromString, toHHmmFromDate, toStringFromDate } from "src/common/utils/date-utils";
|
||||
// import { PrismaClient as Prisma } from "@prisma/client";
|
||||
// import { PrismaClient as PrismaLegacy } from "@prisma/client-legacy"
|
||||
// import { toDateFromString, toHHmmFromDate, toStringFromDate } from "src/common/utils/date-utils";
|
||||
|
||||
const prisma_legacy = new PrismaLegacy({});
|
||||
const prisma = new Prisma({});
|
||||
// const prisma_legacy = new PrismaLegacy({});
|
||||
// const prisma = new Prisma({});
|
||||
|
||||
type NewEmployee = {
|
||||
id: number;
|
||||
company_code: number;
|
||||
external_payroll_id: number;
|
||||
}
|
||||
// type NewEmployee = {
|
||||
// id: number;
|
||||
// company_code: number;
|
||||
// external_payroll_id: number;
|
||||
// }
|
||||
|
||||
type OldExpense = {
|
||||
time_sheet_id: string | null;
|
||||
date: string | null;
|
||||
code: string | null;
|
||||
description: string | null;
|
||||
value: number | null;
|
||||
status: boolean | null;
|
||||
}
|
||||
// type OldExpense = {
|
||||
// time_sheet_id: string | null;
|
||||
// date: string | null;
|
||||
// code: string | null;
|
||||
// description: string | null;
|
||||
// value: number | null;
|
||||
// status: boolean | null;
|
||||
// }
|
||||
|
||||
export const extractOldExpenses = async () => {
|
||||
const list_of_employees = await prisma.employees.findMany();
|
||||
for (let id = 1; id <= list_of_employees.length+1; id++) {
|
||||
// export const extractOldExpenses = async () => {
|
||||
// const list_of_employees = await prisma.employees.findMany();
|
||||
// for (let id = 1; id <= list_of_employees.length+1; id++) {
|
||||
|
||||
console.log(`Start of Expense migration ***************************************************************`);
|
||||
// console.log(`Start of Expense migration ***************************************************************`);
|
||||
|
||||
const new_employee = await findOneNewEmployee(id);
|
||||
console.log(`Employee ${id} found in new DB`);
|
||||
// const new_employee = await findOneNewEmployee(id);
|
||||
// console.log(`Employee ${id} found in new DB`);
|
||||
|
||||
const new_timesheets = await findManyNewTimesheets(new_employee.id);
|
||||
console.log(`New Timesheets found for employee ${id}`);
|
||||
// const new_timesheets = await findManyNewTimesheets(new_employee.id);
|
||||
// console.log(`New Timesheets found for employee ${id}`);
|
||||
|
||||
const old_employee_id = await findOneOldEmployee(new_employee);
|
||||
console.log(`Employee ${new_employee.id} found in old DB`);
|
||||
// const old_employee_id = await findOneOldEmployee(new_employee);
|
||||
// console.log(`Employee ${new_employee.id} found in old DB`);
|
||||
|
||||
const old_timesheets = await findManyOldTimesheets(old_employee_id);
|
||||
console.log(`Timesheets for employee ${old_employee_id}/${new_employee.id} found in old DB`);
|
||||
// const old_timesheets = await findManyOldTimesheets(old_employee_id);
|
||||
// console.log(`Timesheets for employee ${old_employee_id}/${new_employee.id} found in old DB`);
|
||||
|
||||
console.log('Start of Expense creation*****************************************************************');
|
||||
for (const old_timesheet of old_timesheets) {
|
||||
if (!old_timesheet.start_date) continue;
|
||||
const new_timesheet = new_timesheets.find((ts) => ts.start_date.getTime() === old_timesheet.start_date!.getTime());
|
||||
if (!new_timesheet) {
|
||||
console.warn(`No new timesheet matching legacy timesheet ${old_timesheet.id}`);
|
||||
continue;
|
||||
}
|
||||
const old_expenses = await prisma_legacy.expenses.findMany({
|
||||
where: { time_sheet_id: old_timesheet.id },
|
||||
select: {
|
||||
time_sheet_id: true,
|
||||
date: true,
|
||||
code: true,
|
||||
description: true,
|
||||
value: true,
|
||||
status: true,
|
||||
// console.log('Start of Expense creation*****************************************************************');
|
||||
// for (const old_timesheet of old_timesheets) {
|
||||
// if (!old_timesheet.start_date) continue;
|
||||
// const new_timesheet = new_timesheets.find((ts) => ts.start_date.getTime() === old_timesheet.start_date!.getTime());
|
||||
// if (!new_timesheet) {
|
||||
// console.warn(`No new timesheet matching legacy timesheet ${old_timesheet.id}`);
|
||||
// continue;
|
||||
// }
|
||||
// const old_expenses = await prisma_legacy.expenses.findMany({
|
||||
// where: { time_sheet_id: old_timesheet.id },
|
||||
// select: {
|
||||
// time_sheet_id: true,
|
||||
// date: true,
|
||||
// code: true,
|
||||
// description: true,
|
||||
// value: true,
|
||||
// status: true,
|
||||
|
||||
},
|
||||
});
|
||||
await createManyNewExpenses(new_timesheet.id, old_expenses);
|
||||
}
|
||||
// },
|
||||
// });
|
||||
// await createManyNewExpenses(new_timesheet.id, old_expenses);
|
||||
// }
|
||||
|
||||
}
|
||||
await prisma_legacy.$disconnect();
|
||||
await prisma.$disconnect();
|
||||
console.log('finished migrating expenses ***************************');
|
||||
}
|
||||
// }
|
||||
// await prisma_legacy.$disconnect();
|
||||
// await prisma.$disconnect();
|
||||
// console.log('finished migrating expenses ***************************');
|
||||
// }
|
||||
|
||||
const findOneNewEmployee = async (id: number): Promise<NewEmployee> => {
|
||||
const new_employee = await prisma.employees.findUnique({
|
||||
where: { id: id },
|
||||
select: {
|
||||
id: true,
|
||||
company_code: true,
|
||||
external_payroll_id: true,
|
||||
},
|
||||
});
|
||||
if (!new_employee) throw new Error(`New Employee with id ${id} not found`)
|
||||
return new_employee;
|
||||
}
|
||||
// const findOneNewEmployee = async (id: number): Promise<NewEmployee> => {
|
||||
// const new_employee = await prisma.employees.findUnique({
|
||||
// where: { id: id },
|
||||
// select: {
|
||||
// id: true,
|
||||
// company_code: true,
|
||||
// external_payroll_id: true,
|
||||
// },
|
||||
// });
|
||||
// if (!new_employee) throw new Error(`New Employee with id ${id} not found`)
|
||||
// return new_employee;
|
||||
// }
|
||||
|
||||
const findOneOldEmployee = async (new_employee: NewEmployee): Promise<string> => {
|
||||
const old_employee = await prisma_legacy.employees.findFirst({
|
||||
where: {
|
||||
company: new_employee.company_code,
|
||||
employee_number: new_employee.external_payroll_id.toString(),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
if (!old_employee) throw new Error(`Old Employee not found`);
|
||||
return old_employee.id;
|
||||
}
|
||||
// const findOneOldEmployee = async (new_employee: NewEmployee): Promise<string> => {
|
||||
// const old_employee = await prisma_legacy.employees.findFirst({
|
||||
// where: {
|
||||
// company: new_employee.company_code,
|
||||
// employee_number: new_employee.external_payroll_id.toString(),
|
||||
// },
|
||||
// select: {
|
||||
// id: true,
|
||||
// },
|
||||
// });
|
||||
// if (!old_employee) throw new Error(`Old Employee not found`);
|
||||
// return old_employee.id;
|
||||
// }
|
||||
|
||||
const findManyOldTimesheets = async (old_employee_id: string) => {
|
||||
const old_timesheets = await prisma_legacy.time_sheets.findMany({
|
||||
where: { employee_id: old_employee_id },
|
||||
select: { id: true, start_date: true, status: true }
|
||||
});
|
||||
return old_timesheets;
|
||||
}
|
||||
// const findManyOldTimesheets = async (old_employee_id: string) => {
|
||||
// const old_timesheets = await prisma_legacy.time_sheets.findMany({
|
||||
// where: { employee_id: old_employee_id },
|
||||
// select: { id: true, start_date: true, status: true }
|
||||
// });
|
||||
// return old_timesheets;
|
||||
// }
|
||||
|
||||
const findManyNewTimesheets = async (employee_id: number) => {
|
||||
const timesheets = await prisma.timesheets.findMany({
|
||||
where: { employee_id: employee_id },
|
||||
select: { id: true, start_date: true }
|
||||
})
|
||||
return timesheets;
|
||||
}
|
||||
// const findManyNewTimesheets = async (employee_id: number) => {
|
||||
// const timesheets = await prisma.timesheets.findMany({
|
||||
// where: { employee_id: employee_id },
|
||||
// select: { id: true, start_date: true }
|
||||
// })
|
||||
// return timesheets;
|
||||
// }
|
||||
|
||||
const createManyNewExpenses = async (timesheet_id: number, old_expenses: OldExpense[]) => {
|
||||
for (const old_expense of old_expenses) {
|
||||
let mileage: number = 0;
|
||||
let amount: number = old_expense.value ?? 0;
|
||||
if (old_expense.code === 'G503') {
|
||||
mileage = old_expense.value!;
|
||||
amount = mileage * 0.72;
|
||||
}
|
||||
if (mileage < 0 || amount < 0) {
|
||||
console.warn(`expense of value less than '0' found`)
|
||||
continue;
|
||||
}
|
||||
// const createManyNewExpenses = async (timesheet_id: number, old_expenses: OldExpense[]) => {
|
||||
// for (const old_expense of old_expenses) {
|
||||
// let mileage: number = 0;
|
||||
// let amount: number = old_expense.value ?? 0;
|
||||
// if (old_expense.code === 'G503') {
|
||||
// mileage = old_expense.value!;
|
||||
// amount = mileage * 0.72;
|
||||
// }
|
||||
// if (mileage < 0 || amount < 0) {
|
||||
// console.warn(`expense of value less than '0' found`)
|
||||
// continue;
|
||||
// }
|
||||
|
||||
if (old_expense.date == null) {
|
||||
console.warn(`Expense date invalid ${old_expense.date}`);
|
||||
continue;
|
||||
}
|
||||
const date = toDateFromString(old_expense.date);
|
||||
// if (old_expense.date == null) {
|
||||
// console.warn(`Expense date invalid ${old_expense.date}`);
|
||||
// continue;
|
||||
// }
|
||||
// const date = toDateFromString(old_expense.date);
|
||||
|
||||
if (old_expense.status == null) {
|
||||
console.warn(`status null for legacy expense ${old_expense}`);
|
||||
continue;
|
||||
}
|
||||
// if (old_expense.status == null) {
|
||||
// console.warn(`status null for legacy expense ${old_expense}`);
|
||||
// continue;
|
||||
// }
|
||||
|
||||
if (old_expense.code == null) {
|
||||
console.warn(`Code null for legacy expense ${old_expense.code}`);
|
||||
continue;
|
||||
}
|
||||
const bank_code_id = await findBankCodeIdUsingOldCode(old_expense.code);
|
||||
// if (old_expense.code == null) {
|
||||
// console.warn(`Code null for legacy expense ${old_expense.code}`);
|
||||
// continue;
|
||||
// }
|
||||
// const bank_code_id = await findBankCodeIdUsingOldCode(old_expense.code);
|
||||
|
||||
await prisma.expenses.upsert({
|
||||
where: { unique_ts_id_date_amount_mileage: { timesheet_id: timesheet_id, date, amount, mileage } },
|
||||
update: {
|
||||
is_approved: old_expense.status,
|
||||
},
|
||||
create: {
|
||||
date: date,
|
||||
comment: old_expense.description ?? '',
|
||||
timesheet_id: timesheet_id,
|
||||
bank_code_id: bank_code_id,
|
||||
amount: amount,
|
||||
mileage: mileage,
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
// await prisma.expenses.upsert({
|
||||
// where: { unique_ts_id_date_amount_mileage: { timesheet_id: timesheet_id, date, amount, mileage } },
|
||||
// update: {
|
||||
// is_approved: old_expense.status,
|
||||
// },
|
||||
// create: {
|
||||
// date: date,
|
||||
// comment: old_expense.description ?? '',
|
||||
// timesheet_id: timesheet_id,
|
||||
// bank_code_id: bank_code_id,
|
||||
// amount: amount,
|
||||
// mileage: mileage,
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
|
||||
const findBankCodeIdUsingOldCode = async (code: string): Promise<number> => {
|
||||
const bank_code = await prisma.bankCodes.findFirst({
|
||||
where: { bank_code: code },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!bank_code) throw new Error(`Bank_code_id not found for Code ${code}`)
|
||||
return bank_code.id;
|
||||
}
|
||||
// const findBankCodeIdUsingOldCode = async (code: string): Promise<number> => {
|
||||
// const bank_code = await prisma.bankCodes.findFirst({
|
||||
// where: { bank_code: code },
|
||||
// select: { id: true },
|
||||
// });
|
||||
// if (!bank_code) throw new Error(`Bank_code_id not found for Code ${code}`)
|
||||
// return bank_code.id;
|
||||
// }
|
||||
|
|
@ -1,216 +1,216 @@
|
|||
import { PrismaClient as PrismaNew } from "@prisma/client";
|
||||
import { PrismaClient as PrismaLegacy } from "@prisma/client-legacy"
|
||||
// import { PrismaClient as PrismaNew } from "@prisma/client";
|
||||
// import { PrismaClient as PrismaLegacy } from "@prisma/client-legacy"
|
||||
|
||||
const prisma_legacy = new PrismaLegacy({});
|
||||
const prisma = new PrismaNew({});
|
||||
// const prisma_legacy = new PrismaLegacy({});
|
||||
// const prisma = new PrismaNew({});
|
||||
|
||||
type NewEmployee = {
|
||||
id: number;
|
||||
company_code: number;
|
||||
external_payroll_id: number;
|
||||
}
|
||||
// type NewEmployee = {
|
||||
// id: number;
|
||||
// company_code: number;
|
||||
// external_payroll_id: number;
|
||||
// }
|
||||
|
||||
type OldShifts = {
|
||||
time_sheet_id: string | null;
|
||||
code: string | null;
|
||||
type: string | null;
|
||||
date: Date | null;
|
||||
start_time: bigint | null;
|
||||
end_time: bigint | null;
|
||||
comment: string | null;
|
||||
status: boolean | null;
|
||||
}
|
||||
// type OldShifts = {
|
||||
// time_sheet_id: string | null;
|
||||
// code: string | null;
|
||||
// type: string | null;
|
||||
// date: Date | null;
|
||||
// start_time: bigint | null;
|
||||
// end_time: bigint | null;
|
||||
// comment: string | null;
|
||||
// status: boolean | null;
|
||||
// }
|
||||
|
||||
export const extractOldShifts = async () => {
|
||||
const list_of_employees = await prisma.employees.findMany();
|
||||
// export const extractOldShifts = async () => {
|
||||
// const list_of_employees = await prisma.employees.findMany();
|
||||
|
||||
for (let id = 1; id <= list_of_employees.length + 1; id++) {
|
||||
console.log(`Start of shift migration ***************************************************************`);
|
||||
const new_employee = await findOneNewEmployee(id);
|
||||
console.log(`Employee ${id} found in new DB`);
|
||||
// for (let id = 1; id <= list_of_employees.length + 1; id++) {
|
||||
// console.log(`Start of shift migration ***************************************************************`);
|
||||
// const new_employee = await findOneNewEmployee(id);
|
||||
// console.log(`Employee ${id} found in new DB`);
|
||||
|
||||
const new_timesheets = await findManyNewTimesheets(new_employee.id);
|
||||
console.log(new_timesheets.length, `new Timesheets found for employee ${id}`);
|
||||
// const new_timesheets = await findManyNewTimesheets(new_employee.id);
|
||||
// console.log(new_timesheets.length, `new Timesheets found for employee ${id}`);
|
||||
|
||||
const old_employee_id = await findOneOldEmployee(new_employee);
|
||||
console.log(`Employee ${new_employee.id} found in old DB`);
|
||||
// const old_employee_id = await findOneOldEmployee(new_employee);
|
||||
// console.log(`Employee ${new_employee.id} found in old DB`);
|
||||
|
||||
const old_timesheets = await findManyOldTimesheets(old_employee_id);
|
||||
console.log(old_timesheets.length, `old timesheets for employee ${new_employee.id} found in old DB`);
|
||||
// const old_timesheets = await findManyOldTimesheets(old_employee_id);
|
||||
// console.log(old_timesheets.length, `old timesheets for employee ${new_employee.id} found in old DB`);
|
||||
|
||||
for (const old_timesheet of old_timesheets) {
|
||||
if (!old_timesheet.start_date) {
|
||||
console.warn('Start_date of the old_timesheet ', old_timesheet.id, 'invalid, start_date: ', old_timesheet.start_date);
|
||||
continue;
|
||||
}
|
||||
const new_timesheet = new_timesheets.find((ts) => ts.start_date.getTime() === old_timesheet.start_date!.getTime());
|
||||
if (!new_timesheet) {
|
||||
console.warn(`No new timesheet ${new_timesheet} matching legacy timesheet ${old_timesheet.id}`);
|
||||
continue;
|
||||
}
|
||||
const old_shifts = await prisma_legacy.shifts.findMany({
|
||||
where: { time_sheet_id: old_timesheet.id },
|
||||
select: {
|
||||
time_sheet_id: true,
|
||||
code: true,
|
||||
type: true,
|
||||
date: true,
|
||||
start_time: true,
|
||||
end_time: true,
|
||||
comment: true,
|
||||
status: true,
|
||||
},
|
||||
});
|
||||
await createManyNewShifts(new_timesheet.id, old_shifts);
|
||||
}
|
||||
}
|
||||
await prisma_legacy.$disconnect();
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
// for (const old_timesheet of old_timesheets) {
|
||||
// if (!old_timesheet.start_date) {
|
||||
// console.warn('Start_date of the old_timesheet ', old_timesheet.id, 'invalid, start_date: ', old_timesheet.start_date);
|
||||
// continue;
|
||||
// }
|
||||
// const new_timesheet = new_timesheets.find((ts) => ts.start_date.getTime() === old_timesheet.start_date!.getTime());
|
||||
// if (!new_timesheet) {
|
||||
// console.warn(`No new timesheet ${new_timesheet} matching legacy timesheet ${old_timesheet.id}`);
|
||||
// continue;
|
||||
// }
|
||||
// const old_shifts = await prisma_legacy.shifts.findMany({
|
||||
// where: { time_sheet_id: old_timesheet.id },
|
||||
// select: {
|
||||
// time_sheet_id: true,
|
||||
// code: true,
|
||||
// type: true,
|
||||
// date: true,
|
||||
// start_time: true,
|
||||
// end_time: true,
|
||||
// comment: true,
|
||||
// status: true,
|
||||
// },
|
||||
// });
|
||||
// await createManyNewShifts(new_timesheet.id, old_shifts);
|
||||
// }
|
||||
// }
|
||||
// await prisma_legacy.$disconnect();
|
||||
// await prisma.$disconnect();
|
||||
// }
|
||||
|
||||
const findOneNewEmployee = async (id: number): Promise<NewEmployee> => {
|
||||
const new_employee = await prisma.employees.findUnique({
|
||||
where: { id: id },
|
||||
select: {
|
||||
id: true,
|
||||
company_code: true,
|
||||
external_payroll_id: true,
|
||||
},
|
||||
});
|
||||
if (!new_employee) throw new Error(`New Employee with id ${id} not found`)
|
||||
return new_employee;
|
||||
}
|
||||
// const findOneNewEmployee = async (id: number): Promise<NewEmployee> => {
|
||||
// const new_employee = await prisma.employees.findUnique({
|
||||
// where: { id: id },
|
||||
// select: {
|
||||
// id: true,
|
||||
// company_code: true,
|
||||
// external_payroll_id: true,
|
||||
// },
|
||||
// });
|
||||
// if (!new_employee) throw new Error(`New Employee with id ${id} not found`)
|
||||
// return new_employee;
|
||||
// }
|
||||
|
||||
const findOneOldEmployee = async (new_employee: NewEmployee): Promise<string> => {
|
||||
const old_employee = await prisma_legacy.employees.findFirst({
|
||||
where: {
|
||||
company: new_employee.company_code,
|
||||
employee_number: new_employee.external_payroll_id.toString(),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
if (!old_employee) throw new Error(`Old Employee not found`);
|
||||
return old_employee.id;
|
||||
}
|
||||
// const findOneOldEmployee = async (new_employee: NewEmployee): Promise<string> => {
|
||||
// const old_employee = await prisma_legacy.employees.findFirst({
|
||||
// where: {
|
||||
// company: new_employee.company_code,
|
||||
// employee_number: new_employee.external_payroll_id.toString(),
|
||||
// },
|
||||
// select: {
|
||||
// id: true,
|
||||
// },
|
||||
// });
|
||||
// if (!old_employee) throw new Error(`Old Employee not found`);
|
||||
// return old_employee.id;
|
||||
// }
|
||||
|
||||
const findManyOldTimesheets = async (old_employee_id: string) => {
|
||||
const old_timesheets = await prisma_legacy.time_sheets.findMany({
|
||||
where: { employee_id: old_employee_id },
|
||||
select: { id: true, start_date: true, status: true }
|
||||
});
|
||||
return old_timesheets;
|
||||
}
|
||||
// const findManyOldTimesheets = async (old_employee_id: string) => {
|
||||
// const old_timesheets = await prisma_legacy.time_sheets.findMany({
|
||||
// where: { employee_id: old_employee_id },
|
||||
// select: { id: true, start_date: true, status: true }
|
||||
// });
|
||||
// return old_timesheets;
|
||||
// }
|
||||
|
||||
const findManyNewTimesheets = async (employee_id: number) => {
|
||||
const timesheets = await prisma.timesheets.findMany({
|
||||
where: { employee_id: employee_id },
|
||||
select: { id: true, start_date: true }
|
||||
})
|
||||
return timesheets;
|
||||
}
|
||||
// const findManyNewTimesheets = async (employee_id: number) => {
|
||||
// const timesheets = await prisma.timesheets.findMany({
|
||||
// where: { employee_id: employee_id },
|
||||
// select: { id: true, start_date: true }
|
||||
// })
|
||||
// return timesheets;
|
||||
// }
|
||||
|
||||
const createManyNewShifts = async (timesheet_id: number, old_shifts: OldShifts[]) => {
|
||||
let shifts_count = 0;
|
||||
for (const old_shift of old_shifts) {
|
||||
let is_remote = true;
|
||||
// const createManyNewShifts = async (timesheet_id: number, old_shifts: OldShifts[]) => {
|
||||
// let shifts_count = 0;
|
||||
// for (const old_shift of old_shifts) {
|
||||
// let is_remote = true;
|
||||
|
||||
const start = toHHmmfromLegacyTimestamp(old_shift.start_time);
|
||||
if (old_shift.start_time == null || !start) {
|
||||
console.warn(`Shift start invalid ${old_shift.start_time}`);
|
||||
continue;
|
||||
}
|
||||
// const start = toHHmmfromLegacyTimestamp(old_shift.start_time);
|
||||
// if (old_shift.start_time == null || !start) {
|
||||
// console.warn(`Shift start invalid ${old_shift.start_time}`);
|
||||
// continue;
|
||||
// }
|
||||
|
||||
const end = toHHmmfromLegacyTimestamp(old_shift.end_time);
|
||||
if (old_shift.end_time == null || !end) {
|
||||
console.warn(`Shift end invalid ${old_shift.end_time}`);
|
||||
continue;
|
||||
}
|
||||
// const end = toHHmmfromLegacyTimestamp(old_shift.end_time);
|
||||
// if (old_shift.end_time == null || !end) {
|
||||
// console.warn(`Shift end invalid ${old_shift.end_time}`);
|
||||
// continue;
|
||||
// }
|
||||
|
||||
if (old_shift.date == null) {
|
||||
console.warn(`Shift date invalid ${old_shift.date}`);
|
||||
continue;
|
||||
}
|
||||
// if (old_shift.date == null) {
|
||||
// console.warn(`Shift date invalid ${old_shift.date}`);
|
||||
// continue;
|
||||
// }
|
||||
|
||||
if (old_shift.status == null) {
|
||||
console.warn(`status null for legacy shift ${old_shift}`);
|
||||
continue;
|
||||
}
|
||||
if (old_shift.type == null) {
|
||||
console.warn(`type null for legacy shift ${old_shift.type}`);
|
||||
continue;
|
||||
}
|
||||
// if (old_shift.status == null) {
|
||||
// console.warn(`status null for legacy shift ${old_shift}`);
|
||||
// continue;
|
||||
// }
|
||||
// if (old_shift.type == null) {
|
||||
// console.warn(`type null for legacy shift ${old_shift.type}`);
|
||||
// continue;
|
||||
// }
|
||||
|
||||
if (old_shift.type === 'office') {
|
||||
is_remote = false;
|
||||
}
|
||||
// if (old_shift.type === 'office') {
|
||||
// is_remote = false;
|
||||
// }
|
||||
|
||||
if (old_shift.code == null) {
|
||||
console.warn(`Code null for legacy shift ${old_shift.code}`);
|
||||
continue;
|
||||
}
|
||||
const bank_code_id = await findBankCodeIdUsingOldCode(old_shift.code);
|
||||
try {
|
||||
// if (old_shift.code == null) {
|
||||
// console.warn(`Code null for legacy shift ${old_shift.code}`);
|
||||
// continue;
|
||||
// }
|
||||
// const bank_code_id = await findBankCodeIdUsingOldCode(old_shift.code);
|
||||
// try {
|
||||
|
||||
await prisma.shifts.create({
|
||||
// where: { unique_ts_id_date_start_time: {
|
||||
// timesheet_id,
|
||||
// await prisma.shifts.create({
|
||||
// // where: { unique_ts_id_date_start_time: {
|
||||
// // timesheet_id,
|
||||
// // date: old_shift.date,
|
||||
// // start_time: toDateFromHHmm(start) }},
|
||||
// // update: {
|
||||
// // start_time: toDateFromHHmm(start),
|
||||
// // end_time: toDateFromHHmm(end),
|
||||
// // comment: old_shift.comment,
|
||||
// // is_approved: old_shift.status,
|
||||
// // is_remote: is_remote,
|
||||
// // bank_code_id: bank_code_id,
|
||||
// // },
|
||||
// data: {
|
||||
// date: old_shift.date,
|
||||
// start_time: toDateFromHHmm(start) }},
|
||||
// update: {
|
||||
// start_time: toDateFromHHmm(start),
|
||||
// end_time: toDateFromHHmm(end),
|
||||
// comment: old_shift.comment,
|
||||
// is_approved: old_shift.status,
|
||||
// is_remote: is_remote,
|
||||
// timesheet_id: timesheet_id,
|
||||
// bank_code_id: bank_code_id,
|
||||
// },
|
||||
data: {
|
||||
date: old_shift.date,
|
||||
start_time: toDateFromHHmm(start),
|
||||
end_time: toDateFromHHmm(end),
|
||||
comment: old_shift.comment,
|
||||
is_approved: old_shift.status,
|
||||
is_remote: is_remote,
|
||||
timesheet_id: timesheet_id,
|
||||
bank_code_id: bank_code_id,
|
||||
},
|
||||
});
|
||||
shifts_count++;
|
||||
} catch (error) {
|
||||
console.log('An error occured during shifts creation', error);
|
||||
}
|
||||
// });
|
||||
// shifts_count++;
|
||||
// } catch (error) {
|
||||
// console.log('An error occured during shifts creation', error);
|
||||
// }
|
||||
|
||||
}
|
||||
console.warn(shifts_count, ' new shifts created');
|
||||
}
|
||||
// }
|
||||
// console.warn(shifts_count, ' new shifts created');
|
||||
// }
|
||||
|
||||
const toHHmmfromLegacyTimestamp = (value: bigint | null): string | null => {
|
||||
if (value == null) return null;
|
||||
const date = new Date(Number(value));
|
||||
const hh = String(date.getHours()).padStart(2, '0');
|
||||
const mm = String(date.getMinutes()).padStart(2, '0');
|
||||
return `${hh}:${mm}`;
|
||||
}
|
||||
// const toHHmmfromLegacyTimestamp = (value: bigint | null): string | null => {
|
||||
// if (value == null) return null;
|
||||
// const date = new Date(Number(value));
|
||||
// const hh = String(date.getHours()).padStart(2, '0');
|
||||
// const mm = String(date.getMinutes()).padStart(2, '0');
|
||||
// return `${hh}:${mm}`;
|
||||
// }
|
||||
|
||||
const toDateFromHHmm = (hhmm: string): Date => {
|
||||
const [hh, mm] = hhmm.split(':');
|
||||
const hours = Number(hh);
|
||||
const minutes = Number(mm);
|
||||
return new Date(Date.UTC(1970, 0, 1, hours, minutes, 0, 0));
|
||||
}
|
||||
// const toDateFromHHmm = (hhmm: string): Date => {
|
||||
// const [hh, mm] = hhmm.split(':');
|
||||
// const hours = Number(hh);
|
||||
// const minutes = Number(mm);
|
||||
// return new Date(Date.UTC(1970, 0, 1, hours, minutes, 0, 0));
|
||||
// }
|
||||
|
||||
const findBankCodeIdUsingOldCode = async (code: string): Promise<number> => {
|
||||
if (code === 'G700') {
|
||||
code = 'G104';
|
||||
} else if (code === 'G140') {
|
||||
code = 'G56'
|
||||
}
|
||||
const bank_code = await prisma.bankCodes.findFirst({
|
||||
where: { bank_code: code },
|
||||
select: { id: true, bank_code: true },
|
||||
});
|
||||
if (!bank_code) throw new Error(`Bank_code_id not found for Code ${code}`)
|
||||
return bank_code.id;
|
||||
}
|
||||
// const findBankCodeIdUsingOldCode = async (code: string): Promise<number> => {
|
||||
// if (code === 'G700') {
|
||||
// code = 'G104';
|
||||
// } else if (code === 'G140') {
|
||||
// code = 'G56'
|
||||
// }
|
||||
// const bank_code = await prisma.bankCodes.findFirst({
|
||||
// where: { bank_code: code },
|
||||
// select: { id: true, bank_code: true },
|
||||
// });
|
||||
// if (!bank_code) throw new Error(`Bank_code_id not found for Code ${code}`)
|
||||
// return bank_code.id;
|
||||
// }
|
||||
|
|
|
|||
|
|
@ -1,118 +1,118 @@
|
|||
import { PrismaClient as Prisma } from "@prisma/client";
|
||||
import { PrismaClient as PrismaLegacy } from "@prisma/client-legacy"
|
||||
import { toStringFromDate } from "src/common/utils/date-utils";
|
||||
// import { PrismaClient as Prisma } from "@prisma/client";
|
||||
// import { PrismaClient as PrismaLegacy } from "@prisma/client-legacy"
|
||||
// import { toStringFromDate } from "src/common/utils/date-utils";
|
||||
|
||||
type NewEmployee = {
|
||||
id: number;
|
||||
company_code: number;
|
||||
external_payroll_id: number;
|
||||
}
|
||||
// type NewEmployee = {
|
||||
// id: number;
|
||||
// company_code: number;
|
||||
// external_payroll_id: number;
|
||||
// }
|
||||
|
||||
type OldTimesheets = {
|
||||
id: string;
|
||||
start_date: Date | null;
|
||||
status: boolean | null;
|
||||
}
|
||||
// type OldTimesheets = {
|
||||
// id: string;
|
||||
// start_date: Date | null;
|
||||
// status: boolean | null;
|
||||
// }
|
||||
|
||||
const prisma_legacy = new PrismaLegacy({});
|
||||
const prisma_new = new Prisma({});
|
||||
// const prisma_legacy = new PrismaLegacy({});
|
||||
// const prisma_new = new Prisma({});
|
||||
|
||||
export const extractOldTimesheets = async () => {
|
||||
const list_of_employees = await prisma_new.employees.findMany();
|
||||
// export const extractOldTimesheets = async () => {
|
||||
// const list_of_employees = await prisma_new.employees.findMany();
|
||||
|
||||
for (let id = 1; id <= list_of_employees.length; id++) {
|
||||
const new_employee = await findOneNewEmployee(id);
|
||||
// for (let id = 1; id <= list_of_employees.length; id++) {
|
||||
// const new_employee = await findOneNewEmployee(id);
|
||||
|
||||
const old_employee_id = await findOneOldEmployee(new_employee);
|
||||
// const old_employee_id = await findOneOldEmployee(new_employee);
|
||||
|
||||
const old_timesheets = await findManyOldTimesheets(old_employee_id);
|
||||
// const old_timesheets = await findManyOldTimesheets(old_employee_id);
|
||||
|
||||
await createManyNewTimesheets(old_timesheets, new_employee);
|
||||
console.log(`${old_timesheets.length} New Timesheets created in new DB for employee ${new_employee.id}`);
|
||||
}
|
||||
// await createManyNewTimesheets(old_timesheets, new_employee);
|
||||
// console.log(`${old_timesheets.length} New Timesheets created in new DB for employee ${new_employee.id}`);
|
||||
// }
|
||||
|
||||
await prisma_legacy.$disconnect();
|
||||
await prisma_new.$disconnect();
|
||||
console.log('migration of timesheets finished')
|
||||
}
|
||||
|
||||
const findOneNewEmployee = async (id: number): Promise<NewEmployee> => {
|
||||
const new_employee = await prisma_new.employees.findUnique({
|
||||
where: { id: id },
|
||||
select: {
|
||||
id: true,
|
||||
company_code: true,
|
||||
external_payroll_id: true,
|
||||
},
|
||||
});
|
||||
if (!new_employee) throw new Error(`New Employee with id ${id} not found`)
|
||||
return new_employee;
|
||||
}
|
||||
|
||||
const findOneOldEmployee = async (new_employee: NewEmployee): Promise<string> => {
|
||||
const employee_number = new_employee.external_payroll_id.toString()
|
||||
const old_employee = await prisma_legacy.employees.findFirst({
|
||||
where: {
|
||||
company: new_employee.company_code,
|
||||
employee_number: employee_number,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
if (!old_employee) throw new Error(`Old Employee not found`);
|
||||
return old_employee.id;
|
||||
}
|
||||
|
||||
const findManyOldTimesheets = async (old_employee_id: string) => {
|
||||
console.log('trying to find old timesheets ...');
|
||||
const old_timesheets = await prisma_legacy.time_sheets.findMany({
|
||||
where: { employee_id: old_employee_id },
|
||||
select: { id: true, start_date: true, status: true }
|
||||
});
|
||||
console.log(old_timesheets.length, 'old timesheets found')
|
||||
if (!old_timesheets) throw new Error(`old Timesheets not found for employee_id ${old_employee_id}`)
|
||||
return old_timesheets;
|
||||
}
|
||||
|
||||
const createManyNewTimesheets = async (old_timesheets: OldTimesheets[], new_employee: NewEmployee) => {
|
||||
console.log(old_timesheets.length, ' timesheets ready for creation')
|
||||
for (const timesheet of old_timesheets) {
|
||||
if (timesheet.start_date == null) {
|
||||
console.warn(`start_date invalid for legacy timesheet ${timesheet.id}`);
|
||||
continue;
|
||||
}
|
||||
if (timesheet.status == null) {
|
||||
console.warn(`status null for legacy timesheet ${timesheet.id}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`Timesheet with start_date: ${toStringFromDate(timesheet.start_date!)} for employee ${new_employee.id} created`)
|
||||
const new_timesheet = await prisma_new.timesheets.create({
|
||||
data: {
|
||||
employee_id: new_employee.id,
|
||||
start_date: timesheet.start_date,
|
||||
is_approved: timesheet.status,
|
||||
},
|
||||
});
|
||||
if (!new_timesheet) throw new Error(
|
||||
`Timesheet with start_date: ${toStringFromDate(timesheet.start_date!)} for employee ${new_employee.id} not created`
|
||||
);
|
||||
} catch (error) {
|
||||
throw new Error('An error occured during timesheets creation', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// extractOldTimesheets()
|
||||
// .then(() => {
|
||||
// console.log("Migration completed");
|
||||
// })
|
||||
// .catch((error) => {
|
||||
// console.error("Migration failed:", error);
|
||||
// })
|
||||
// .finally(async () => {
|
||||
// await prisma_legacy.$disconnect();
|
||||
// await prisma_new.$disconnect();
|
||||
// console.log('migration of timesheets finished')
|
||||
// }
|
||||
|
||||
// const findOneNewEmployee = async (id: number): Promise<NewEmployee> => {
|
||||
// const new_employee = await prisma_new.employees.findUnique({
|
||||
// where: { id: id },
|
||||
// select: {
|
||||
// id: true,
|
||||
// company_code: true,
|
||||
// external_payroll_id: true,
|
||||
// },
|
||||
// });
|
||||
// if (!new_employee) throw new Error(`New Employee with id ${id} not found`)
|
||||
// return new_employee;
|
||||
// }
|
||||
|
||||
// const findOneOldEmployee = async (new_employee: NewEmployee): Promise<string> => {
|
||||
// const employee_number = new_employee.external_payroll_id.toString()
|
||||
// const old_employee = await prisma_legacy.employees.findFirst({
|
||||
// where: {
|
||||
// company: new_employee.company_code,
|
||||
// employee_number: employee_number,
|
||||
// },
|
||||
// select: {
|
||||
// id: true,
|
||||
// },
|
||||
// });
|
||||
// if (!old_employee) throw new Error(`Old Employee not found`);
|
||||
// return old_employee.id;
|
||||
// }
|
||||
|
||||
// const findManyOldTimesheets = async (old_employee_id: string) => {
|
||||
// console.log('trying to find old timesheets ...');
|
||||
// const old_timesheets = await prisma_legacy.time_sheets.findMany({
|
||||
// where: { employee_id: old_employee_id },
|
||||
// select: { id: true, start_date: true, status: true }
|
||||
// });
|
||||
// console.log(old_timesheets.length, 'old timesheets found')
|
||||
// if (!old_timesheets) throw new Error(`old Timesheets not found for employee_id ${old_employee_id}`)
|
||||
// return old_timesheets;
|
||||
// }
|
||||
|
||||
// const createManyNewTimesheets = async (old_timesheets: OldTimesheets[], new_employee: NewEmployee) => {
|
||||
// console.log(old_timesheets.length, ' timesheets ready for creation')
|
||||
// for (const timesheet of old_timesheets) {
|
||||
// if (timesheet.start_date == null) {
|
||||
// console.warn(`start_date invalid for legacy timesheet ${timesheet.id}`);
|
||||
// continue;
|
||||
// }
|
||||
// if (timesheet.status == null) {
|
||||
// console.warn(`status null for legacy timesheet ${timesheet.id}`);
|
||||
// continue;
|
||||
// }
|
||||
|
||||
// try {
|
||||
// console.log(`Timesheet with start_date: ${toStringFromDate(timesheet.start_date!)} for employee ${new_employee.id} created`)
|
||||
// const new_timesheet = await prisma_new.timesheets.create({
|
||||
// data: {
|
||||
// employee_id: new_employee.id,
|
||||
// start_date: timesheet.start_date,
|
||||
// is_approved: timesheet.status,
|
||||
// },
|
||||
// });
|
||||
// if (!new_timesheet) throw new Error(
|
||||
// `Timesheet with start_date: ${toStringFromDate(timesheet.start_date!)} for employee ${new_employee.id} not created`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// throw new Error('An error occured during timesheets creation', error);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// // extractOldTimesheets()
|
||||
// // .then(() => {
|
||||
// // console.log("Migration completed");
|
||||
// // })
|
||||
// // .catch((error) => {
|
||||
// // console.error("Migration failed:", error);
|
||||
// // })
|
||||
// // .finally(async () => {
|
||||
// // await prisma_legacy.$disconnect();
|
||||
// // await prisma_new.$disconnect();
|
||||
// // });
|
||||
|
|
@ -1,10 +1,11 @@
|
|||
import { BankedHoursService } from "./services/banking-hours.service.service";
|
||||
import { SickLeaveService } from "./services/sick-leave.service";
|
||||
import { OvertimeService } from "./services/overtime.service";
|
||||
import { VacationService } from "./services/vacation.service";
|
||||
import { HolidayService } from "./services/holiday.service";
|
||||
import { MileageService } from "./services/mileage.service";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { EmailToIdResolver } from "src/common/mappers/email-id.mapper";
|
||||
import { Module } from "@nestjs/common";
|
||||
|
||||
|
||||
@Module({
|
||||
|
|
@ -16,6 +17,7 @@ import { EmailToIdResolver } from "src/common/mappers/email-id.mapper";
|
|||
SickLeaveService,
|
||||
VacationService,
|
||||
EmailToIdResolver,
|
||||
BankedHoursService,
|
||||
],
|
||||
exports: [
|
||||
HolidayService,
|
||||
|
|
@ -23,6 +25,7 @@ import { EmailToIdResolver } from "src/common/mappers/email-id.mapper";
|
|||
OvertimeService,
|
||||
SickLeaveService,
|
||||
VacationService,
|
||||
BankedHoursService,
|
||||
],
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,64 @@
|
|||
// import { Injectable } from "@nestjs/common";
|
||||
// import { Result } from "src/common/errors/result-error.factory";
|
||||
// import { PrismaService } from "src/prisma/prisma.service";
|
||||
|
||||
// @Injectable()
|
||||
// export class BankedHoursService {
|
||||
|
||||
// constructor(private readonly prisma: PrismaService) { }
|
||||
|
||||
// //manage shifts with bank_code.type BANKING
|
||||
// bankingHours = async (employee_id: number, hours: number): Promise<Result<number, string>> => {
|
||||
// if (hours <= 0) return { success: false, error: 'INVALID_BANKING_HOURS' };
|
||||
|
||||
// try {
|
||||
// const result = await this.prisma.$transaction(async (tx) => {
|
||||
// const employee = await this.prisma.employees.findUnique({
|
||||
// where: { id: employee_id },
|
||||
// select: {
|
||||
// id: true,
|
||||
// paid_time_off: {
|
||||
// select: {
|
||||
// banked_hours: true
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// });
|
||||
// if (!employee) {
|
||||
// return { success: false, error: 'EMPLOYEE_NOT_FOUND' } as Result<number, string>
|
||||
// }
|
||||
// if (!employee.paid_time_off) {
|
||||
// return { success: false, error: 'VACATION_HOURS_BANK_NOT_FOUND' } as Result<number, string>
|
||||
// }
|
||||
|
||||
// const new_balance = await tx.paidTimeOff.update({
|
||||
// where: { employee_id: employee.id },
|
||||
// data: {
|
||||
// banked_hours: { increment: hours },
|
||||
// },
|
||||
// select: {
|
||||
// banked_hours: true,
|
||||
// },
|
||||
// });
|
||||
// return { success: true, data: new_balance };
|
||||
// });
|
||||
|
||||
// return result;
|
||||
// } catch (error) {
|
||||
// return { success: false, error: 'INVALID_BANKING_SHIFT' };
|
||||
// }
|
||||
|
||||
|
||||
|
||||
|
||||
// }
|
||||
|
||||
|
||||
// //manage shifts with bank_code.type WITHDRAW_BANKED
|
||||
// withdrawBankedHours = async (employee_id: number, asked_hours: number): Promise<Result<number, string>> => {
|
||||
// if (asked_hours <= 0) return { success: false, error: 'INVALID_WITHDRAW_BANKED' };
|
||||
|
||||
|
||||
|
||||
// }
|
||||
// }
|
||||
|
|
@ -79,7 +79,7 @@ export class VacationService {
|
|||
try {
|
||||
const result = await this.prisma.$transaction(async (tx) => {
|
||||
//checks for remaining hours in vacation bank
|
||||
const employee = await this.prisma.employees.findUnique({
|
||||
const employee = await tx.employees.findUnique({
|
||||
where: { id: employee_id },
|
||||
select: { paid_time_off: { select: { vacation_hours: true } } },
|
||||
});
|
||||
|
|
@ -96,7 +96,7 @@ export class VacationService {
|
|||
return { success: true, data: vacation_bank } as Result<number, string>
|
||||
} else {
|
||||
//update vacation_bank
|
||||
await this.prisma.paidTimeOff.update({
|
||||
await tx.paidTimeOff.update({
|
||||
where: { employee_id: employee_id, vacation_hours: { gte: asked_hours } },
|
||||
data: {
|
||||
vacation_hours: { decrement: asked_hours },
|
||||
|
|
|
|||
|
|
@ -103,6 +103,8 @@ export class ShiftsCreateService {
|
|||
dto.end_time = this.addHourstoDateString(dto.start_time, vacation_shift.data);
|
||||
}
|
||||
|
||||
//ADD HERE THE LOGICS TO CHECK FOR AVAILABLE BANK TYPE "PAID_BANKED_HOUR" AND BANKING_HOUR
|
||||
|
||||
//sends data for creation of a shift in db
|
||||
const created_shift = await this.prisma.shifts.create({
|
||||
data: {
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user