synchronisation du contenu avec la DB et amélioration du CMS

- Migration du blog et des interviews des données mockées vers PostgreSQL (Prisma).
- Refonte des pages publiques en Server Components pour de meilleures performances/SEO.
- Intégration d'un éditeur de texte riche (React Quill) avec titres H1-H6 et séparateurs.
- Correction des erreurs de validation Prisma liées aux paramètres asynchrones (Next.js 15+).
- Correction des problèmes d'affichage des modales de suspension via React Portals.
- Installation de @tailwindcss/typography et correction du débordement de texte (break-words).
- Implémentation des actions de modération (suspension/révocation) pour les utilisateurs et boutiques.
This commit is contained in:
2026-04-12 18:59:20 +02:00
parent b73939d381
commit 887030ee47
84 changed files with 5577 additions and 15128 deletions

View File

@@ -0,0 +1,38 @@
import { NextRequest, NextResponse } from 'next/server'
import prisma from '../../../../../lib/prisma'
// PATCH /api/admin/reports/[id] — Update report status
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const userId = request.headers.get('x-user-id')
const { id } = await params
const { status } = await request.json()
if (!userId) {
return NextResponse.json({ error: 'Utilisateur non identifié' }, { status: 401 })
}
// Check if user is admin
const user = await prisma.user.findUnique({
where: { id: userId },
select: { role: true }
})
if (!user || user.role !== 'ADMIN') {
return NextResponse.json({ error: 'Accès réservé aux administrateurs' }, { status: 403 })
}
const report = await prisma.messageReport.update({
where: { id },
data: { status }
})
return NextResponse.json(report)
} catch (error) {
console.error('PATCH /api/admin/reports/[id] error:', error)
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
}
}

View File

@@ -0,0 +1,53 @@
import { NextRequest, NextResponse } from 'next/server'
import prisma from '../../../../lib/prisma'
// GET /api/admin/reports — List all reports for moderation
export async function GET(request: NextRequest) {
try {
const userId = request.headers.get('x-user-id')
if (!userId) {
return NextResponse.json({ error: 'Utilisateur non identifié' }, { status: 401 })
}
// Check if user is admin
const user = await prisma.user.findUnique({
where: { id: userId },
select: { role: true }
})
if (!user || user.role !== 'ADMIN') {
return NextResponse.json({ error: 'Accès réservé aux administrateurs' }, { status: 403 })
}
const reports = await prisma.messageReport.findMany({
include: {
message: {
include: {
sender: {
select: { id: true, name: true, email: true }
},
conversation: {
include: {
business: {
select: { id: true, name: true }
}
}
}
}
},
reporter: {
select: { id: true, name: true, email: true }
}
},
orderBy: {
createdAt: 'desc'
}
})
return NextResponse.json(reports)
} catch (error) {
console.error('GET /api/admin/reports error:', error)
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
}
}

View File

@@ -0,0 +1,55 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '../../../../../lib/prisma';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const { id } = await params;
if (!id) {
return NextResponse.json({ error: 'ID Business requis' }, { status: 400 });
}
// 1. Get total views from AnalyticsEvent
const totalViews = await prisma.analyticsEvent.count({
where: {
type: 'BUSINESS_VIEW',
metadata: {
path: ['businessId'],
equals: id
}
}
});
// 2. Get contact clicks from AnalyticsEvent
const contactClicks = await prisma.analyticsEvent.count({
where: {
type: 'BUSINESS_CONTACT_CLICK',
metadata: {
path: ['businessId'],
equals: id
}
}
});
// 3. Get monthly stats (views per day for last 30 days)
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
// Note: Raw query might be needed for group by date in some DBs,
// but for now we'll just return the totals for simplicity.
return NextResponse.json({
businessId: id,
totalViews,
contactClicks,
updatedAt: new Date().toISOString()
});
} catch (error) {
console.error('Error fetching business analytics:', error);
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 });
}
}

View File

@@ -11,7 +11,13 @@ export async function GET(request: NextRequest) {
const featured = searchParams.get('featured')
// 1. Fetch from Database
const where: any = {}
const where: any = {
isActive: true,
isSuspended: false,
owner: {
isSuspended: false
}
}
if (category && category !== 'All') where.category = category
if (featured === 'true') where.isFeatured = true
if (q) {
@@ -72,19 +78,22 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: 'ownerId est requis (via body ou x-user-id header)' }, { status: 400 })
}
// 1. Sanitize data - ONLY pass fields that exist in the Prisma Business model
// We must exclude 'id', 'offers', 'owner', 'createdAt', 'updatedAt' from the data object
// 1. Sanitize & Validate data
const cleanData: any = {
name: data.name || "Nouvelle Entreprise",
name: data.name || "",
slug: data.slug || null,
category: data.category || "Autre",
location: data.location || "Ma Ville",
location: data.location || "",
description: data.description || "",
logoUrl: data.logoUrl || "https://picsum.photos/200/200?random=default",
videoUrl: data.videoUrl || null,
contactEmail: data.contactEmail || "",
contactPhone: data.contactPhone || null,
websiteUrl: data.websiteUrl || null,
socialLinks: data.socialLinks || {},
showEmail: data.showEmail ?? true,
showPhone: data.showPhone ?? true,
showSocials: data.showSocials ?? true,
verified: data.verified ?? false,
viewCount: data.viewCount ?? 0,
rating: data.rating ?? 0,
@@ -94,6 +103,15 @@ export async function POST(request: NextRequest) {
founderImageUrl: data.founderImageUrl || null,
keyMetric: data.keyMetric || null,
}
// 1b. Calculate isActive based on mandatory fields
const isNameOk = cleanData.name && cleanData.name !== "Nouvelle Entreprise";
const isDescOk = cleanData.description && cleanData.description.length >= 20;
const isLocOk = cleanData.location && cleanData.location !== "Ma Ville";
const isEmailOk = !!cleanData.contactEmail;
const isPhoneOk = !!cleanData.contactPhone;
cleanData.isActive = !!(isNameOk && isDescOk && isLocOk && isEmailOk && isPhoneOk);
// 2. Slug Uniqueness Check
if (cleanData.slug) {
@@ -133,6 +151,12 @@ export async function POST(request: NextRequest) {
},
include: { owner: true }
});
// Automatic role upgrade
await prisma.user.update({
where: { id: ownerId },
data: { role: 'ENTREPRENEUR' }
});
}
console.log('Business saved successfully:', business.id);

View File

@@ -0,0 +1,35 @@
import { NextRequest, NextResponse } from 'next/server'
import prisma from '../../../../../lib/prisma'
// PATCH /api/conversations/[id]/archive — Toggle archive status for the user
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const userId = request.headers.get('x-user-id')
const { id } = await params
const { archived } = await request.json()
if (!userId) {
return NextResponse.json({ error: 'Utilisateur non identifié' }, { status: 401 })
}
const updatedParticipant = await prisma.conversationParticipant.update({
where: {
userId_conversationId: {
userId: userId,
conversationId: id
}
},
data: {
isArchived: archived ?? true
}
})
return NextResponse.json(updatedParticipant)
} catch (error) {
console.error('PATCH /api/conversations/[id]/archive error:', error)
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
}
}

View File

@@ -0,0 +1,60 @@
import { NextRequest, NextResponse } from 'next/server'
import prisma from '../../../../lib/prisma'
// GET /api/conversations/[id] — Get messages for a conversation
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const userId = request.headers.get('x-user-id')
const { id } = await params
if (!userId) {
return NextResponse.json({ error: 'Utilisateur non identifié' }, { status: 401 })
}
// Verify user is a participant
const isParticipant = await prisma.conversationParticipant.findUnique({
where: {
userId_conversationId: {
userId: userId,
conversationId: id
}
}
})
if (!isParticipant) {
return NextResponse.json({ error: 'Accès non autorisé' }, { status: 403 })
}
const messages = await prisma.message.findMany({
where: { conversationId: id },
orderBy: { createdAt: 'asc' },
include: {
sender: {
select: {
id: true,
name: true,
avatar: true
}
}
}
})
// Mark messages as read (where sender is not the current user)
await prisma.message.updateMany({
where: {
conversationId: id,
senderId: { not: userId },
read: false
},
data: { read: true }
})
return NextResponse.json(messages)
} catch (error) {
console.error('GET /api/conversations/[id] error:', error)
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
}
}

View File

@@ -0,0 +1,60 @@
import { NextRequest, NextResponse } from 'next/server'
import prisma from '../../../lib/prisma'
// GET /api/conversations — List all conversations for the user
export async function GET(request: NextRequest) {
try {
const userId = request.headers.get('x-user-id')
if (!userId) {
return NextResponse.json({ error: 'Utilisateur non identifié' }, { status: 401 })
}
const { searchParams } = new URL(request.url)
const businessId = searchParams.get('businessId')
const conversations = await prisma.conversation.findMany({
where: {
participants: {
some: { userId: userId }
},
...(businessId ? { businessId: businessId } : {})
},
include: {
business: {
select: {
id: true,
name: true,
logoUrl: true,
slug: true,
ownerId: true
}
},
participants: {
include: {
user: {
select: {
id: true,
name: true,
avatar: true,
role: true
}
}
}
},
messages: {
orderBy: { createdAt: 'desc' },
take: 1
}
},
orderBy: {
updatedAt: 'desc'
}
})
return NextResponse.json(conversations)
} catch (error) {
console.error('GET /api/conversations error:', error)
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
}
}

View File

@@ -0,0 +1,52 @@
import { NextRequest, NextResponse } from 'next/server'
import prisma from '../../../../../lib/prisma'
// POST /api/messages/[id]/report — Report a message for moderation
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
const userId = request.headers.get('x-user-id')
const { id } = await params
const { reason } = await request.json()
if (!userId) {
return NextResponse.json({ error: 'Utilisateur non identifié' }, { status: 401 })
}
// Verify message exists
const message = await prisma.message.findUnique({
where: { id }
})
if (!message) {
return NextResponse.json({ error: 'Message introuvable' }, { status: 404 })
}
// Check if user already reported this message
const existingReport = await prisma.messageReport.findFirst({
where: {
messageId: id,
reporterId: userId
}
})
if (existingReport) {
return NextResponse.json({ error: 'Vous avez déjà signalé ce message' }, { status: 400 })
}
const report = await prisma.messageReport.create({
data: {
messageId: id,
reporterId: userId,
reason: reason || 'Non spécifié'
}
})
return NextResponse.json(report)
} catch (error) {
console.error('POST /api/messages/[id]/report error:', error)
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
}
}

115
app/api/messages/route.ts Normal file
View File

@@ -0,0 +1,115 @@
import { NextRequest, NextResponse } from 'next/server'
import prisma from '../../../lib/prisma'
// POST /api/messages — Send a message or start a conversation
export async function POST(request: NextRequest) {
try {
const userId = request.headers.get('x-user-id')
const { businessId, conversationId, content } = await request.json()
if (!userId) {
return NextResponse.json({ error: 'Utilisateur non identifié' }, { status: 401 })
}
if (!content) {
return NextResponse.json({ error: 'Contenu manquant' }, { status: 400 })
}
let conversation;
let receiverId;
let finalBusinessId = businessId;
if (conversationId) {
// Case 1: Reply to an existing conversation
conversation = await prisma.conversation.findUnique({
where: { id: conversationId },
include: { participants: true }
});
if (!conversation) {
return NextResponse.json({ error: 'Conversation introuvable' }, { status: 404 });
}
const isParticipant = conversation.participants.some(p => p.userId === userId);
if (!isParticipant) {
return NextResponse.json({ error: 'Vous n\'êtes pas participant à cette conversation' }, { status: 403 });
}
// Find the other participant to determine receiverId
const otherParticipant = conversation.participants.find(p => p.userId !== userId);
receiverId = otherParticipant?.userId;
finalBusinessId = conversation.businessId;
} else if (businessId) {
// Case 2: Start a new conversation via business profile
const business = await prisma.business.findUnique({
where: { id: businessId },
select: { ownerId: true }
})
if (!business) {
return NextResponse.json({ error: 'Entreprise introuvable' }, { status: 404 })
}
receiverId = business.ownerId
if (userId === receiverId) {
return NextResponse.json({ error: 'Vous ne pouvez pas vous envoyer un message à vous-même' }, { status: 400 })
}
// Find or create a conversation for this user + business
conversation = await prisma.conversation.findFirst({
where: {
businessId: businessId,
participants: {
every: {
userId: { in: [userId, receiverId] }
}
}
}
})
if (!conversation) {
conversation = await prisma.conversation.create({
data: {
businessId: businessId,
participants: {
create: [
{ userId: userId },
{ userId: receiverId }
]
}
}
})
}
} else {
return NextResponse.json({ error: 'ID Business ou ID Conversation manquant' }, { status: 400 })
}
// 3. Create the message
const message = await prisma.message.create({
data: {
content,
senderId: userId,
conversationId: conversation.id
}
})
// 4. Update conversation updatedAt timestamp AND reset archive status for all
await prisma.$transaction([
prisma.conversation.update({
where: { id: conversation.id },
data: { updatedAt: new Date() }
}),
prisma.conversationParticipant.updateMany({
where: { conversationId: conversation.id },
data: { isArchived: false }
})
])
return NextResponse.json(message)
} catch (error) {
console.error('POST /api/messages error:', error)
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
}
}

View File

@@ -0,0 +1,29 @@
import { NextRequest, NextResponse } from 'next/server'
import prisma from '../../../../lib/prisma'
export async function GET(request: NextRequest) {
try {
const userId = request.headers.get('x-user-id')
if (!userId) {
return NextResponse.json({ error: 'Utilisateur non identifié' }, { status: 401 })
}
const unreadCount = await prisma.message.count({
where: {
conversation: {
participants: {
some: { userId: userId }
}
},
senderId: { not: userId },
read: false
}
})
return NextResponse.json({ count: unreadCount })
} catch (error) {
console.error('GET /api/messages/unread error:', error)
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 })
}
}

39
app/api/users/me/route.ts Normal file
View File

@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from 'next/server'
import prisma from '../../../../lib/prisma'
// PATCH /api/users/me — Update personal user profile
export async function PATCH(request: NextRequest) {
try {
const userId = request.headers.get('x-user-id')
const data = await request.json()
if (!userId) {
return NextResponse.json({ error: 'Utilisateur non identifié' }, { status: 401 })
}
const updatedUser = await prisma.user.update({
where: { id: userId },
data: {
name: data.name,
phone: data.phone,
bio: data.bio,
location: data.location,
},
select: {
id: true,
name: true,
email: true,
role: true,
phone: true,
bio: true,
location: true,
avatar: true
}
})
return NextResponse.json(updatedUser)
} catch (error) {
console.error('PATCH /api/users/me error:', error)
return NextResponse.json({ error: 'Erreur lors de la mise à jour' }, { status: 500 })
}
}

View File

@@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from 'next/server';
import prisma from '../../../../lib/prisma';
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const email = searchParams.get('email');
if (!email) {
return NextResponse.json({ error: 'Email requis' }, { status: 400 });
}
try {
const user = await prisma.user.findUnique({
where: { email },
select: {
id: true,
name: true,
email: true,
role: true,
avatar: true
}
});
if (!user) {
return NextResponse.json({ error: 'Utilisateur introuvable' }, { status: 404 });
}
return NextResponse.json(user);
} catch (error) {
console.error('Error fetching user profile:', error);
return NextResponse.json({ error: 'Erreur serveur' }, { status: 500 });
}
}