241 lines
9.7 KiB
JavaScript
241 lines
9.7 KiB
JavaScript
import bcrypt from 'bcryptjs';
|
||
import mysql from 'mysql2/promise';
|
||
import dotenv from 'dotenv';
|
||
|
||
dotenv.config();
|
||
|
||
async function seedDatabase() {
|
||
let connection;
|
||
|
||
try {
|
||
// Connect to database with retry logic
|
||
console.log('🔌 Connecting to database...');
|
||
|
||
let retries = 5;
|
||
while (retries > 0) {
|
||
try {
|
||
connection = await mysql.createConnection({
|
||
host: process.env.DB_HOST || 'localhost',
|
||
user: process.env.DB_USER || 'root',
|
||
password: process.env.DB_PASSWORD || 'admin123',
|
||
database: process.env.DB_NAME || 'work_allocation',
|
||
port: process.env.DB_PORT || 3306,
|
||
connectTimeout: 10000,
|
||
enableKeepAlive: true,
|
||
keepAliveInitialDelay: 0
|
||
});
|
||
break;
|
||
} catch (err) {
|
||
retries--;
|
||
if (retries === 0) throw err;
|
||
console.log(` ⏳ Retrying connection... (${5 - retries}/5)`);
|
||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||
}
|
||
}
|
||
|
||
console.log('✅ Connected to database');
|
||
console.log('');
|
||
|
||
// 1. Seed Departments
|
||
console.log('📁 Seeding departments...');
|
||
const [existingDepts] = await connection.query('SELECT COUNT(*) as count FROM departments');
|
||
|
||
if (existingDepts[0].count === 0) {
|
||
await connection.query(`
|
||
INSERT INTO departments (name) VALUES
|
||
('Tudki'),
|
||
('Dana'),
|
||
('Groundnut')
|
||
`);
|
||
console.log(' ✅ Departments created');
|
||
} else {
|
||
console.log(' ℹ️ Departments already exist');
|
||
}
|
||
|
||
// 2. Seed Sub-departments for Groundnut
|
||
console.log('📂 Seeding sub-departments...');
|
||
const [groundnutDept] = await connection.query('SELECT id FROM departments WHERE name = ?', ['Groundnut']);
|
||
let groundnutId = null;
|
||
|
||
if (groundnutDept.length > 0) {
|
||
groundnutId = groundnutDept[0].id;
|
||
const [existingSubDepts] = await connection.query('SELECT COUNT(*) as count FROM sub_departments WHERE department_id = ?', [groundnutId]);
|
||
|
||
if (existingSubDepts[0].count === 0) {
|
||
await connection.query(`
|
||
INSERT INTO sub_departments (department_id, name, primary_activity) VALUES
|
||
(?, 'Mufali Aavak Katai', 'Loading/Unloading'),
|
||
(?, 'Mufali Aavak Dhang', 'Loading/Unloading'),
|
||
(?, 'Dhang Se Katai', 'Loading/Unloading'),
|
||
(?, 'Guthli Bori Silai Dhang', 'Loading/Unloading'),
|
||
(?, 'Guthali dada Pala Tulai Silai Dhang', 'Loading/Unloading'),
|
||
(?, 'Mufali Patthar Bori silai dhang', 'Loading/Unloading'),
|
||
(?, 'Mufali Patthar Bori Utrai', 'Loading/Unloading'),
|
||
(?, 'Bardana Bandal Loading Unloading', 'Loading/Unloading'),
|
||
(?, 'Bardana Gatthi Loading', 'Loading/Unloading'),
|
||
(?, 'Black Dana Loading/Unloading', 'Loading/Unloading'),
|
||
(?, 'Pre Cleaning', 'Pre Cleaning'),
|
||
(?, 'Destoner', 'Destoner'),
|
||
(?, 'Water', 'Water'),
|
||
(?, 'Decordicater', 'Decordicater & Cleaning'),
|
||
(?, 'Round Chalna', 'Round Chalna & Cleaning'),
|
||
(?, 'Cleaning', 'Decordicater & Cleaning'),
|
||
(?, 'Round Chalna No.1', 'Round Chalna No.1')
|
||
`, Array(17).fill(groundnutId));
|
||
console.log(' ✅ Sub-departments created');
|
||
} else {
|
||
console.log(' ℹ️ Sub-departments already exist');
|
||
}
|
||
}
|
||
|
||
// 3. Seed SuperAdmin
|
||
console.log('👤 Seeding SuperAdmin user...');
|
||
const [existingAdmin] = await connection.query('SELECT id FROM users WHERE username = ?', ['admin']);
|
||
|
||
const adminPassword = await bcrypt.hash('admin123', 10);
|
||
|
||
if (existingAdmin.length > 0) {
|
||
await connection.query(
|
||
'UPDATE users SET password = ?, is_active = TRUE WHERE username = ?',
|
||
[adminPassword, 'admin']
|
||
);
|
||
console.log(' ✅ SuperAdmin password updated');
|
||
} else {
|
||
await connection.query(
|
||
'INSERT INTO users (username, name, email, password, role, is_active) VALUES (?, ?, ?, ?, ?, ?)',
|
||
['admin', 'Super Admin', 'admin@workallocate.com', adminPassword, 'SuperAdmin', true]
|
||
);
|
||
console.log(' ✅ SuperAdmin created');
|
||
}
|
||
|
||
// 4. Seed Sample Supervisors
|
||
console.log('👥 Seeding sample supervisors...');
|
||
const [tudkiDept] = await connection.query('SELECT id FROM departments WHERE name = ?', ['Tudki']);
|
||
const [danaDept] = await connection.query('SELECT id FROM departments WHERE name = ?', ['Dana']);
|
||
|
||
const supervisorPassword = await bcrypt.hash('supervisor123', 10);
|
||
|
||
const supervisors = [
|
||
{ username: 'supervisor_tudki', name: 'Tudki Supervisor', email: 'supervisor.tudki@workallocate.com', deptId: tudkiDept[0]?.id },
|
||
{ username: 'supervisor_dana', name: 'Dana Supervisor', email: 'supervisor.dana@workallocate.com', deptId: danaDept[0]?.id },
|
||
{ username: 'supervisor_groundnut', name: 'Groundnut Supervisor', email: 'supervisor.groundnut@workallocate.com', deptId: groundnutId }
|
||
];
|
||
|
||
for (const sup of supervisors) {
|
||
if (sup.deptId) {
|
||
const [existing] = await connection.query('SELECT id FROM users WHERE username = ?', [sup.username]);
|
||
if (existing.length === 0) {
|
||
await connection.query(
|
||
'INSERT INTO users (username, name, email, password, role, department_id, is_active) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||
[sup.username, sup.name, sup.email, supervisorPassword, 'Supervisor', sup.deptId, true]
|
||
);
|
||
console.log(` ✅ ${sup.name} created`);
|
||
} else {
|
||
console.log(` ℹ️ ${sup.name} already exists`);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 5. Seed Sample Contractors
|
||
console.log('🏗️ Seeding sample contractors...');
|
||
const contractorPassword = await bcrypt.hash('contractor123', 10);
|
||
|
||
const contractors = [
|
||
{ username: 'contractor1', name: 'Contractor One', email: 'contractor1@workallocate.com', deptId: groundnutId },
|
||
{ username: 'contractor2', name: 'Contractor Two', email: 'contractor2@workallocate.com', deptId: groundnutId }
|
||
];
|
||
|
||
for (const con of contractors) {
|
||
const [existing] = await connection.query('SELECT id FROM users WHERE username = ?', [con.username]);
|
||
if (existing.length === 0) {
|
||
await connection.query(
|
||
'INSERT INTO users (username, name, email, password, role, department_id, is_active) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||
[con.username, con.name, con.email, contractorPassword, 'Contractor', con.deptId, true]
|
||
);
|
||
console.log(` ✅ ${con.name} created`);
|
||
} else {
|
||
console.log(` ℹ️ ${con.name} already exists`);
|
||
}
|
||
}
|
||
|
||
// 6. Seed Sample Employees
|
||
console.log('👷 Seeding sample employees...');
|
||
const [contractor1] = await connection.query('SELECT id FROM users WHERE username = ?', ['contractor1']);
|
||
const employeePassword = await bcrypt.hash('employee123', 10);
|
||
|
||
if (contractor1.length > 0) {
|
||
const employees = [
|
||
{ username: 'employee1', name: 'Employee One', email: 'employee1@workallocate.com' },
|
||
{ username: 'employee2', name: 'Employee Two', email: 'employee2@workallocate.com' },
|
||
{ username: 'employee3', name: 'Employee Three', email: 'employee3@workallocate.com' }
|
||
];
|
||
|
||
for (const emp of employees) {
|
||
const [existing] = await connection.query('SELECT id FROM users WHERE username = ?', [emp.username]);
|
||
if (existing.length === 0) {
|
||
await connection.query(
|
||
'INSERT INTO users (username, name, email, password, role, department_id, contractor_id, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
||
[emp.username, emp.name, emp.email, employeePassword, 'Employee', groundnutId, contractor1[0].id, true]
|
||
);
|
||
console.log(` ✅ ${emp.name} created`);
|
||
} else {
|
||
console.log(` ℹ️ ${emp.name} already exists`);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 7. Seed Contractor Rates
|
||
console.log('💰 Seeding contractor rates...');
|
||
if (contractor1.length > 0) {
|
||
const [existingRate] = await connection.query(
|
||
'SELECT id FROM contractor_rates WHERE contractor_id = ?',
|
||
[contractor1[0].id]
|
||
);
|
||
|
||
if (existingRate.length === 0) {
|
||
await connection.query(
|
||
'INSERT INTO contractor_rates (contractor_id, rate, effective_date) VALUES (?, ?, CURDATE())',
|
||
[contractor1[0].id, 500.00]
|
||
);
|
||
console.log(' ✅ Contractor rates created');
|
||
} else {
|
||
console.log(' ℹ️ Contractor rates already exist');
|
||
}
|
||
}
|
||
|
||
console.log('');
|
||
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
|
||
console.log('✅ Database seeding completed successfully!');
|
||
console.log('');
|
||
console.log('🔑 Default Login Credentials:');
|
||
console.log('');
|
||
console.log(' SuperAdmin:');
|
||
console.log(' Username: admin');
|
||
console.log(' Password: admin123');
|
||
console.log('');
|
||
console.log(' Supervisor (Groundnut):');
|
||
console.log(' Username: supervisor_groundnut');
|
||
console.log(' Password: supervisor123');
|
||
console.log('');
|
||
console.log(' Contractor:');
|
||
console.log(' Username: contractor1');
|
||
console.log(' Password: contractor123');
|
||
console.log('');
|
||
console.log(' Employee:');
|
||
console.log(' Username: employee1');
|
||
console.log(' Password: employee123');
|
||
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
|
||
console.log('');
|
||
|
||
} catch (error) {
|
||
console.error('❌ Error seeding database:', error.message);
|
||
process.exit(1);
|
||
} finally {
|
||
if (connection) {
|
||
await connection.end();
|
||
}
|
||
}
|
||
}
|
||
|
||
seedDatabase();
|