feat(market): add Minha Intenções tab with panel, hook, and badge
- Introduced "Minhas Intenções" tab visible only to logged-in users. - Integrated MyPurchaseIntentionsPanel and useMyPurchaseIntentions hook. - Added tab badge showing count of pending intentions. - Extended session API to include user’s main character for downstream features.
This commit is contained in:
1 parent
f35fee944d
commit
7f42def478
55 files changed
+4906
-95
No files matched your search
@@ -0,0 +1,265 @@
|
||||
/**
|
||||
* GET /api/chats/[chatId]/messages - Busca mensagens do chat
|
||||
* POST /api/chats/[chatId]/messages - Envia mensagem (fallback se Socket.io não estiver disponível)
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireAuth } from "@/lib/auth/middleware";
|
||||
import { connectMongoDB } from "@/lib/mongodb/connection";
|
||||
import { Chat } from "@/lib/mongodb/models/Chat";
|
||||
import { Message } from "@/lib/mongodb/models/Message";
|
||||
import { sendMessageSchema, getMessagesSchema } from "@/lib/validation/chat-schemas";
|
||||
import { secureLogger } from "@/lib/secure-logger";
|
||||
|
||||
/**
|
||||
* GET /api/chats/[chatId]/messages
|
||||
* Busca mensagens do chat com paginação
|
||||
*/
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ chatId: string }> }
|
||||
) {
|
||||
try {
|
||||
const authResult = await requireAuth(request);
|
||||
if (authResult instanceof NextResponse) return authResult;
|
||||
const auth = authResult;
|
||||
|
||||
const { chatId } = await params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
|
||||
const queryValidation = getMessagesSchema.safeParse({
|
||||
page: searchParams.get("page"),
|
||||
limit: searchParams.get("limit"),
|
||||
});
|
||||
|
||||
if (!queryValidation.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Parâmetros inválidos",
|
||||
details: queryValidation.error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { page, limit } = queryValidation.data;
|
||||
|
||||
await connectMongoDB();
|
||||
|
||||
// Verificar se chat existe e usuário tem acesso
|
||||
const chat = await Chat.findOne({ chat_id: chatId });
|
||||
|
||||
if (!chat) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Chat não encontrado" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
if (chat.buyer_id !== auth.userId && chat.seller_id !== auth.userId) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Você não tem permissão para acessar este chat" },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Buscar mensagens (não deletadas)
|
||||
const skip = (page - 1) * limit;
|
||||
const messages = await Message.find({
|
||||
chat_id: chatId,
|
||||
deleted_at: null,
|
||||
})
|
||||
.sort({ created_at: -1 })
|
||||
.skip(skip)
|
||||
.limit(limit);
|
||||
|
||||
const total = await Message.countDocuments({
|
||||
chat_id: chatId,
|
||||
deleted_at: null,
|
||||
});
|
||||
|
||||
// Marcar mensagens como lidas
|
||||
await Message.updateMany(
|
||||
{
|
||||
chat_id: chatId,
|
||||
sender_id: { $ne: auth.userId },
|
||||
read_at: null,
|
||||
},
|
||||
{
|
||||
$set: { read_at: new Date() },
|
||||
}
|
||||
);
|
||||
|
||||
// Atualizar contador de não lidas
|
||||
if (chat.buyer_id === auth.userId) {
|
||||
chat.buyer_unread_count = 0;
|
||||
} else {
|
||||
chat.seller_unread_count = 0;
|
||||
}
|
||||
await chat.save();
|
||||
|
||||
// Serializar mensagens (ordem reversa para mostrar mais antigas primeiro)
|
||||
const serializedMessages = messages
|
||||
.reverse()
|
||||
.map((msg) => ({
|
||||
_id: msg._id.toString(),
|
||||
chat_id: msg.chat_id,
|
||||
sender_id: msg.sender_id,
|
||||
content: msg.content,
|
||||
created_at: msg.created_at.toISOString(),
|
||||
read_at: msg.read_at?.toISOString() || null,
|
||||
edited_at: msg.edited_at?.toISOString() || null,
|
||||
message_type: msg.message_type,
|
||||
metadata: msg.metadata || null,
|
||||
}));
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
messages: serializedMessages,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
totalPages: Math.ceil(total / limit),
|
||||
},
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error) {
|
||||
secureLogger.error("❌ Erro ao buscar mensagens", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Erro ao buscar mensagens" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/chats/[chatId]/messages
|
||||
* Envia mensagem (fallback se Socket.io não estiver disponível)
|
||||
*/
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ chatId: string }> }
|
||||
) {
|
||||
try {
|
||||
const authResult = await requireAuth(request);
|
||||
if (authResult instanceof NextResponse) return authResult;
|
||||
const auth = authResult;
|
||||
|
||||
const { chatId } = await params;
|
||||
const body = await request.json();
|
||||
const validationResult = sendMessageSchema.safeParse(body);
|
||||
|
||||
if (!validationResult.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Dados inválidos",
|
||||
details: validationResult.error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { content } = validationResult.data;
|
||||
|
||||
await connectMongoDB();
|
||||
|
||||
// Verificar se chat existe e usuário tem acesso
|
||||
const chat = await Chat.findOne({ chat_id: chatId });
|
||||
|
||||
if (!chat) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Chat não encontrado" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
if (chat.buyer_id !== auth.userId && chat.seller_id !== auth.userId) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Você não tem permissão para enviar mensagens neste chat" },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Criar mensagem
|
||||
const message = new Message({
|
||||
chat_id: chatId,
|
||||
sender_id: auth.userId,
|
||||
content,
|
||||
message_type: "text",
|
||||
});
|
||||
|
||||
await message.save();
|
||||
|
||||
// Atualizar chat
|
||||
chat.last_message_at = new Date();
|
||||
chat.last_message_preview = content.substring(0, 100);
|
||||
|
||||
if (chat.buyer_id === auth.userId) {
|
||||
chat.seller_unread_count += 1;
|
||||
} else {
|
||||
chat.buyer_unread_count += 1;
|
||||
}
|
||||
|
||||
await chat.save();
|
||||
|
||||
// Tentar enviar via Socket.io se disponível
|
||||
try {
|
||||
const { getSocketIO } = await import("@/lib/socket/server");
|
||||
const io = getSocketIO();
|
||||
if (io) {
|
||||
io.to(`chat:${chatId}`).emit("new_message", {
|
||||
message: {
|
||||
_id: message._id.toString(),
|
||||
chat_id: message.chat_id,
|
||||
sender_id: message.sender_id,
|
||||
content: message.content,
|
||||
created_at: message.created_at.toISOString(),
|
||||
read_at: message.read_at?.toISOString() || null,
|
||||
message_type: message.message_type,
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (socketError) {
|
||||
// Socket.io não disponível, mensagem já foi salva
|
||||
secureLogger.warn("Socket.io não disponível, mensagem salva via REST", {
|
||||
chatId,
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
message: {
|
||||
_id: message._id.toString(),
|
||||
chat_id: message.chat_id,
|
||||
sender_id: message.sender_id,
|
||||
content: message.content,
|
||||
created_at: message.created_at.toISOString(),
|
||||
read_at: message.read_at?.toISOString() || null,
|
||||
message_type: message.message_type,
|
||||
},
|
||||
},
|
||||
{ status: 201 }
|
||||
);
|
||||
} catch (error) {
|
||||
secureLogger.error("❌ Erro ao enviar mensagem", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Erro ao enviar mensagem" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* GET /api/chats/[chatId] - Busca detalhes de um chat específico
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireAuth } from "@/lib/auth/middleware";
|
||||
import { connectMongoDB } from "@/lib/mongodb/connection";
|
||||
import { Chat } from "@/lib/mongodb/models/Chat";
|
||||
import { secureLogger } from "@/lib/secure-logger";
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ chatId: string }> }
|
||||
) {
|
||||
try {
|
||||
const authResult = await requireAuth(request);
|
||||
if (authResult instanceof NextResponse) return authResult;
|
||||
const auth = authResult;
|
||||
|
||||
const { chatId } = await params;
|
||||
|
||||
await connectMongoDB();
|
||||
|
||||
// Buscar chat
|
||||
const chat = await Chat.findOne({ chat_id: chatId });
|
||||
|
||||
if (!chat) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Chat não encontrado" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Verificar se o usuário pertence ao chat
|
||||
if (chat.buyer_id !== auth.userId && chat.seller_id !== auth.userId) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Você não tem permissão para acessar este chat" },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
chat: {
|
||||
chat_id: chat.chat_id,
|
||||
listing_id: chat.listing_id,
|
||||
buyer_id: chat.buyer_id,
|
||||
seller_id: chat.seller_id,
|
||||
created_at: chat.created_at.toISOString(),
|
||||
updated_at: chat.updated_at.toISOString(),
|
||||
last_message_at: chat.last_message_at?.toISOString() || null,
|
||||
last_message_preview: chat.last_message_preview,
|
||||
buyer_unread_count: chat.buyer_unread_count,
|
||||
seller_unread_count: chat.seller_unread_count,
|
||||
is_active: chat.is_active,
|
||||
listing_cache: chat.listing_cache,
|
||||
buyer_cache: chat.buyer_cache,
|
||||
seller_cache: chat.seller_cache,
|
||||
},
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error) {
|
||||
secureLogger.error("❌ Erro ao buscar chat", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Erro ao buscar chat" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* POST /api/chats/mark-all-read
|
||||
* Marca todas as mensagens de todos os chats do usuário como lidas
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireAuth } from "@/lib/auth/middleware";
|
||||
import { connectMongoDB } from "@/lib/mongodb/connection";
|
||||
import { Chat } from "@/lib/mongodb/models/Chat";
|
||||
import { Message } from "@/lib/mongodb/models/Message";
|
||||
import { secureLogger } from "@/lib/secure-logger";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const authResult = await requireAuth(request);
|
||||
if (authResult instanceof NextResponse) return authResult;
|
||||
const auth = authResult;
|
||||
|
||||
await connectMongoDB();
|
||||
|
||||
// Buscar todos os chats do usuário
|
||||
const chats = await Chat.find({
|
||||
$or: [{ buyer_id: auth.userId }, { seller_id: auth.userId }],
|
||||
is_active: true,
|
||||
});
|
||||
|
||||
// Para cada chat, marcar mensagens não lidas como lidas
|
||||
const updatePromises = chats.map(async (chat) => {
|
||||
const chatId = chat.chat_id;
|
||||
|
||||
// Marcar mensagens como lidas
|
||||
await Message.updateMany(
|
||||
{
|
||||
chat_id: chatId,
|
||||
sender_id: { $ne: auth.userId },
|
||||
read_at: null,
|
||||
},
|
||||
{
|
||||
$set: { read_at: new Date() },
|
||||
}
|
||||
);
|
||||
|
||||
// Zerar contador de não lidas
|
||||
if (chat.buyer_id === auth.userId) {
|
||||
chat.buyer_unread_count = 0;
|
||||
} else {
|
||||
chat.seller_unread_count = 0;
|
||||
}
|
||||
|
||||
return chat.save();
|
||||
});
|
||||
|
||||
await Promise.all(updatePromises);
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
message: "Todos os chats marcados como lidos",
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error) {
|
||||
secureLogger.error("❌ Erro ao marcar chats como lidos", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Erro ao marcar como lido" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
/**
|
||||
* GET /api/chats - Lista chats do usuário
|
||||
* POST /api/chats - Cria novo chat
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireAuth } from "@/lib/auth/middleware";
|
||||
import { connectMongoDB } from "@/lib/mongodb/connection";
|
||||
import { Chat } from "@/lib/mongodb/models/Chat";
|
||||
import { createChatSchema } from "@/lib/validation/chat-schemas";
|
||||
import { getListingById } from "@/lib/prisma/queries/listings";
|
||||
import { getMainCharacter } from "@/lib/prisma/queries/characters";
|
||||
import { getUserById } from "@/lib/prisma/queries/users";
|
||||
import { secureLogger } from "@/lib/secure-logger";
|
||||
|
||||
/**
|
||||
* GET /api/chats
|
||||
* Lista todos os chats do usuário autenticado
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const authResult = await requireAuth(request);
|
||||
if (authResult instanceof NextResponse) return authResult;
|
||||
const auth = authResult;
|
||||
|
||||
await connectMongoDB();
|
||||
|
||||
// Buscar todos os chats do usuário (como comprador ou vendedor)
|
||||
const chats = await Chat.find({
|
||||
$or: [{ buyer_id: auth.userId }, { seller_id: auth.userId }],
|
||||
is_active: true,
|
||||
})
|
||||
.sort({ updated_at: -1 })
|
||||
.limit(100);
|
||||
|
||||
// Serializar datas
|
||||
const serializedChats = chats.map((chat) => ({
|
||||
chat_id: chat.chat_id,
|
||||
listing_id: chat.listing_id,
|
||||
buyer_id: chat.buyer_id,
|
||||
seller_id: chat.seller_id,
|
||||
created_at: chat.created_at.toISOString(),
|
||||
updated_at: chat.updated_at.toISOString(),
|
||||
last_message_at: chat.last_message_at?.toISOString() || null,
|
||||
last_message_preview: chat.last_message_preview,
|
||||
buyer_unread_count: chat.buyer_unread_count,
|
||||
seller_unread_count: chat.seller_unread_count,
|
||||
is_active: chat.is_active,
|
||||
listing_cache: chat.listing_cache,
|
||||
buyer_cache: chat.buyer_cache,
|
||||
seller_cache: chat.seller_cache,
|
||||
}));
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
chats: serializedChats,
|
||||
count: serializedChats.length,
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error) {
|
||||
secureLogger.error("❌ Erro ao buscar chats", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Erro ao buscar chats" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/chats
|
||||
* Cria um novo chat entre comprador e vendedor
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const authResult = await requireAuth(request);
|
||||
if (authResult instanceof NextResponse) return authResult;
|
||||
const auth = authResult;
|
||||
|
||||
const body = await request.json();
|
||||
const validationResult = createChatSchema.safeParse(body);
|
||||
|
||||
if (!validationResult.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: "Dados inválidos",
|
||||
details: validationResult.error.issues,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { listing_id, buyer_message } = validationResult.data;
|
||||
|
||||
await connectMongoDB();
|
||||
|
||||
// Buscar anúncio
|
||||
const listing = await getListingById(listing_id);
|
||||
if (!listing) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Anúncio não encontrado" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Verificar se não é o próprio vendedor
|
||||
if (listing.seller_id === auth.userId) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Você não pode criar um chat com você mesmo" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Verificar se anúncio está ativo
|
||||
if (listing.listing_status !== "active") {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Anúncio não está disponível para chat" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Gerar chat_id único
|
||||
const chat_id = `${listing_id}_${auth.userId}_${listing.seller_id}`;
|
||||
|
||||
// Verificar se chat já existe
|
||||
let chat = await Chat.findOne({ chat_id });
|
||||
|
||||
if (chat) {
|
||||
// Chat já existe, retornar
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
chat: {
|
||||
chat_id: chat.chat_id,
|
||||
listing_id: chat.listing_id,
|
||||
buyer_id: chat.buyer_id,
|
||||
seller_id: chat.seller_id,
|
||||
created_at: chat.created_at.toISOString(),
|
||||
updated_at: chat.updated_at.toISOString(),
|
||||
last_message_at: chat.last_message_at?.toISOString() || null,
|
||||
last_message_preview: chat.last_message_preview,
|
||||
buyer_unread_count: chat.buyer_unread_count,
|
||||
seller_unread_count: chat.seller_unread_count,
|
||||
is_active: chat.is_active,
|
||||
listing_cache: chat.listing_cache,
|
||||
buyer_cache: chat.buyer_cache,
|
||||
seller_cache: chat.seller_cache,
|
||||
},
|
||||
already_exists: true,
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
|
||||
// Buscar dados do comprador
|
||||
const buyer = await getUserById(auth.userId);
|
||||
if (!buyer) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Usuário não encontrado" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
const buyerCharacter = await getMainCharacter(auth.userId);
|
||||
|
||||
// Buscar dados do vendedor
|
||||
const seller = await getUserById(listing.seller_id);
|
||||
if (!seller) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Vendedor não encontrado" },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
const sellerCharacter = await getMainCharacter(listing.seller_id);
|
||||
|
||||
// Criar chat
|
||||
chat = new Chat({
|
||||
chat_id,
|
||||
listing_id,
|
||||
buyer_id: auth.userId,
|
||||
seller_id: listing.seller_id,
|
||||
listing_cache: {
|
||||
item_name: listing.item_name,
|
||||
item_image_url: null, // Imagem será obtida via item_id se necessário
|
||||
price_pix: listing.price_pix ? Number(listing.price_pix) : null,
|
||||
price_tibia_coins: listing.price_tibia_coins || null,
|
||||
price_gold_coins: listing.price_gold_coins ? Number(listing.price_gold_coins) : null,
|
||||
server_name: listing.server_name,
|
||||
listing_status: listing.listing_status,
|
||||
},
|
||||
buyer_cache: {
|
||||
user_id: buyer.user_id,
|
||||
username: buyer.username,
|
||||
character_name: buyerCharacter?.character_name || null,
|
||||
},
|
||||
seller_cache: {
|
||||
user_id: seller.user_id,
|
||||
username: seller.username,
|
||||
character_name: sellerCharacter?.character_name || null,
|
||||
},
|
||||
});
|
||||
|
||||
await chat.save();
|
||||
|
||||
// Se houver mensagem inicial, criar
|
||||
if (buyer_message && buyer_message.trim().length > 0) {
|
||||
const { Message } = await import("@/lib/mongodb/models/Message");
|
||||
const message = new Message({
|
||||
chat_id,
|
||||
sender_id: auth.userId,
|
||||
content: buyer_message.trim(),
|
||||
message_type: "text",
|
||||
});
|
||||
await message.save();
|
||||
|
||||
// Atualizar chat
|
||||
chat.last_message_at = new Date();
|
||||
chat.last_message_preview = buyer_message.substring(0, 100);
|
||||
chat.seller_unread_count = 1;
|
||||
await chat.save();
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
chat: {
|
||||
chat_id: chat.chat_id,
|
||||
listing_id: chat.listing_id,
|
||||
buyer_id: chat.buyer_id,
|
||||
seller_id: chat.seller_id,
|
||||
created_at: chat.created_at.toISOString(),
|
||||
updated_at: chat.updated_at.toISOString(),
|
||||
last_message_at: chat.last_message_at?.toISOString() || null,
|
||||
last_message_preview: chat.last_message_preview,
|
||||
buyer_unread_count: chat.buyer_unread_count,
|
||||
seller_unread_count: chat.seller_unread_count,
|
||||
is_active: chat.is_active,
|
||||
listing_cache: chat.listing_cache,
|
||||
buyer_cache: chat.buyer_cache,
|
||||
seller_cache: chat.seller_cache,
|
||||
},
|
||||
already_exists: false,
|
||||
},
|
||||
{ status: 201 }
|
||||
);
|
||||
} catch (error) {
|
||||
secureLogger.error("❌ Erro ao criar chat", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Erro ao criar chat" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* GET /api/chats/unread-count
|
||||
* Retorna contagem de usuários únicos com mensagens não vistas
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { requireAuth } from "@/lib/auth/middleware";
|
||||
import { connectMongoDB } from "@/lib/mongodb/connection";
|
||||
import { Chat } from "@/lib/mongodb/models/Chat";
|
||||
import { secureLogger } from "@/lib/secure-logger";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const authResult = await requireAuth(request);
|
||||
if (authResult instanceof NextResponse) return authResult;
|
||||
const auth = authResult;
|
||||
|
||||
await connectMongoDB();
|
||||
|
||||
// Buscar todos os chats do usuário
|
||||
const chats = await Chat.find({
|
||||
$or: [{ buyer_id: auth.userId }, { seller_id: auth.userId }],
|
||||
is_active: true,
|
||||
});
|
||||
|
||||
// Calcular contagem de usuários únicos com mensagens não vistas
|
||||
const uniqueUsersWithUnread = new Set<number>();
|
||||
|
||||
chats.forEach((chat) => {
|
||||
let unreadCount = 0;
|
||||
let otherUserId: number;
|
||||
|
||||
if (chat.buyer_id === auth.userId) {
|
||||
unreadCount = chat.buyer_unread_count;
|
||||
otherUserId = chat.seller_id;
|
||||
} else {
|
||||
unreadCount = chat.seller_unread_count;
|
||||
otherUserId = chat.buyer_id;
|
||||
}
|
||||
|
||||
// Se há mensagens não vistas, adicionar o outro usuário ao Set
|
||||
if (unreadCount > 0) {
|
||||
uniqueUsersWithUnread.add(otherUserId);
|
||||
}
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
count: uniqueUsersWithUnread.size,
|
||||
totalUnreadMessages: chats.reduce((total, chat) => {
|
||||
if (chat.buyer_id === auth.userId) {
|
||||
return total + chat.buyer_unread_count;
|
||||
}
|
||||
return total + chat.seller_unread_count;
|
||||
}, 0),
|
||||
},
|
||||
{ status: 200 }
|
||||
);
|
||||
} catch (error) {
|
||||
secureLogger.error("❌ Erro ao buscar contagem de chats não lidos", {
|
||||
error: error instanceof Error ? error.message : "Erro desconhecido",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{ success: false, error: "Erro ao buscar contagem" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user