feat: expand admin companies and users modules
This commit is contained in:
parent
a043b1203c
commit
2e3b46a7b5
31 changed files with 5626 additions and 2003 deletions
|
|
@ -1,22 +1,31 @@
|
|||
import { NextResponse } from "next/server"
|
||||
import { randomBytes } from "crypto"
|
||||
import { ZodError } from "zod"
|
||||
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library"
|
||||
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { assertStaffSession } from "@/lib/auth-server"
|
||||
import { isAdmin } from "@/lib/authz"
|
||||
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library"
|
||||
import { syncConvexCompany } from "@/server/companies-sync"
|
||||
import {
|
||||
buildCompanyData,
|
||||
fetchCompaniesByTenant,
|
||||
formatZodError,
|
||||
normalizeCompany,
|
||||
sanitizeCompanyInput,
|
||||
} from "@/server/company-service"
|
||||
|
||||
export const runtime = "nodejs"
|
||||
|
||||
const DEFAULT_TENANT_ID = "tenant-atlas"
|
||||
|
||||
export async function GET() {
|
||||
const session = await assertStaffSession()
|
||||
if (!session) return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
|
||||
|
||||
const companies = await prisma.company.findMany({
|
||||
orderBy: { name: "asc" },
|
||||
})
|
||||
return NextResponse.json({ companies })
|
||||
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
|
||||
const companies = await fetchCompaniesByTenant(tenantId)
|
||||
return NextResponse.json({ companies: companies.map(normalizeCompany) })
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
|
|
@ -26,43 +35,16 @@ export async function POST(request: Request) {
|
|||
return NextResponse.json({ error: "Apenas administradores podem criar empresas" }, { status: 403 })
|
||||
}
|
||||
|
||||
const body = (await request.json()) as Partial<{
|
||||
name: string
|
||||
slug: string
|
||||
isAvulso: boolean
|
||||
contractedHoursPerMonth: number | string | null
|
||||
cnpj: string | null
|
||||
domain: string | null
|
||||
phone: string | null
|
||||
description: string | null
|
||||
address: string | null
|
||||
}>
|
||||
const { name, slug, isAvulso, contractedHoursPerMonth, cnpj, domain, phone, description, address } = body ?? {}
|
||||
if (!name || !slug) {
|
||||
return NextResponse.json({ error: "Nome e slug são obrigatórios" }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const rawBody = await request.json()
|
||||
const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
|
||||
const form = sanitizeCompanyInput(rawBody, tenantId)
|
||||
const provisioningCode = randomBytes(32).toString("hex")
|
||||
|
||||
const company = await prisma.company.create({
|
||||
data: {
|
||||
tenantId: session.user.tenantId ?? "tenant-atlas",
|
||||
name: String(name),
|
||||
slug: String(slug),
|
||||
...buildCompanyData(form, tenantId),
|
||||
provisioningCode,
|
||||
// Campos opcionais
|
||||
isAvulso: Boolean(isAvulso ?? false),
|
||||
contractedHoursPerMonth:
|
||||
typeof contractedHoursPerMonth === "number"
|
||||
? contractedHoursPerMonth
|
||||
: contractedHoursPerMonth
|
||||
? Number(contractedHoursPerMonth)
|
||||
: null,
|
||||
cnpj: cnpj ? String(cnpj) : null,
|
||||
domain: domain ? String(domain) : null,
|
||||
phone: phone ? String(phone) : null,
|
||||
description: description ? String(description) : null,
|
||||
address: address ? String(address) : null,
|
||||
},
|
||||
})
|
||||
|
||||
|
|
@ -78,16 +60,18 @@ export async function POST(request: Request) {
|
|||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ company })
|
||||
return NextResponse.json({ company: normalizeCompany(company) })
|
||||
} catch (error) {
|
||||
console.error("Failed to create company", error)
|
||||
if (error instanceof ZodError) {
|
||||
return NextResponse.json({ error: "Dados inválidos", issues: formatZodError(error) }, { status: 422 })
|
||||
}
|
||||
if (error instanceof PrismaClientKnownRequestError && error.code === "P2002") {
|
||||
// Duplicidade de slug por tenant ou provisioningCode único
|
||||
return NextResponse.json(
|
||||
{ error: "Já existe uma empresa com este slug ou código de provisionamento." },
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
console.error("Failed to create company", error)
|
||||
return NextResponse.json({ error: "Falha ao criar empresa" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue