sync-docs-and-fixes
This commit is contained in:
@@ -4,7 +4,7 @@ import { cache } from "react"
|
||||
import { eq } from "drizzle-orm"
|
||||
|
||||
import { db } from "@/shared/db"
|
||||
import { users } from "@/shared/db/schema"
|
||||
import { roles, users, usersToRoles } from "@/shared/db/schema"
|
||||
|
||||
export type UserProfile = {
|
||||
id: string
|
||||
@@ -21,6 +21,25 @@ export type UserProfile = {
|
||||
updatedAt: Date
|
||||
}
|
||||
|
||||
const rolePriority = ["admin", "teacher", "parent", "student"] as const
|
||||
|
||||
const normalizeRoleName = (value: string) => {
|
||||
const role = value.trim().toLowerCase()
|
||||
if (role === "grade_head" || role === "teaching_head") return "teacher"
|
||||
if (role === "admin" || role === "teacher" || role === "parent" || role === "student") return role
|
||||
return ""
|
||||
}
|
||||
|
||||
const resolvePrimaryRole = (roleNames: string[]) => {
|
||||
const mapped = roleNames.map(normalizeRoleName).filter(Boolean)
|
||||
if (mapped.length) {
|
||||
for (const role of rolePriority) {
|
||||
if (mapped.includes(role)) return role
|
||||
}
|
||||
}
|
||||
return "student"
|
||||
}
|
||||
|
||||
export const getUserProfile = cache(async (userId: string): Promise<UserProfile | null> => {
|
||||
const user = await db.query.users.findFirst({
|
||||
where: eq(users.id, userId),
|
||||
@@ -28,12 +47,19 @@ export const getUserProfile = cache(async (userId: string): Promise<UserProfile
|
||||
|
||||
if (!user) return null
|
||||
|
||||
const roleRows = await db
|
||||
.select({ name: roles.name })
|
||||
.from(usersToRoles)
|
||||
.innerJoin(roles, eq(usersToRoles.roleId, roles.id))
|
||||
.where(eq(usersToRoles.userId, userId))
|
||||
const role = resolvePrimaryRole(roleRows.map((r) => r.name))
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
image: user.image,
|
||||
role: user.role,
|
||||
role,
|
||||
phone: user.phone,
|
||||
address: user.address,
|
||||
gender: user.gender,
|
||||
|
||||
Reference in New Issue
Block a user