2026-03-01 18:32:49 +00:00

262 lines
9.4 KiB
TypeScript

import "dotenv/config";
import { createClient } from "@supabase/supabase-js";
import { clerkClient } from "@clerk/nextjs/server";
import * as fs from "fs";
import * as path from "path";
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
"sb_secret_N7UND0UgjKTVK-Uodkm0Hg_xSvEMPvz",
{ auth: { persistSession: false } }
);
const PASSWORD = "&%5C400l&%";
async function cleanClerk() {
console.log("Cleaning up old Clerk users...");
const clerk = clerkClient();
const users = await clerk.users.getUserList({ limit: 500 });
for (const user of users.data) {
if (
user.publicMetadata.role === "teacher" ||
user.publicMetadata.role === "student" ||
user.publicMetadata.role === "parent"
) {
await clerk.users.deleteUser(user.id);
}
}
}
async function cleanSupabase() {
console.log("Cleaning up Supabase tables...");
const tables = [
"Result", "Assignment", "Exam", "Attendance", "Event", "Announcement",
"Lesson", "TeacherSubject", "Student", "Teacher", "Parent", "Class", "Subject", "Grade"
];
for (const table of tables) {
await supabase.from(table).delete().neq("id", "0" as any);
}
}
async function seedAdmin() {
console.log("Syncing Admin...");
const clerk = clerkClient();
const users = await clerk.users.getUserList({ limit: 100 });
const adminUser = users.data.find(u => u.username === "admin" || u.emailAddresses[0]?.emailAddress?.includes("admin"));
if (adminUser) {
await supabase.from("Admin").upsert({ id: adminUser.id, username: adminUser.username || "admin" });
console.log(`Synced Admin ID: ${adminUser.id}`);
}
}
async function main() {
try {
const clerk = clerkClient();
await cleanClerk();
await cleanSupabase();
await seedAdmin();
console.log("Seeding Grades and Subjects...");
const grades = [1, 2, 3, 4, 5, 6].map((level) => ({ id: level, level }));
await supabase.from("Grade").insert(grades);
const subjectsArray = [
{ id: 1, name: "Mathematics" },
{ id: 2, name: "Science" },
{ id: 3, name: "English" },
{ id: 4, name: "History" },
{ id: 5, name: "Geography" },
{ id: 6, name: "Physics" },
{ id: 7, name: "Chemistry" },
{ id: 8, name: "Biology" },
{ id: 9, name: "Computer Science" },
{ id: 10, name: "Art" },
];
await supabase.from("Subject").insert(subjectsArray);
console.log("Creating 15 Teachers...");
const teacherMap: Record<number, string> = {};
for (let i = 1; i <= 15; i++) {
const user = await clerk.users.createUser({
username: `teacher${i}`,
password: PASSWORD,
firstName: `TName${i}`,
lastName: `TSurname${i}`,
publicMetadata: { role: "teacher" }
});
teacherMap[i] = user.id;
await supabase.from("Teacher").insert({
id: user.id,
username: `teacher${i}`,
name: `TName${i}`,
surname: `TSurname${i}`,
email: `teacher${i}@example.com`,
phone: `123-456-789${i}`,
address: `Address${i}`,
bloodType: "A+",
sex: i % 2 === 0 ? "MALE" : "FEMALE",
birthday: "1996-02-27T00:26:35.280Z"
});
await supabase.from("TeacherSubject").insert([
{ subjectId: (i % 10) + 1, teacherId: user.id, isPrimary: true },
{ subjectId: ((i + 1) % 10) + 1, teacherId: user.id }
]);
}
console.log("Creating 6 Classes...");
const classesArray = [
{ id: 1, name: "1A", gradeId: 1, capacity: 20, supervisorId: teacherMap[1] },
{ id: 2, name: "2A", gradeId: 2, capacity: 20, supervisorId: teacherMap[2] },
{ id: 3, name: "3A", gradeId: 3, capacity: 20, supervisorId: teacherMap[3] },
{ id: 4, name: "4A", gradeId: 4, capacity: 20, supervisorId: teacherMap[4] },
{ id: 5, name: "5A", gradeId: 5, capacity: 20, supervisorId: teacherMap[5] },
{ id: 6, name: "6A", gradeId: 6, capacity: 20, supervisorId: teacherMap[1] },
];
await supabase.from("Class").insert(classesArray);
console.log("Creating 25 Parents...");
const parentMap: Record<number, string> = {};
for (let i = 1; i <= 25; i++) {
const user = await clerk.users.createUser({
username: `parent${i}`,
password: PASSWORD,
firstName: `PName${i}`,
lastName: `PSurname${i}`,
publicMetadata: { role: "parent" }
});
parentMap[i] = user.id;
await supabase.from("Parent").insert({
id: user.id,
username: `parent${i}`,
name: `PName${i}`,
surname: `PSurname${i}`,
email: `parent${i}@example.com`,
phone: `123-456-789${i}`,
address: `Address${i}`
});
}
console.log("Creating 50 Students...");
const studentMap: Record<number, string> = {};
for (let i = 1; i <= 50; i++) {
const user = await clerk.users.createUser({
username: `student${i}`,
password: PASSWORD,
firstName: `SName${i}`,
lastName: `SSurname${i}`,
publicMetadata: { role: "student" }
});
studentMap[i] = user.id;
const classInfo = classesArray[(i % 6)];
await supabase.from("Student").insert({
id: user.id,
username: `student${i}`,
name: `SName${i}`,
surname: `SSurname${i}`,
email: `student${i}@example.com`,
phone: `987-654-321${i}`,
address: `Address${i}`,
bloodType: "O-",
sex: i % 2 === 0 ? "MALE" : "FEMALE",
parentId: parentMap[(i % 25) + 1],
gradeId: classInfo.gradeId,
classId: classInfo.id,
birthday: "2016-02-27T00:26:35.281Z"
});
}
console.log("Exporting User IDs to seed-data.json...");
const seedDataPath = path.join(process.cwd(), "scripts", "seed-data.json");
const seedData = {
teacherMap,
parentMap,
studentMap,
classes: classesArray
};
fs.writeFileSync(seedDataPath, JSON.stringify(seedData, null, 2));
console.log("User generation complete! Saved to seed-data.json.");
/*
const daysOfWeek: ("MONDAY" | "TUESDAY" | "WEDNESDAY" | "THURSDAY" | "FRIDAY")[] = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY"];
for (let i = 1; i <= 30; i++) {
const classIndex = i % 6;
const classInfo = classesArray[classIndex];
const teacherIndex = (i % 15) + 1;
const teacherId = teacherMap[teacherIndex];
const subjectId = (teacherIndex % 10) + 1;
// Distribute across 5 days (Monday to Friday)
const dayIndex = i % 5;
const dayName = daysOfWeek[dayIndex];
// Distribute across 6 periods (e.g., 8:00 AM to 2:00 PM)
const periodIndex = (i % 6);
// Base date (a Monday): 2026-02-23T00:00:00.000Z
const lessonDate = new Date("2026-02-23T00:00:00.000Z");
lessonDate.setDate(lessonDate.getDate() + dayIndex);
// Create start time and end time (1 hour lesson)
const startHour = 8 + periodIndex;
const startTime = new Date(lessonDate);
startTime.setUTCHours(startHour, 0, 0, 0);
const endTime = new Date(lessonDate);
endTime.setUTCHours(startHour + 1, 0, 0, 0);
await supabase.from("Lesson").insert({
id: i,
name: `Lesson${i}`,
day: dayName,
startTime: startTime.toISOString(),
endTime: endTime.toISOString(),
subjectId: subjectId,
classId: classInfo.id,
teacherId: teacherId
});
await supabase.from("Exam").insert({
id: i,
title: `Exam ${i}`,
startTime: startTime.toISOString(),
endTime: endTime.toISOString(),
lessonId: i
});
await supabase.from("Assignment").insert({
id: i,
title: `Assignment ${i}`,
startDate: startTime.toISOString(),
dueDate: new Date(startTime.getTime() + 7 * 24 * 60 * 60 * 1000).toISOString(), // Due in 7 days
lessonId: i
});
// Result requires a student from the class 'classIndex'.
// Student 'j' is in class 'j % 6'.
const studentBase = classIndex === 0 ? 6 : classIndex;
const studentIndex = studentBase + 6 * (i % 8); // Ensures variation 1-48
await supabase.from("Result").insert({
id: i,
score: 90 + (i % 10),
studentId: studentMap[studentIndex],
examId: i
});
}
*/
} catch (err) {
console.error("Seed error:", err);
}
}
main();