feat: Implement Prisma PG adapter, refactor user and agent profiles in schema, and add database seeding.

This commit is contained in:
pradeepkumar
2025-12-19 01:15:19 +05:30
parent c1fcf32eb5
commit 1812fd3c98
8 changed files with 867 additions and 1143 deletions

View File

@@ -7,7 +7,6 @@ generator client {
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
// ===========================================
@@ -33,24 +32,14 @@ enum AuthProvider {
FACEBOOK
}
enum VerificationStatus {
PENDING
APPROVED
REJECTED
}
// ===========================================
// USER & AUTHENTICATION (Milestone 1)
// USER - Authentication Only
// ===========================================
model User {
id String @id @default(uuid())
email String @unique
password String? // Null for social login users
firstName String?
lastName String?
phone String?
avatar String?
role UserRole @default(USER)
status UserStatus @default(ACTIVE)
emailVerified Boolean @default(false)
@@ -66,10 +55,12 @@ model User {
updatedAt DateTime @updatedAt
lastLoginAt DateTime?
// Relations (will be added in later milestones)
// Relations - Profile based on role
userProfile UserProfile?
agentProfile AgentProfile?
// Auth Relations
sessions Session[]
passwordResets PasswordReset[]
@@index([email])
@@index([role])
@@ -77,6 +68,83 @@ model User {
@@map("users")
}
// ===========================================
// USER PROFILE - Normal Users
// ===========================================
model UserProfile {
id String @id @default(uuid())
userId String @unique
firstName String?
lastName String?
phone String?
avatar String?
// Location
city String?
state String?
country String?
// Timestamps
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Relations
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
@@map("user_profiles")
}
// ===========================================
// AGENT PROFILE - Agents/Subscribers
// ===========================================
model AgentProfile {
id String @id @default(uuid())
userId String @unique
slug String @unique
// Basic Info
firstName String?
lastName String?
phone String?
avatar String?
bio String?
headline String?
// Location
city String?
state String?
country String?
address String?
// Professional Info
yearsOfExperience Int?
licenseNumber String?
companyName String?
// Profile Status
isProfileComplete Boolean @default(false)
profileCompleteness Int @default(0)
// Timestamps
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Relations
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId])
@@index([slug])
@@index([city, state])
@@map("agent_profiles")
}
// ===========================================
// SESSION - JWT Token Management
// ===========================================
model Session {
id String @id @default(uuid())
userId String
@@ -93,55 +161,3 @@ model Session {
@@index([token])
@@map("sessions")
}
model PasswordReset {
id String @id @default(uuid())
userId String
token String @unique
expiresAt DateTime
usedAt DateTime?
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([token])
@@map("password_resets")
}
// ===========================================
// AGENT PROFILE (Milestone 2 - Placeholder)
// ===========================================
model AgentProfile {
id String @id @default(uuid())
userId String @unique
slug String @unique
bio String?
headline String?
location String?
city String?
state String?
country String?
yearsOfExperience Int?
licenseNumber String?
// Verification
verificationStatus VerificationStatus @default(PENDING)
verifiedAt DateTime?
// Profile completeness
isProfileComplete Boolean @default(false)
profileCompleteness Int @default(0)
// Timestamps
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
// Relations
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([slug])
@@index([verificationStatus])
@@index([city, state])
@@map("agent_profiles")
}

69
prisma/seed.ts Normal file
View File

@@ -0,0 +1,69 @@
import { PrismaClient, UserRole, UserStatus, AuthProvider } from '@prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';
import { Pool } from 'pg';
import * as argon2 from 'argon2';
async function main() {
const connectionString = process.env.DATABASE_URL;
const pool = new Pool({ connectionString });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });
console.log('🌱 Starting database seeding...\n');
// Admin credentials
const adminEmail = process.env.ADMIN_EMAIL || 'admin@realestate.com';
const adminPassword = process.env.ADMIN_PASSWORD || 'Admin@123456';
// Hash password with Argon2 (more secure than bcrypt)
const hashedPassword = await argon2.hash(adminPassword);
// Check if admin already exists
const existingAdmin = await prisma.user.findUnique({
where: { email: adminEmail },
});
if (existingAdmin) {
console.log(`⚠️ Admin user already exists: ${adminEmail}`);
} else {
// Create admin user
const admin = await prisma.user.create({
data: {
email: adminEmail,
password: hashedPassword,
role: UserRole.ADMIN,
status: UserStatus.ACTIVE,
emailVerified: true,
emailVerifiedAt: new Date(),
authProvider: AuthProvider.LOCAL,
},
});
console.log('✅ Admin user created successfully!');
console.log(' ───────────────────────────────');
console.log(` 📧 Email: ${adminEmail}`);
console.log(` 🔑 Password: ${adminPassword}`);
console.log(` 👤 Role: ${admin.role}`);
console.log(` 🆔 ID: ${admin.id}`);
console.log(' ───────────────────────────────\n');
}
// Summary
const userCount = await prisma.user.count();
const adminCount = await prisma.user.count({ where: { role: UserRole.ADMIN } });
console.log('📊 Database Summary:');
console.log(` Total Users: ${userCount}`);
console.log(` Admins: ${adminCount}`);
console.log('\n🌱 Seeding completed!\n');
await prisma.$disconnect();
await pool.end();
}
main()
.catch((e) => {
console.error('❌ Seeding failed:', e);
process.exit(1);
});