fix: make seed resilient to tenantId NOT NULL constraint

This commit is contained in:
kevin-asprec
2026-04-15 11:08:56 +08:00
parent ab4eeb7ce6
commit 5b168f5682

View File

@@ -57,6 +57,14 @@ async function hashPassword(password: string): Promise<string> {
async function main() { async function main() {
console.log('Seeding database...'); console.log('Seeding database...');
// Ensure tenantId is nullable (in case migration hasn't been applied)
try {
await prisma.$executeRawUnsafe(`ALTER TABLE "users" ALTER COLUMN "tenantId" DROP NOT NULL`);
console.log('Made tenantId nullable');
} catch (e: any) {
console.log('tenantId already nullable or error:', e.message?.substring(0, 80));
}
// Clean existing data (order matters for FK constraints) // Clean existing data (order matters for FK constraints)
await prisma.journalLine.deleteMany(); await prisma.journalLine.deleteMany();
await prisma.journalEntry.deleteMany(); await prisma.journalEntry.deleteMany();
@@ -101,9 +109,22 @@ async function main() {
console.log(`Tenant: ${tenant.name}`); console.log(`Tenant: ${tenant.name}`);
// ─── Super Admin (platform-level, no tenant) ─────────── // ─── Super Admin (platform-level, no tenant) ───────────
const superAdmin = await prisma.user.create({ // If tenantId column is NOT NULL (migration not applied), use tenant.id as fallback
let superAdmin;
try {
superAdmin = await prisma.user.create({
data: { tenantId: null, email: 'superadmin@fiberops.dev', password: await hashPassword('admin123!'), firstName: 'Super', lastName: 'Admin' }, data: { tenantId: null, email: 'superadmin@fiberops.dev', password: await hashPassword('admin123!'), firstName: 'Super', lastName: 'Admin' },
}); });
} catch (e: any) {
if (e?.code === 'P2002' || e?.message?.includes('Null constraint')) {
console.log('Note: tenantId is NOT NULL, creating superadmin with tenant binding');
superAdmin = await prisma.user.create({
data: { tenantId: tenant.id, email: 'superadmin@fiberops.dev', password: await hashPassword('admin123!'), firstName: 'Super', lastName: 'Admin' },
});
} else {
throw e;
}
}
await prisma.userRole.create({ data: { userId: superAdmin.id, role: 'super_admin' } }); await prisma.userRole.create({ data: { userId: superAdmin.id, role: 'super_admin' } });
console.log(`Super Admin: superadmin@fiberops.dev (super_admin)`); console.log(`Super Admin: superadmin@fiberops.dev (super_admin)`);