admin/companies: melhorar criação/edição\n\n- Aceita isAvulso e contractedHoursPerMonth no POST\n- Retorna 409 para duplicidade (slug/provisioningCode)\n- Retorna 409 para duplicidade no PATCH

This commit is contained in:
Esdras Renan 2025-10-16 17:29:08 -03:00
parent e6e343fe38
commit f60a48e7b3
2 changed files with 22 additions and 2 deletions

View file

@ -2,6 +2,7 @@ import { NextResponse } from "next/server"
import { randomBytes } from "crypto"
import { prisma } from "@/lib/prisma"
import { Prisma } from "@prisma/client"
import { assertStaffSession } from "@/lib/auth-server"
import { isAdmin } from "@/lib/authz"
@ -27,13 +28,15 @@ export async function POST(request: Request) {
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, cnpj, domain, phone, description, address } = body ?? {}
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 })
}
@ -46,7 +49,14 @@ export async function POST(request: Request) {
name: String(name),
slug: String(slug),
provisioningCode,
// Campos opcionais (isAvulso, contractedHoursPerMonth) podem ser definidos via PATCH posteriormente.
// 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,
@ -57,6 +67,13 @@ export async function POST(request: Request) {
return NextResponse.json({ company })
} catch (error) {
console.error("Failed to create company", error)
if (error instanceof Prisma.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 }
)
}
return NextResponse.json({ error: "Falha ao criar empresa" }, { status: 500 })
}
}