87 lines
2.5 KiB
TypeScript
87 lines
2.5 KiB
TypeScript
import * as bcrypt from 'bcrypt';
|
|
import { AppDataSource } from '../data-source';
|
|
import { Branch } from '../entities/branch.entity';
|
|
import { User } from '../entities/user.entity';
|
|
import { UserRole } from '../enums/user-role.enum';
|
|
|
|
const DEFAULT_PASSWORD = 'Password123';
|
|
|
|
type SeedUser = {
|
|
cardNumber: string;
|
|
role: UserRole;
|
|
branchCode: string;
|
|
};
|
|
|
|
const BRANCHES = [
|
|
{ code: 'A', name: 'Branch A' },
|
|
{ code: 'B', name: 'Branch B' },
|
|
];
|
|
|
|
const USERS: SeedUser[] = [
|
|
{ cardNumber: '100000', role: UserRole.SUPER_ADMIN, branchCode: 'A' },
|
|
{ cardNumber: '200000', role: UserRole.ADMIN, branchCode: 'A' },
|
|
{ cardNumber: '300000', role: UserRole.SUPERVISOR, branchCode: 'B' },
|
|
{ cardNumber: '400000', role: UserRole.WORKER, branchCode: 'B' },
|
|
];
|
|
|
|
async function upsertBranches(): Promise<Map<string, Branch>> {
|
|
const branchRepo = AppDataSource.getRepository(Branch);
|
|
const branchMap = new Map<string, Branch>();
|
|
|
|
for (const branchInput of BRANCHES) {
|
|
let branch = await branchRepo.findOne({ where: { code: branchInput.code } });
|
|
if (!branch) {
|
|
branch = branchRepo.create(branchInput);
|
|
} else {
|
|
branch.name = branchInput.name;
|
|
}
|
|
const saved = await branchRepo.save(branch);
|
|
branchMap.set(saved.code, saved);
|
|
}
|
|
|
|
return branchMap;
|
|
}
|
|
|
|
async function upsertUsers(branches: Map<string, Branch>): Promise<void> {
|
|
const userRepo = AppDataSource.getRepository(User);
|
|
const passwordHash = await bcrypt.hash(DEFAULT_PASSWORD, 10);
|
|
|
|
for (const seedUser of USERS) {
|
|
const branch = branches.get(seedUser.branchCode);
|
|
if (!branch) {
|
|
throw new Error(`Branch with code ${seedUser.branchCode} not found during seed`);
|
|
}
|
|
|
|
let user = await userRepo.findOne({ where: { cardNumber: seedUser.cardNumber } });
|
|
if (!user) {
|
|
user = userRepo.create({
|
|
cardNumber: seedUser.cardNumber,
|
|
role: seedUser.role,
|
|
branchId: branch.id,
|
|
passwordHash,
|
|
refreshTokenHash: null,
|
|
refreshTokenExpiresAt: null,
|
|
});
|
|
} else {
|
|
user.role = seedUser.role;
|
|
user.branchId = branch.id;
|
|
user.passwordHash = passwordHash;
|
|
}
|
|
|
|
await userRepo.save(user);
|
|
}
|
|
}
|
|
|
|
async function runSeed(): Promise<void> {
|
|
await AppDataSource.initialize();
|
|
const branches = await upsertBranches();
|
|
await upsertUsers(branches);
|
|
await AppDataSource.destroy();
|
|
}
|
|
|
|
runSeed().catch((error) => {
|
|
// eslint-disable-next-line no-console
|
|
console.error('Seed failed:', error);
|
|
process.exit(1);
|
|
});
|