77 lines
2.6 KiB
TypeScript
77 lines
2.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import prisma from '@/lib/prisma'
|
|
|
|
// GET /api/offers — optionally filter by businessId
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
const { searchParams } = new URL(request.url)
|
|
const businessId = searchParams.get('businessId')
|
|
|
|
const where: Record<string, unknown> = {}
|
|
if (businessId) where.businessId = businessId
|
|
|
|
const offers = await prisma.offer.findMany({
|
|
where,
|
|
include: { business: true },
|
|
orderBy: { createdAt: 'desc' },
|
|
})
|
|
return NextResponse.json(offers)
|
|
} catch (error) {
|
|
console.error('GET /api/offers error:', error)
|
|
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
// POST /api/offers
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const body = await request.json()
|
|
const { businessId } = body
|
|
|
|
if (!businessId) {
|
|
return NextResponse.json({ error: 'businessId manquant' }, { status: 400 })
|
|
}
|
|
|
|
// 1. Fetch business and their plan's limit
|
|
const business = await prisma.business.findUnique({
|
|
where: { id: businessId },
|
|
include: {
|
|
_count: { select: { offers: true } }
|
|
}
|
|
})
|
|
|
|
if (!business) {
|
|
return NextResponse.json({ error: 'Entreprise non trouvée' }, { status: 404 })
|
|
}
|
|
|
|
// Fetch the specific limit for this tier from the database
|
|
const planDetails = await prisma.pricingPlan.findUnique({
|
|
where: { tier: business.plan }
|
|
})
|
|
|
|
if (!planDetails) {
|
|
return NextResponse.json({ error: 'Configuration du forfait introuvable' }, { status: 500 })
|
|
}
|
|
|
|
// 2. Enforce limits
|
|
const currentCount = business._count.offers
|
|
const offerLimit = planDetails.offerLimit
|
|
|
|
if (currentCount >= offerLimit) {
|
|
return NextResponse.json({
|
|
error: `Limite d'offres atteinte (${offerLimit} max pour le plan ${planDetails.name}). Veuillez passer au plan supérieur pour publier plus d'offres.`
|
|
}, { status: 403 })
|
|
}
|
|
|
|
// 3. Create offer
|
|
const offer = await prisma.offer.create({
|
|
data: body,
|
|
include: { business: true },
|
|
})
|
|
return NextResponse.json(offer, { status: 201 })
|
|
} catch (error) {
|
|
console.error('POST /api/offers error:', error)
|
|
return NextResponse.json({ error: 'Erreur lors de la création' }, { status: 500 })
|
|
}
|
|
}
|