feat: expand admin companies and users modules

This commit is contained in:
Esdras Renan 2025-10-22 01:27:43 -03:00
parent a043b1203c
commit 2e3b46a7b5
31 changed files with 5626 additions and 2003 deletions

View file

@ -1,35 +1,19 @@
import { NextResponse } from "next/server"
import { randomBytes } from "crypto"
import { hashPassword } from "better-auth/crypto"
import { ConvexHttpClient } from "convex/browser"
import type { UserRole } from "@prisma/client"
import { api } from "@/convex/_generated/api"
import { prisma } from "@/lib/prisma"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { assertStaffSession } from "@/lib/auth-server"
import { ROLE_OPTIONS, type RoleOption, isAdmin } from "@/lib/authz"
import { isAdmin } from "@/lib/authz"
export const runtime = "nodejs"
function normalizeRole(input: string | null | undefined): RoleOption {
const role = (input ?? "agent").toLowerCase() as RoleOption
return (ROLE_OPTIONS as readonly string[]).includes(role) ? role : "agent"
}
const ALLOWED_ROLES = ["MANAGER", "COLLABORATOR"] as const
const USER_ROLE_OPTIONS: ReadonlyArray<UserRole> = ["ADMIN", "MANAGER", "AGENT", "COLLABORATOR"]
type AllowedRole = (typeof ALLOWED_ROLES)[number]
function mapToUserRole(role: RoleOption): UserRole {
const candidate = role.toUpperCase() as UserRole
return USER_ROLE_OPTIONS.includes(candidate) ? candidate : "AGENT"
}
function generatePassword(length = 12) {
const bytes = randomBytes(length)
return Array.from(bytes)
.map((byte) => (byte % 36).toString(36))
.join("")
function normalizeRole(role?: string | null): AllowedRole {
const normalized = (role ?? "COLLABORATOR").toUpperCase()
return ALLOWED_ROLES.includes(normalized as AllowedRole) ? (normalized as AllowedRole) : "COLLABORATOR"
}
export async function GET() {
@ -38,111 +22,135 @@ export async function GET() {
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
}
const users = await prisma.authUser.findMany({
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
const users = await prisma.user.findMany({
where: {
tenantId,
role: { in: [...ALLOWED_ROLES] },
},
include: {
company: {
select: {
id: true,
name: true,
},
},
},
orderBy: { createdAt: "desc" },
})
const emails = users.map((user) => user.email)
const authUsers = await prisma.authUser.findMany({
where: { email: { in: emails } },
select: {
id: true,
email: true,
name: true,
role: true,
tenantId: true,
updatedAt: true,
createdAt: true,
},
})
const sessions = await prisma.authSession.findMany({
where: { userId: { in: authUsers.map((authUser) => authUser.id) } },
orderBy: { updatedAt: "desc" },
select: {
userId: true,
updatedAt: true,
},
})
return NextResponse.json({ users })
const sessionByUserId = new Map<string, Date>()
for (const sessionRow of sessions) {
if (!sessionByUserId.has(sessionRow.userId)) {
sessionByUserId.set(sessionRow.userId, sessionRow.updatedAt)
}
}
const authByEmail = new Map<string, { id: string; updatedAt: Date; createdAt: Date }>()
for (const authUser of authUsers) {
authByEmail.set(authUser.email.toLowerCase(), {
id: authUser.id,
updatedAt: authUser.updatedAt,
createdAt: authUser.createdAt,
})
}
const items = users.map((user) => {
const auth = authByEmail.get(user.email.toLowerCase())
const lastSeenAt = auth ? sessionByUserId.get(auth.id) ?? auth.updatedAt : null
return {
id: user.id,
email: user.email,
name: user.name,
role: normalizeRole(user.role),
companyId: user.companyId,
companyName: user.company?.name ?? null,
tenantId: user.tenantId,
createdAt: user.createdAt.toISOString(),
updatedAt: user.updatedAt.toISOString(),
authUserId: auth?.id ?? null,
lastSeenAt: lastSeenAt ? lastSeenAt.toISOString() : null,
}
})
return NextResponse.json({ items })
}
export async function POST(request: Request) {
export async function DELETE(request: Request) {
const session = await assertStaffSession()
if (!session) {
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
}
if (!isAdmin(session.user.role)) {
return NextResponse.json({ error: "Apenas administradores podem criar usuários" }, { status: 403 })
return NextResponse.json({ error: "Apenas administradores podem excluir usuários." }, { status: 403 })
}
const payload = await request.json().catch(() => null)
if (!payload || typeof payload !== "object") {
return NextResponse.json({ error: "Payload inválido" }, { status: 400 })
const json = await request.json().catch(() => null)
const ids = Array.isArray(json?.ids) ? (json.ids as string[]) : []
if (ids.length === 0) {
return NextResponse.json({ error: "Nenhum usuário selecionado." }, { status: 400 })
}
const emailInput = typeof payload.email === "string" ? payload.email.trim().toLowerCase() : ""
const nameInput = typeof payload.name === "string" ? payload.name.trim() : ""
const roleInput = typeof payload.role === "string" ? payload.role : undefined
const tenantInput = typeof payload.tenantId === "string" ? payload.tenantId.trim() : undefined
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
if (!emailInput || !emailInput.includes("@")) {
return NextResponse.json({ error: "Informe um e-mail válido" }, { status: 400 })
}
const role = normalizeRole(roleInput)
const tenantId = tenantInput || session.user.tenantId || DEFAULT_TENANT_ID
const userRole = mapToUserRole(role)
const existing = await prisma.authUser.findUnique({ where: { email: emailInput } })
if (existing) {
return NextResponse.json({ error: "Já existe um usuário com este e-mail" }, { status: 409 })
}
const password = generatePassword()
const hashedPassword = await hashPassword(password)
const user = await prisma.authUser.create({
data: {
email: emailInput,
name: nameInput || emailInput,
role,
const users = await prisma.user.findMany({
where: {
id: { in: ids },
tenantId,
accounts: {
create: {
providerId: "credential",
accountId: emailInput,
password: hashedPassword,
},
},
role: { in: [...ALLOWED_ROLES] },
},
select: {
id: true,
email: true,
name: true,
role: true,
tenantId: true,
createdAt: true,
},
})
await prisma.user.upsert({
where: { email: user.email },
update: {
name: user.name ?? user.email,
role: userRole,
tenantId,
},
create: {
email: user.email,
name: user.name ?? user.email,
role: userRole,
tenantId,
},
})
const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL
if (convexUrl) {
try {
const convex = new ConvexHttpClient(convexUrl)
await convex.mutation(api.users.ensureUser, {
tenantId,
email: emailInput,
name: nameInput || emailInput,
avatarUrl: undefined,
role: userRole,
})
} catch (error) {
console.warn("Falha ao sincronizar usuário no Convex", error)
}
if (users.length === 0) {
return NextResponse.json({ deletedIds: [] })
}
return NextResponse.json({ user, temporaryPassword: password })
const emails = users.map((user) => user.email.toLowerCase())
const authUsers = await prisma.authUser.findMany({
where: {
email: { in: emails },
},
select: {
id: true,
},
})
const authUserIds = authUsers.map((authUser) => authUser.id)
await prisma.$transaction(async (tx) => {
if (authUserIds.length > 0) {
await tx.authSession.deleteMany({ where: { userId: { in: authUserIds } } })
await tx.authAccount.deleteMany({ where: { userId: { in: authUserIds } } })
await tx.authUser.deleteMany({ where: { id: { in: authUserIds } } })
}
await tx.user.deleteMany({ where: { id: { in: users.map((user) => user.id) } } })
})
return NextResponse.json({ deletedIds: users.map((user) => user.id) })
}