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:
Evandro Fonseca Junior committed 2025-11-07 17:25:51 -03:00
1 parent f35fee944d
commit 7f42def478
55 files changed
+4906 -95

No files matched your search

+35 -1
View File
@@ -19,8 +19,11 @@ import { useMarketTelemetry } from "@/lib/hooks/use-telemetry";
import { AdCard } from "@/components/marketplace/AdCard";
import { CreateAdModal } from "@/components/marketplace/CreateAdModal";
import { MyAdsPanel } from "@/components/marketplace/MyAdsPanel";
import { MyPurchaseIntentionsPanel } from "@/components/marketplace/MyPurchaseIntentionsPanel";
import { useSession } from "@/lib/hooks/use-session";
import { useListings, useInvalidateListings } from "@/lib/hooks/use-listings";
import { useMyPurchaseIntentions } from "@/lib/hooks/use-purchase-intentions";
import { useLocale } from "next-intl";
interface Listing {
listing_id: number;
@@ -53,6 +56,7 @@ export default function MarketClient({ initial }: { initial: InitialData }) {
const { user } = useSession();
const { trackSearch, trackFilter, trackPageView } = useMarketTelemetry();
const invalidateListings = useInvalidateListings();
const locale = useLocale();
const [page, setPage] = useState<number>(initial.page || 1);
const [pageSize] = useState<number>(initial.pageSize || 20);
@@ -152,11 +156,14 @@ export default function MarketClient({ initial }: { initial: InitialData }) {
)}
</div>
{/* Tabs para Explorar e Meus Anúncios */}
{/* Tabs para Explorar, Meus Anúncios e Minhas Intenções */}
<Tabs value={activeTab} onValueChange={setActiveTab}>
<TabsList>
<TabsTrigger value="explore">Explorar</TabsTrigger>
{user && <TabsTrigger value="my-ads">Meus Anúncios</TabsTrigger>}
{user && (
<MyPurchaseIntentionsTabTrigger />
)}
</TabsList>
{/* Aba: Explorar Anúncios */}
@@ -399,8 +406,35 @@ export default function MarketClient({ initial }: { initial: InitialData }) {
<MyAdsPanel />
</TabsContent>
)}
{/* Aba: Minhas Intenções */}
{user && (
<TabsContent value="my-intentions" className="mt-6">
<MyPurchaseIntentionsPanel locale={locale} />
</TabsContent>
)}
</Tabs>
</div>
);
}
// Componente para o trigger da tab com badge de contador
function MyPurchaseIntentionsTabTrigger() {
const { intentions } = useMyPurchaseIntentions();
const pendingCount = intentions.filter((i) => i.status === "pending").length;
return (
<TabsTrigger value="my-intentions" className="relative">
Minhas Intenções
{pendingCount > 0 && (
<Badge
variant="destructive"
className="ml-2 h-5 min-w-5 px-1.5 text-xs"
>
{pendingCount}
</Badge>
)}
</TabsTrigger>
);
}
+5
View File
@@ -3,6 +3,7 @@ import { cookies } from "next/headers";
import { secureLogger } from "@/lib/secure-logger";
import { getSession, refreshSession, deleteSession } from "@/lib/redis/session";
import { verifyAccessToken } from "@/lib/auth/jwt";
import { getMainCharacter } from "@/lib/prisma/queries/characters";
/**
* GET /api/auth/session
@@ -65,6 +66,9 @@ export async function GET(request: NextRequest) {
// Atualizar TTL da sessão
await refreshSession(sessionId);
// Buscar personagem principal do usuário
const mainCharacter = await getMainCharacter(session.userId);
return NextResponse.json(
{
success: true,
@@ -73,6 +77,7 @@ export async function GET(request: NextRequest) {
userId: session.userId,
username: session.username,
email: session.email,
characterName: mainCharacter?.character_name || null,
},
},
{ status: 200 }
+265
View File
@@ -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 }
);
}
}
+76
View File
@@ -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 }
);
}
}
+72
View File
@@ -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 }
);
}
}
+265
View File
@@ -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 }
);
}
}
+70
View File
@@ -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 }
);
}
}
+28 -6
View File
@@ -6,6 +6,7 @@ import {
createPurchaseIntention,
getPurchaseIntentionsByListing,
hasPendingIntention,
getPendingIntentionByBuyerAndListing,
} from "@/lib/prisma/queries/purchase-intentions";
import { createNotification } from "@/lib/prisma/queries/notifications";
import { trackEvent } from "@/lib/prisma/queries/telemetry";
@@ -94,12 +95,33 @@ export async function POST(
}
// Verificar se já existe uma intenção pendente
const alreadyHasPending = await hasPendingIntention(listingId, auth.userId);
if (alreadyHasPending) {
return NextResponse.json(
{ success: false, error: "Você já possui uma intenção de compra pendente para este anúncio" },
{ status: 400 }
);
const existingIntention = await getPendingIntentionByBuyerAndListing(listingId, auth.userId);
if (existingIntention) {
// Se já existe e ainda pode trocar o método
if (existingIntention.payment_method_change_count < 1) {
// Permite atualizar o método via endpoint específico
return NextResponse.json(
{
success: false,
error: "Você já possui uma intenção de compra pendente para este anúncio",
existing_intention_id: existingIntention.intention_id,
can_change_payment_method: true,
payment_method_change_count: existingIntention.payment_method_change_count,
message: "Use o endpoint PATCH /api/purchase-intentions/[intentionId]/payment-method para trocar o método de pagamento",
},
{ status: 400 }
);
} else {
// Já atingiu o limite de trocas
return NextResponse.json(
{
success: false,
error: "Você já possui uma intenção de compra pendente para este anúncio e atingiu o limite de trocas de método de pagamento",
existing_intention_id: existingIntention.intention_id,
},
{ status: 400 }
);
}
}
// Criar intenção de compra
+28 -6
View File
@@ -6,6 +6,7 @@ import { createNotification } from "@/lib/prisma/queries/notifications";
import {
createPurchaseIntention,
hasPendingIntention,
getPendingIntentionByBuyerAndListing,
} from "@/lib/prisma/queries/purchase-intentions";
import { trackEvent } from "@/lib/prisma/queries/telemetry";
@@ -98,12 +99,33 @@ export async function POST(
}
// Verificar se já existe uma intenção pendente
const alreadyHasPending = await hasPendingIntention(listingId, auth.userId);
if (alreadyHasPending) {
return NextResponse.json(
{ success: false, error: "Você já possui uma intenção de compra pendente para este anúncio" },
{ status: 400 }
);
const existingIntention = await getPendingIntentionByBuyerAndListing(listingId, auth.userId);
if (existingIntention) {
// Se já existe e ainda pode trocar o método
if (existingIntention.payment_method_change_count < 1) {
// Permite atualizar o método via endpoint específico
return NextResponse.json(
{
success: false,
error: "Você já possui uma intenção de compra pendente para este anúncio",
existing_intention_id: existingIntention.intention_id,
can_change_payment_method: true,
payment_method_change_count: existingIntention.payment_method_change_count,
message: "Use o endpoint PATCH /api/purchase-intentions/[intentionId]/payment-method para trocar o método de pagamento",
},
{ status: 400 }
);
} else {
// Já atingiu o limite de trocas
return NextResponse.json(
{
success: false,
error: "Você já possui uma intenção de compra pendente para este anúncio e atingiu o limite de trocas de método de pagamento",
existing_intention_id: existingIntention.intention_id,
},
{ status: 400 }
);
}
}
// Criar intenção de compra ao invés de mudar status diretamente
+11 -1
View File
@@ -6,6 +6,7 @@ import {
updateListing,
deleteListing,
} from "@/lib/prisma/queries/listings";
import { hasPendingIntention } from "@/lib/prisma/queries/purchase-intentions";
import { updateListingSchema } from "@/lib/validation-schemas";
/**
@@ -17,6 +18,7 @@ export async function GET(
{ params }: { params: Promise<{ id: string }> }
) {
try {
const auth = await optionalAuth(request);
const { id } = await params;
const listingId = parseInt(id, 10);
@@ -42,10 +44,18 @@ export async function GET(
);
}
const hasPendingForUser =
auth && auth.userId
? await hasPendingIntention(listingId, auth.userId)
: false;
return NextResponse.json(
{
success: true,
listing,
listing: {
...listing,
has_pending_intention_for_current_user: hasPendingForUser,
},
},
{ status: 200 }
);
+19 -1
View File
@@ -13,6 +13,7 @@ import {
getActiveListings,
} from "@/lib/prisma/queries/listings";
import { isServerActive } from "@/lib/prisma/queries/servers";
import { getPendingIntentionListingIdsForBuyer } from "@/lib/prisma/queries/purchase-intentions";
/**
* GET /api/listings
@@ -20,6 +21,7 @@ import { isServerActive } from "@/lib/prisma/queries/servers";
*/
export async function GET(request: NextRequest) {
try {
const auth = await optionalAuth(request);
const { searchParams } = new URL(request.url);
const filters = {
@@ -65,10 +67,26 @@ export async function GET(request: NextRequest) {
? await getListings(filters)
: await getActiveListings(filters);
let listingsResponse = listingsData.listings;
if (auth && listingsResponse.length > 0) {
const listingIds = listingsResponse.map((listing) => listing.listing_id);
const pendingListingIds = await getPendingIntentionListingIdsForBuyer(
auth.userId,
listingIds
);
const pendingSet = new Set(pendingListingIds);
listingsResponse = listingsResponse.map((listing) => ({
...listing,
has_pending_intention_for_current_user: pendingSet.has(listing.listing_id),
}));
}
return NextResponse.json(
{
success: true,
listings: listingsData.listings,
listings: listingsResponse,
pagination: {
page: filters.page,
pageSize: filters.pageSize,
@@ -0,0 +1,175 @@
/**
* PATCH /api/purchase-intentions/[intentionId]/payment-method
* Permite ao comprador trocar o método de pagamento (máximo 1 vez)
*/
import { NextRequest, NextResponse } from "next/server";
import { requireAuth } from "@/lib/auth/middleware";
import {
getPurchaseIntentionById,
updatePurchaseIntentionPaymentMethod,
} from "@/lib/prisma/queries/purchase-intentions";
import { getListingById } from "@/lib/prisma/queries/listings";
import { createSystemMessageInChat } from "@/lib/chat/system-messages";
import { secureLogger } from "@/lib/secure-logger";
function getPaymentMethodLabel(method: string): string {
switch (method) {
case "pix":
return "PIX";
case "tibia_coins":
return "Tibia Coins";
case "gold_coins":
return "Gold Coins";
case "trade":
return "Troca";
default:
return method.toUpperCase();
}
}
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ intentionId: string }> }
) {
try {
const authResult = await requireAuth(request);
if (authResult instanceof NextResponse) return authResult;
const auth = authResult;
const { intentionId: intentionIdParam } = await params;
const intentionId = parseInt(intentionIdParam, 10);
if (isNaN(intentionId)) {
return NextResponse.json(
{ success: false, error: "ID de intenção inválido" },
{ status: 400 }
);
}
const body = await request.json();
const { payment_method } = body;
if (!payment_method || !["pix", "tibia_coins", "gold_coins", "trade"].includes(payment_method)) {
return NextResponse.json(
{ success: false, error: "Método de pagamento inválido" },
{ status: 400 }
);
}
// Buscar intenção
const intention = await getPurchaseIntentionById(intentionId);
if (!intention) {
return NextResponse.json(
{ success: false, error: "Intenção não encontrada" },
{ status: 404 }
);
}
// Verificar se o usuário é o comprador
if (intention.buyer_id !== auth.userId) {
return NextResponse.json(
{ success: false, error: "Apenas o comprador pode trocar o método de pagamento" },
{ status: 403 }
);
}
// Verificar se a intenção está pendente
if (intention.status !== "pending") {
return NextResponse.json(
{ success: false, error: "Apenas intenções pendentes podem ter o método de pagamento alterado" },
{ status: 400 }
);
}
// Verificar se já atingiu o limite de trocas
if (intention.payment_method_change_count >= 1) {
return NextResponse.json(
{ success: false, error: "Você já atingiu o limite de trocas de método de pagamento (1 vez)" },
{ status: 400 }
);
}
// Verificar se o novo método é diferente
if (intention.payment_method === payment_method) {
return NextResponse.json(
{ success: false, error: "O novo método de pagamento deve ser diferente do atual" },
{ status: 400 }
);
}
// Buscar listing para validar método disponível
const listing = await getListingById(intention.listing_id);
if (!listing) {
return NextResponse.json(
{ success: false, error: "Anúncio não encontrado" },
{ status: 404 }
);
}
// Validar método de pagamento disponível
const availableMethods: string[] = [];
if (listing.price_pix) availableMethods.push("pix");
if (listing.price_tibia_coins) availableMethods.push("tibia_coins");
if (listing.price_gold_coins) availableMethods.push("gold_coins");
if (listing.trade_item_id) availableMethods.push("trade");
if (!availableMethods.includes(payment_method)) {
return NextResponse.json(
{
success: false,
error: `Método de pagamento "${payment_method}" não está disponível para este anúncio`,
available_methods: availableMethods,
},
{ status: 400 }
);
}
// Atualizar método de pagamento
const oldPaymentMethod = intention.payment_method;
const updatedIntention = await updatePurchaseIntentionPaymentMethod(
intentionId,
payment_method as any
);
// Criar mensagem do sistema no chat
await createSystemMessageInChat({
listingId: intention.listing_id,
buyerId: intention.buyer_id,
sellerId: listing.seller_id,
message: `O comprador alterou o método de pagamento de ${getPaymentMethodLabel(oldPaymentMethod)} para ${getPaymentMethodLabel(payment_method)}`,
metadata: {
action: "payment_method_changed",
old_payment_method: oldPaymentMethod,
new_payment_method: payment_method,
intention_id: intentionId,
},
});
secureLogger.info("✅ Método de pagamento atualizado", {
userId: auth.userId,
intentionId,
oldPaymentMethod,
newPaymentMethod: payment_method,
});
return NextResponse.json(
{
success: true,
intention: updatedIntention,
message: "Método de pagamento atualizado com sucesso. O vendedor foi notificado.",
},
{ status: 200 }
);
} catch (error) {
secureLogger.error("❌ Erro ao atualizar método de pagamento", {
error: error instanceof Error ? error.message : "Erro desconhecido",
stack: error instanceof Error ? error.stack : undefined,
});
return NextResponse.json(
{ success: false, error: error instanceof Error ? error.message : "Erro ao atualizar método de pagamento" },
{ status: 500 }
);
}
}
+202
View File
@@ -0,0 +1,202 @@
import { NextRequest, NextResponse } from "next/server";
import { secureLogger } from "@/lib/secure-logger";
import { requireAuth } from "@/lib/auth/middleware";
import { getPurchaseIntentionsByBuyer } from "@/lib/prisma/queries/purchase-intentions";
import { prisma } from "@/lib/prisma/app";
import { trackEvent } from "@/lib/prisma/queries/telemetry";
/**
* GET /api/purchase-intentions/my
* Lista todas as intenções de compra 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;
// Buscar parâmetros de filtro
const { searchParams } = new URL(request.url);
const status = searchParams.get("status") as
| "pending"
| "accepted"
| "rejected"
| "expired"
| "completed"
| null;
const limit = parseInt(searchParams.get("limit") || "100", 10);
// Buscar intenções do comprador
const intentions = await getPurchaseIntentionsByBuyer(auth.userId, {
status: status || undefined,
limit,
});
// Buscar todos os listings de uma vez (otimização)
const listingIds = [...new Set(intentions.map((i) => i.listing_id))];
const listings = await prisma.listing.findMany({
where: { listing_id: { in: listingIds } },
select: {
listing_id: true,
item_id: true,
item_id_unified: true,
item_name: true,
quantity: true,
server_name: true,
seller_id: true,
price_pix: true,
price_tibia_coins: true,
price_gold_coins: true,
listing_status: true,
created_at: true,
description: true,
trade_item_id: true,
trade_item_name: true,
trade_item_quantity: true,
views_count: true,
favorites_count: true,
is_featured: true,
item: {
select: {
image_url: true,
image_local_path: true,
category: true,
},
},
seller: {
select: {
user_id: true,
username: true,
email: true,
},
},
},
});
// Criar mapa de listings para acesso rápido
const listingsMap = new Map(listings.map((l) => [l.listing_id, l]));
// Buscar character names dos vendedores em batch
const sellerServerPairs = [
...new Set(
listings.map((l) => `${l.seller_id}:${l.server_name}`)
),
];
const characterMap = new Map<string, string | null>();
await Promise.all(
sellerServerPairs.map(async (pair) => {
const [sellerId, serverName] = pair.split(":");
const character = await prisma.userCharacter.findFirst({
where: {
user_id: parseInt(sellerId, 10),
server_name: serverName,
is_main: true,
},
select: {
character_name: true,
},
});
characterMap.set(pair, character?.character_name || null);
})
);
// Serializar datas para string
const serializeDate = (date: Date | null): string | null => {
return date ? new Date(date).toISOString() : null;
};
// Expandir dados do listing para cada intenção
const intentionsWithListingDetails = intentions.map((intention) => {
const listing = listingsMap.get(intention.listing_id);
const characterKey = listing
? `${listing.seller_id}:${listing.server_name}`
: null;
const sellerCharacterName = characterKey
? characterMap.get(characterKey) || null
: null;
const chatId =
listing?.seller_id != null
? `${intention.listing_id}_${intention.buyer_id}_${listing.seller_id}`
: null;
return {
...intention,
created_at: serializeDate(intention.created_at as Date) || intention.created_at,
updated_at: serializeDate(intention.updated_at as Date) || intention.updated_at,
expires_at: serializeDate(intention.expires_at as Date | null),
accepted_at: serializeDate(intention.accepted_at as Date | null),
rejected_at: serializeDate(intention.rejected_at as Date | null),
chat_id: chatId,
listing: listing
? {
listing_id: listing.listing_id,
item_id: listing.item_id,
item_id_unified: listing.item_id_unified,
item_name: listing.item_name,
quantity: listing.quantity,
server_name: listing.server_name,
seller_id: listing.seller_id,
price_pix: listing.price_pix ? Number(listing.price_pix) : null,
price_tibia_coins:
listing.price_tibia_coins !== null && listing.price_tibia_coins !== undefined
? Number(listing.price_tibia_coins)
: null,
price_gold_coins: listing.price_gold_coins
? Number(listing.price_gold_coins)
: null,
listing_status: listing.listing_status,
created_at:
listing.created_at instanceof Date
? listing.created_at.toISOString()
: listing.created_at,
description: listing.description,
trade_item_id: listing.trade_item_id,
trade_item_name: listing.trade_item_name,
trade_item_quantity: listing.trade_item_quantity,
views_count: listing.views_count ?? 0,
favorites_count: listing.favorites_count ?? 0,
is_featured: listing.is_featured ?? false,
image_url: listing.item?.image_url || null,
image_local_path: listing.item?.image_local_path || null,
item_category: listing.item?.category || null,
seller_character_name: sellerCharacterName,
seller_username: listing.seller?.username || null,
seller_email: listing.seller?.email || null,
}
: null,
};
});
// Registrar telemetria
await trackEvent({
event_type: "purchase_intention_viewed",
user_id: auth.userId,
metadata: {
intentions_count: intentionsWithListingDetails.length,
filter_status: status || "all",
},
});
return NextResponse.json(
{
success: true,
intentions: intentionsWithListingDetails,
count: intentionsWithListingDetails.length,
},
{ status: 200 }
);
} catch (error) {
secureLogger.error("❌ Erro ao buscar intenções de compra do usuário", {
error: error instanceof Error ? error.message : "Erro desconhecido",
stack: error instanceof Error ? error.stack : undefined,
});
return NextResponse.json(
{ success: false, error: "Erro ao buscar intenções de compra" },
{ status: 500 }
);
}
}
+16
View File
@@ -0,0 +1,16 @@
/**
* API Route para Socket.io
* Next.js 15 não suporta servidor HTTP customizado diretamente
* Esta rota será usada para health check
* O Socket.io será inicializado via server.ts customizado
*/
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({
status: "ok",
message: "Socket.io está ativo",
});
}
+9
View File
@@ -12,6 +12,7 @@ import { ThemeToggle } from "./theme-toggle";
import { LanguageSwitcher } from "./language-switcher";
import { MobileMenu } from "./mobile-menu";
import { NotificationBell } from "./notifications/NotificationBell";
import { MessagesBell } from "./messages/MessagesBell";
import { LoginDialog } from "./auth/login-dialog";
import { RegisterDialog } from "./auth/register-dialog";
import { Button } from "@/components/ui/button";
@@ -97,6 +98,9 @@ export default function Header() {
<ThemeToggle />
<LanguageSwitcher />
{/* Messages */}
{mounted && isAuthenticated && <MessagesBell />}
{/* Notifications */}
{mounted && isAuthenticated && <NotificationBell />}
@@ -123,6 +127,11 @@ export default function Header() {
<p className="text-sm font-medium leading-none">
{user.username}
</p>
{user.characterName && (
<p className="text-xs leading-none text-primary font-medium">
{user.characterName}
</p>
)}
<p className="text-xs leading-none text-muted-foreground">
{user.email}
</p>
+115
View File
@@ -0,0 +1,115 @@
"use client";
import { useState } from "react";
import { Package, MapPin, DollarSign, Coins, User } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import Image from "next/image";
import type { Chat } from "@/lib/hooks/use-chat";
interface ChatHeaderProps {
chat: Chat;
currentUserId: number;
}
export function ChatHeader({ chat, currentUserId }: ChatHeaderProps) {
const listing = chat.listing_cache;
const otherUser =
chat.buyer_id === currentUserId ? chat.seller_cache : chat.buyer_cache;
const [imageError, setImageError] = useState(false);
const formatPrice = (price: number | null | undefined, type: "pix" | "tc" | "gp"): string => {
if (price === null || price === undefined) return "N/A";
if (type === "pix") {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
}).format(price);
}
if (type === "tc") {
return `${price.toLocaleString("pt-BR")} TC`;
}
if (type === "gp") {
const gold = price / 1000000;
if (gold >= 1) {
return `${gold.toFixed(2)}kk`;
}
return `${price.toLocaleString("pt-BR")} gp`;
}
return price.toLocaleString("pt-BR");
};
return (
<div className="border-b bg-muted/30 p-4 space-y-3">
{/* Informações do Anúncio */}
<div className="flex items-start gap-3">
{/* Imagem do item */}
<div className="relative w-16 h-16 rounded-lg bg-muted flex items-center justify-center flex-shrink-0 overflow-hidden">
{listing.item_image_url && !imageError ? (
<Image
src={listing.item_image_url}
alt={listing.item_name}
fill
className="object-cover"
onError={() => setImageError(true)}
/>
) : (
<Package className="h-8 w-8 text-muted-foreground" />
)}
</div>
{/* Detalhes do anúncio */}
<div className="flex-1 min-w-0">
<h3 className="font-semibold text-lg truncate">{listing.item_name}</h3>
<div className="flex items-center gap-3 text-sm text-muted-foreground mt-1">
<div className="flex items-center gap-1">
<MapPin className="h-3 w-3" />
<span>{listing.server_name}</span>
</div>
<div className="flex items-center gap-1">
<Package className="h-3 w-3" />
<span>Qtd: 1</span>
</div>
</div>
{/* Preços */}
<div className="flex items-center gap-2 mt-2 flex-wrap">
{listing.price_pix && (
<Badge variant="secondary" className="gap-1">
<DollarSign className="h-3 w-3" />
{formatPrice(listing.price_pix, "pix")}
</Badge>
)}
{listing.price_tibia_coins && (
<Badge variant="secondary" className="gap-1">
<Coins className="h-3 w-3" />
{formatPrice(listing.price_tibia_coins, "tc")}
</Badge>
)}
{listing.price_gold_coins && (
<Badge variant="secondary" className="gap-1">
<Coins className="h-3 w-3" />
{formatPrice(listing.price_gold_coins, "gp")}
</Badge>
)}
</div>
</div>
</div>
{/* Informações do outro usuário */}
<div className="flex items-center gap-2 pt-2 border-t">
<User className="h-4 w-4 text-muted-foreground" />
<span className="text-sm text-muted-foreground">
Conversando com:{" "}
</span>
<span className="text-sm font-medium">
{otherUser.character_name || otherUser.username}
</span>
</div>
</div>
);
}
+147
View File
@@ -0,0 +1,147 @@
"use client";
import { useState, useEffect } from "react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { ChatHeader } from "./ChatHeader";
import { MessageList } from "./MessageList";
import { MessageInput } from "./MessageInput";
import { useChat } from "@/lib/hooks/use-chat";
import { useSession } from "@/lib/hooks/use-session";
import { Skeleton } from "@/components/ui/skeleton";
interface ChatModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
listingId?: number | null;
chatId?: string | null;
initialMessage?: string;
}
export function ChatModal({
open,
onOpenChange,
listingId,
chatId: initialChatId,
initialMessage,
}: ChatModalProps) {
const { user } = useSession();
const [chatId, setChatId] = useState<string | null>(initialChatId || null);
const [isCreatingChat, setIsCreatingChat] = useState(false);
const {
chat,
messages,
isLoading,
isSending,
sendMessage,
loadMoreMessages,
hasMore,
otherUserTyping,
} = useChat(chatId);
// Se chatId for fornecido diretamente, usar ele
useEffect(() => {
if (initialChatId) {
setChatId(initialChatId);
return;
}
}, [initialChatId]);
// Criar ou buscar chat quando modal abrir (apenas se não tiver chatId)
useEffect(() => {
if (!open || !user || !listingId || initialChatId) {
if (!initialChatId && !listingId) {
setChatId(null);
}
return;
}
const createOrGetChat = async () => {
setIsCreatingChat(true);
try {
const res = await fetch("/api/chats", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
credentials: "include",
body: JSON.stringify({
listing_id: listingId,
buyer_message: initialMessage,
}),
});
if (!res.ok) {
throw new Error("Erro ao criar chat");
}
const data = await res.json();
setChatId(data.chat.chat_id);
// Se houver mensagem inicial, já foi enviada no backend
} catch (error) {
console.error("Erro ao criar/buscar chat:", error);
} finally {
setIsCreatingChat(false);
}
};
createOrGetChat();
}, [open, user, listingId, initialMessage, initialChatId]);
if (!user) {
return null;
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl h-[80vh] flex flex-col p-0 gap-0">
<DialogHeader className="sr-only">
<DialogTitle>Chat com vendedor</DialogTitle>
<DialogDescription>
Conversa sobre o anúncio
</DialogDescription>
</DialogHeader>
{isCreatingChat || (isLoading && !chat) ? (
<div className="flex-1 flex items-center justify-center">
<div className="space-y-4 w-full px-4">
<Skeleton className="h-24 w-full" />
<Skeleton className="h-64 w-full" />
<Skeleton className="h-20 w-full" />
</div>
</div>
) : chat ? (
<>
<ChatHeader chat={chat} currentUserId={user.userId} />
<MessageList
messages={messages}
currentUserId={user.userId}
isLoading={isLoading}
onLoadMore={loadMoreMessages}
hasMore={hasMore}
otherUserTyping={otherUserTyping}
/>
<MessageInput
onSend={sendMessage}
isSending={isSending}
disabled={!chat.is_active}
chatId={chatId}
/>
</>
) : (
<div className="flex-1 flex items-center justify-center text-center text-muted-foreground">
<p>Erro ao carregar chat</p>
</div>
)}
</DialogContent>
</Dialog>
);
}
+63
View File
@@ -0,0 +1,63 @@
"use client";
import { cn } from "@/lib/utils";
import type { ChatMessage } from "@/lib/hooks/use-chat";
interface MessageBubbleProps {
message: ChatMessage;
isOwn: boolean;
}
function formatTime(date: string): string {
const d = new Date(date);
return d.toLocaleTimeString("pt-BR", {
hour: "2-digit",
minute: "2-digit",
});
}
export function MessageBubble({ message, isOwn }: MessageBubbleProps) {
if (message.message_type === "system") {
return (
<div className="flex justify-center my-2">
<span className="text-xs text-muted-foreground bg-muted px-3 py-1 rounded-full">
{message.content}
</span>
</div>
);
}
return (
<div
className={cn(
"flex w-full mb-2",
isOwn ? "justify-end" : "justify-start"
)}
>
<div
className={cn(
"max-w-[70%] rounded-lg px-4 py-2",
isOwn
? "bg-primary text-primary-foreground"
: "bg-muted text-foreground"
)}
>
<p className="text-sm whitespace-pre-wrap break-words">
{message.content}
</p>
<div
className={cn(
"flex items-center gap-1 mt-1 text-xs",
isOwn ? "text-primary-foreground/70" : "text-muted-foreground"
)}
>
<span>{formatTime(message.created_at)}</span>
{isOwn && message.read_at && (
<span className="opacity-70">✓✓</span>
)}
</div>
</div>
</div>
);
}
+88
View File
@@ -0,0 +1,88 @@
"use client";
import { useState, KeyboardEvent } from "react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Send, Loader2 } from "lucide-react";
import { useChatTyping } from "@/lib/hooks/use-chat";
import { useSocket } from "@/lib/hooks/use-socket";
interface MessageInputProps {
onSend: (content: string) => Promise<void>;
isSending: boolean;
disabled?: boolean;
chatId: string | null;
}
export function MessageInput({
onSend,
isSending,
disabled = false,
chatId,
}: MessageInputProps) {
const [content, setContent] = useState("");
const { socket, isConnected } = useSocket();
const { handleTypingStart, handleTypingStop } = useChatTyping(
socket,
isConnected,
chatId
);
const handleSubmit = async () => {
if (!content.trim() || isSending || disabled) return;
const messageContent = content.trim();
setContent("");
handleTypingStop();
await onSend(messageContent);
};
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSubmit();
}
};
const handleChange = (value: string) => {
setContent(value);
if (value.trim().length > 0) {
handleTypingStart();
} else {
handleTypingStop();
}
};
return (
<div className="border-t p-4">
<div className="flex items-end gap-2">
<Textarea
value={content}
onChange={(e) => handleChange(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Digite sua mensagem... (Enter para enviar, Shift+Enter para nova linha)"
className="min-h-[60px] max-h-[120px] resize-none"
disabled={isSending || disabled}
rows={2}
/>
<Button
onClick={handleSubmit}
disabled={!content.trim() || isSending || disabled}
size="icon"
className="h-[60px] w-[60px] flex-shrink-0"
>
{isSending ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<Send className="h-5 w-5" />
)}
</Button>
</div>
<p className="text-xs text-muted-foreground mt-2">
Máximo 1000 caracteres
</p>
</div>
);
}
+118
View File
@@ -0,0 +1,118 @@
"use client";
import { useEffect, useRef } from "react";
import { MessageBubble } from "./MessageBubble";
import { Skeleton } from "@/components/ui/skeleton";
import type { ChatMessage } from "@/lib/hooks/use-chat";
interface MessageListProps {
messages: ChatMessage[];
currentUserId: number;
isLoading: boolean;
onLoadMore?: () => void;
hasMore: boolean;
otherUserTyping: boolean;
}
export function MessageList({
messages,
currentUserId,
isLoading,
onLoadMore,
hasMore,
otherUserTyping,
}: MessageListProps) {
const messagesEndRef = useRef<HTMLDivElement>(null);
const messagesContainerRef = useRef<HTMLDivElement>(null);
const prevMessagesLengthRef = useRef(0);
// Scroll para última mensagem quando novas mensagens chegarem
useEffect(() => {
if (messages.length > prevMessagesLengthRef.current) {
// Nova mensagem adicionada
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}
prevMessagesLengthRef.current = messages.length;
}, [messages.length]);
// Scroll inicial para o final
useEffect(() => {
if (messages.length > 0 && !isLoading) {
messagesEndRef.current?.scrollIntoView({ behavior: "auto" });
}
}, [isLoading]);
// Detectar scroll no topo para carregar mais
const handleScroll = () => {
const container = messagesContainerRef.current;
if (!container || !onLoadMore || !hasMore || isLoading) return;
if (container.scrollTop === 0) {
const previousScrollHeight = container.scrollHeight;
onLoadMore();
// Ajustar scroll após carregar mais mensagens
setTimeout(() => {
const newScrollHeight = container.scrollHeight;
container.scrollTop = newScrollHeight - previousScrollHeight;
}, 100);
}
};
return (
<div
ref={messagesContainerRef}
onScroll={handleScroll}
className="flex-1 overflow-y-auto p-4 space-y-1"
>
{isLoading && messages.length === 0 ? (
<div className="space-y-4">
{Array.from({ length: 5 }).map((_, i) => (
<Skeleton key={i} className="h-16 w-full" />
))}
</div>
) : messages.length === 0 ? (
<div className="flex items-center justify-center h-full text-center text-muted-foreground">
<div>
<p className="text-sm">Nenhuma mensagem ainda</p>
<p className="text-xs mt-1">Envie a primeira mensagem para começar a conversa</p>
</div>
</div>
) : (
<>
{hasMore && (
<div className="text-center py-2">
<button
onClick={onLoadMore}
className="text-xs text-muted-foreground hover:text-foreground"
disabled={isLoading}
>
{isLoading ? "Carregando..." : "Carregar mensagens anteriores"}
</button>
</div>
)}
{messages.map((message) => (
<MessageBubble
key={message._id}
message={message}
isOwn={message.sender_id === currentUserId}
/>
))}
{otherUserTyping && (
<div className="flex justify-start mb-2">
<div className="bg-muted rounded-lg px-4 py-2">
<div className="flex items-center gap-1">
<div className="w-2 h-2 bg-muted-foreground rounded-full animate-bounce" />
<div className="w-2 h-2 bg-muted-foreground rounded-full animate-bounce delay-75" />
<div className="w-2 h-2 bg-muted-foreground rounded-full animate-bounce delay-150" />
</div>
</div>
</div>
)}
<div ref={messagesEndRef} />
</>
)}
</div>
);
}
+55 -5
View File
@@ -4,7 +4,7 @@ import { useState, useEffect } from "react";
import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Heart, Clock, Eye, Star, MapPin, DollarSign, Coins, RefreshCw, ShoppingCart, TrendingUp, User } from "lucide-react";
import { Heart, Clock, Eye, Star, MapPin, DollarSign, Coins, RefreshCw, ShoppingCart, TrendingUp, User, MessageCircle } from "lucide-react";
import { useAdTracking, useMarketTelemetry } from "@/lib/hooks/use-telemetry";
import { useSession } from "@/lib/hooks/use-session";
import { useQueryClient } from "@tanstack/react-query";
@@ -15,6 +15,7 @@ import { BidModal } from "./BidModal";
import { SellerInfo } from "./SellerInfo";
import { ListingDetailsModal } from "./ListingDetailsModal";
import { AuctionCountdown } from "./AuctionCountdown";
import { ChatModal } from "@/components/chat/ChatModal";
// Função auxiliar para formatar tempo relativo
function formatTimeAgo(date: Date): string {
@@ -66,6 +67,7 @@ interface Listing {
item_category?: string | null;
// Campo do vendedor
seller_character_name?: string | null;
has_pending_intention_for_current_user?: boolean;
}
interface PriceInfo {
@@ -88,6 +90,7 @@ export function AdCard({ listing, viewMode = "grid" }: AdCardProps) {
const [showPurchaseModal, setShowPurchaseModal] = useState(false);
const [showBidModal, setShowBidModal] = useState(false);
const [showDetailsModal, setShowDetailsModal] = useState(false);
const [showChatModal, setShowChatModal] = useState(false);
const invalidateCache = () => {
queryClient.invalidateQueries({ queryKey: ["listings"] });
@@ -261,6 +264,7 @@ export function AdCard({ listing, viewMode = "grid" }: AdCardProps) {
const timeAgo = formatTimeAgo(new Date(listing.created_at));
const availablePrices = getAvailablePrices();
const isSold = listing.listing_status === "sold";
const hasPendingIntention = Boolean(listing.has_pending_intention_for_current_user);
// Função para obter URL da imagem do item
const getItemImageUrl = (): string => {
@@ -662,6 +666,20 @@ export function AdCard({ listing, viewMode = "grid" }: AdCardProps) {
Comprar
</Button>
)}
{user && user.userId !== listing.seller_id && !isSold && (
<Button
variant="outline"
size="sm"
className="transition-all duration-200 hover:scale-105"
onClick={(e) => {
e.stopPropagation();
setShowChatModal(true);
}}
>
<MessageCircle className="h-4 w-4 mr-2" />
Chat
</Button>
)}
</div>
)}
{isSold && (
@@ -932,15 +950,40 @@ export function AdCard({ listing, viewMode = "grid" }: AdCardProps) {
<Button
variant="default"
size="sm"
className={cn(
"flex-1 transition-all duration-200 hover:scale-105",
(isSold || hasPendingIntention) && "opacity-60 cursor-not-allowed hover:scale-100"
)}
onClick={(e) => {
e.stopPropagation();
if (hasPendingIntention) {
return;
}
setShowPurchaseModal(true);
}}
disabled={isSold || hasPendingIntention}
title={
hasPendingIntention
? "Você já enviou uma intenção para este anúncio. Gerencie em Minhas intenções."
: undefined
}
>
<ShoppingCart className="h-4 w-4 mr-2" />
{hasPendingIntention ? "Intenção pendente" : "Comprar"}
</Button>
)}
{user && user.userId !== listing.seller_id && !isSold && (
<Button
variant="outline"
size="sm"
className="flex-1 transition-all duration-200 hover:scale-105"
onClick={(e) => {
e.stopPropagation();
setShowPurchaseModal(true);
setShowChatModal(true);
}}
disabled={isSold}
>
<ShoppingCart className="h-4 w-4 mr-2" />
Comprar
<MessageCircle className="h-4 w-4 mr-2" />
Chat
</Button>
)}
</>
@@ -1021,6 +1064,13 @@ export function AdCard({ listing, viewMode = "grid" }: AdCardProps) {
onActivate={handleActivate}
onCancel={handleCancel}
/>
{user && user.userId !== listing.seller_id && (
<ChatModal
open={showChatModal}
onOpenChange={setShowChatModal}
listingId={listing.listing_id}
/>
)}
</Card>
);
}
@@ -0,0 +1,608 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import {
Clock,
CheckCircle2,
XCircle,
MessageSquare,
ShoppingCart,
MapPin,
Package,
User,
ExternalLink,
AlertCircle,
DollarSign,
Coins,
RefreshCw,
} from "lucide-react";
import { useMyPurchaseIntentions, type PurchaseIntention, type PurchaseIntentionStatus } from "@/lib/hooks/use-purchase-intentions";
import { useSession } from "@/lib/hooks/use-session";
import Link from "next/link";
import Image from "next/image";
import { cn } from "@/lib/utils";
import { ChangePaymentMethodButton } from "@/components/purchase-intentions/ChangePaymentMethodButton";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { ChatModal } from "@/components/chat/ChatModal";
function formatTimeAgo(date: Date | string): string {
const dateObj = typeof date === "string" ? new Date(date) : date;
const seconds = Math.floor((new Date().getTime() - dateObj.getTime()) / 1000);
if (seconds < 60) return "há alguns segundos";
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `há ${minutes} ${minutes === 1 ? "minuto" : "minutos"}`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `há ${hours} ${hours === 1 ? "hora" : "horas"}`;
const days = Math.floor(hours / 24);
if (days < 30) return `há ${days} ${days === 1 ? "dia" : "dias"}`;
const months = Math.floor(days / 30);
if (months < 12) return `há ${months} ${months === 1 ? "mês" : "meses"}`;
const years = Math.floor(months / 12);
return `há ${years} ${years === 1 ? "ano" : "anos"}`;
}
function getStatusBadge(status: PurchaseIntentionStatus) {
switch (status) {
case "pending":
return (
<Badge variant="secondary" className="bg-yellow-500/20 text-yellow-700 dark:text-yellow-400">
<Clock className="h-3 w-3 mr-1" />
Pendente
</Badge>
);
case "accepted":
return (
<Badge variant="secondary" className="bg-green-500/20 text-green-700 dark:text-green-400">
<CheckCircle2 className="h-3 w-3 mr-1" />
Aceita
</Badge>
);
case "rejected":
return (
<Badge variant="secondary" className="bg-red-500/20 text-red-700 dark:text-red-400">
<XCircle className="h-3 w-3 mr-1" />
Rejeitada
</Badge>
);
case "expired":
return (
<Badge variant="secondary" className="bg-gray-500/20 text-gray-700 dark:text-gray-400">
<AlertCircle className="h-3 w-3 mr-1" />
Expirada
</Badge>
);
case "completed":
return (
<Badge variant="secondary" className="bg-blue-500/20 text-blue-700 dark:text-blue-400">
<CheckCircle2 className="h-3 w-3 mr-1" />
Concluída
</Badge>
);
default:
return <Badge variant="secondary">{status}</Badge>;
}
}
function getPaymentMethodLabel(method: string): string {
switch (method) {
case "pix":
return "PIX";
case "tibia_coins":
return "Tibia Coins";
case "gold_coins":
return "Gold Coins";
case "trade":
return "Troca";
default:
return method.toUpperCase();
}
}
function formatPrice(price: number | null, method: string): string {
if (price === null) return "N/A";
if (method === "pix") {
return new Intl.NumberFormat("pt-BR", {
style: "currency",
currency: "BRL",
}).format(price);
}
if (method === "tibia_coins") {
return `${price.toLocaleString("pt-BR")} TC`;
}
if (method === "gold_coins") {
const gold = price / 1000000;
if (gold >= 1) {
return `${gold.toFixed(2)}kk`;
}
return `${price.toLocaleString("pt-BR")} gp`;
}
return price.toLocaleString("pt-BR");
}
interface IntentionCardProps {
intention: PurchaseIntention;
locale?: string;
}
function IntentionCard({ intention, locale = "pt" }: IntentionCardProps) {
const listing = intention.listing;
const [showListingModal, setShowListingModal] = useState(false);
const [showChatModal, setShowChatModal] = useState(false);
if (!listing) {
return (
<Card className="border-dashed opacity-60">
<CardHeader className="pb-3">
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-4 flex-1 min-w-0">
<div className="relative w-16 h-16 rounded-lg bg-muted flex items-center justify-center flex-shrink-0">
<AlertCircle className="h-8 w-8 text-muted-foreground" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<h3 className="font-semibold text-lg">Anúncio não disponível</h3>
{getStatusBadge(intention.status)}
</div>
<p className="text-sm text-muted-foreground">
Este anúncio foi removido ou não está mais disponível
</p>
</div>
</div>
</div>
</CardHeader>
<CardContent>
<div className="text-xs text-muted-foreground">
Intenção criada {formatTimeAgo(intention.created_at)}
</div>
</CardContent>
</Card>
);
}
const getItemImageUrl = () => {
if (listing.image_url) {
return listing.image_url;
}
if (listing.image_local_path) {
const normalizedPath = listing.image_local_path.replace(/\\/g, "/");
if (normalizedPath.startsWith("data/")) {
return `/api/images?path=${encodeURIComponent(normalizedPath)}`;
}
const category = listing.item_category || "other";
return `/api/images?path=${encodeURIComponent(`data/images/${category}/${normalizedPath}`)}`;
}
if (listing.item_id_unified) {
const params = new URLSearchParams({ item: listing.item_id_unified.toString() });
if (listing.item_name) {
params.set("name", listing.item_name);
}
return `/api/images?${params.toString()}`;
}
const params = new URLSearchParams({ item: listing.item_id.toString() });
if (listing.item_name) {
params.set("name", listing.item_name);
}
return `/api/images?${params.toString()}`;
};
const itemImageUrl = getItemImageUrl();
const chatId =
intention.chat_id ??
(listing.seller_id != null
? `${listing.listing_id}_${intention.buyer_id}_${listing.seller_id}`
: null);
const price = listing.price_pix && intention.payment_method === "pix"
? listing.price_pix
: listing.price_tibia_coins && intention.payment_method === "tibia_coins"
? listing.price_tibia_coins
: listing.price_gold_coins && intention.payment_method === "gold_coins"
? listing.price_gold_coins
: null;
return (
<>
<Card className="hover:shadow-md transition-shadow">
<CardHeader className="pb-3">
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-4 flex-1 min-w-0">
<div className="relative w-16 h-16 rounded-lg bg-muted flex items-center justify-center flex-shrink-0 overflow-hidden">
{itemImageUrl ? (
<Image
src={itemImageUrl}
alt={listing.item_name}
fill
className="object-cover"
/>
) : (
<Package className="h-8 w-8 text-muted-foreground" />
)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<h3 className="font-semibold text-lg truncate">{listing.item_name}</h3>
{getStatusBadge(intention.status)}
</div>
<div className="flex items-center gap-4 text-sm text-muted-foreground mb-2">
<div className="flex items-center gap-1">
<MapPin className="h-3 w-3" />
<span>{listing.server_name}</span>
</div>
<div className="flex items-center gap-1">
<Package className="h-3 w-3" />
<span>Qtd: {listing.quantity}</span>
</div>
<div className="flex items-center gap-1">
<ShoppingCart className="h-3 w-3" />
<span>{getPaymentMethodLabel(intention.payment_method)}</span>
{price !== null && (
<span className="font-medium text-foreground ml-1">
{formatPrice(price, intention.payment_method)}
</span>
)}
</div>
</div>
</div>
</div>
</div>
</CardHeader>
<CardContent className="space-y-3">
{/* Informações do vendedor */}
<div className="flex items-center gap-2 text-sm">
<User className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Vendedor:</span>
<span className="font-medium">
{listing.seller_character_name || listing.seller_username || "Desconhecido"}
</span>
</div>
{/* Mensagem do comprador */}
{intention.buyer_message && (
<div className="bg-muted/50 rounded-md p-3">
<div className="flex items-start gap-2">
<MessageSquare className="h-4 w-4 text-muted-foreground mt-0.5 flex-shrink-0" />
<div className="flex-1 min-w-0">
<p className="text-xs text-muted-foreground mb-1">Sua mensagem:</p>
<p className="text-sm">{intention.buyer_message}</p>
</div>
</div>
</div>
)}
{/* Resposta do vendedor */}
{intention.seller_response && (
<div
className={cn(
"rounded-md p-3 border",
intention.status === "accepted"
? "bg-green-500/10 border-green-500/20"
: intention.status === "rejected"
? "bg-red-500/10 border-red-500/20"
: "bg-blue-500/10 border-blue-500/20"
)}
>
<div className="flex items-start gap-2">
<MessageSquare
className={cn(
"h-4 w-4 mt-0.5 flex-shrink-0",
intention.status === "accepted"
? "text-green-600 dark:text-green-400"
: intention.status === "rejected"
? "text-red-600 dark:text-red-400"
: "text-blue-600 dark:text-blue-400"
)}
/>
<div className="flex-1 min-w-0">
<p className="text-xs font-medium mb-1">
{intention.status === "accepted"
? "Resposta do vendedor (Aceita):"
: intention.status === "rejected"
? "Resposta do vendedor (Rejeitada):"
: "Resposta do vendedor:"}
</p>
<p className="text-sm">{intention.seller_response}</p>
</div>
</div>
</div>
)}
{/* Timestamps */}
<div className="flex items-center justify-between text-xs text-muted-foreground pt-2 border-t">
<div className="flex items-center gap-1">
<Clock className="h-3 w-3" />
<span>Criada {formatTimeAgo(intention.created_at)}</span>
</div>
{intention.updated_at !== intention.created_at && (
<span>Atualizada {formatTimeAgo(intention.updated_at)}</span>
)}
</div>
{/* Actions */}
<div className="flex items-center gap-2 pt-2 flex-wrap">
{intention.status === "pending" &&
intention.payment_method_change_count < 1 && (
<ChangePaymentMethodButton
intentionId={intention.intention_id}
currentPaymentMethod={intention.payment_method}
availableMethods={[
...(listing.price_pix ? ["pix"] : []),
...(listing.price_tibia_coins ? ["tibia_coins"] : []),
...(listing.price_gold_coins ? ["gold_coins"] : []),
...(listing.trade_item_id ? ["trade"] : []),
]}
canChange={true}
/>
)}
<Button
variant="outline"
size="sm"
onClick={() => setShowListingModal(true)}
className="flex-1"
>
<ExternalLink className="h-4 w-4 mr-2" />
Ver Anúncio
</Button>
<Button
variant="outline"
size="sm"
className="flex-1"
onClick={() => setShowChatModal(true)}
>
<MessageSquare className="h-4 w-4 mr-2" />
Abrir Chat
</Button>
{intention.status === "accepted" && listing.listing_status === "active" && (
<Button
size="sm"
onClick={() => setShowListingModal(true)}
className="flex-1"
>
<ShoppingCart className="h-4 w-4 mr-2" />
Comprar Agora
</Button>
)}
</div>
</CardContent>
</Card>
<Dialog open={showListingModal} onOpenChange={setShowListingModal}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>{listing.item_name}</DialogTitle>
<DialogDescription>
Detalhes do anúncio selecionado
</DialogDescription>
</DialogHeader>
<div className="grid grid-cols-1 md:grid-cols-[220px,1fr] gap-4">
<div className="relative w-full h-52 rounded-lg bg-muted overflow-hidden flex items-center justify-center">
{itemImageUrl ? (
<Image
src={itemImageUrl}
alt={listing.item_name}
fill
className="object-contain p-4"
/>
) : (
<Package className="h-12 w-12 text-muted-foreground" />
)}
</div>
<div className="space-y-4">
<div>
<h3 className="text-lg font-semibold">{listing.item_name}</h3>
<p className="text-sm text-muted-foreground mt-1">{listing.description ?? "Sem descrição fornecida para este anúncio."}</p>
</div>
<div className="space-y-2 text-sm">
<div className="flex items-center gap-2 text-muted-foreground">
<MapPin className="h-4 w-4" />
<span>Servidor: <span className="font-medium text-foreground">{listing.server_name}</span></span>
</div>
<div className="flex items-center gap-2 text-muted-foreground">
<Package className="h-4 w-4" />
<span>Quantidade: <span className="font-medium text-foreground">{listing.quantity}</span></span>
</div>
<div className="flex items-center gap-2 text-muted-foreground">
<User className="h-4 w-4" />
<span>Vendedor:{" "}
<span className="font-medium text-foreground">
{listing.seller_character_name || listing.seller_username || "Desconhecido"}
</span>
</span>
</div>
</div>
<div className="space-y-2">
<h4 className="text-sm font-medium text-muted-foreground uppercase tracking-wide">Condições de pagamento</h4>
<div className="flex flex-wrap gap-2">
{listing.price_pix && (
<Badge variant="secondary" className="gap-1">
<DollarSign className="h-3 w-3" />
{formatPrice(listing.price_pix, "pix")}
</Badge>
)}
{listing.price_tibia_coins && (
<Badge variant="secondary" className="gap-1">
<Coins className="h-3 w-3" />
{formatPrice(listing.price_tibia_coins, "tibia_coins")}
</Badge>
)}
{listing.price_gold_coins && (
<Badge variant="secondary" className="gap-1">
<Coins className="h-3 w-3" />
{formatPrice(listing.price_gold_coins, "gold_coins")}
</Badge>
)}
{listing.trade_item_id && listing.trade_item_name && listing.trade_item_quantity && (
<Badge variant="secondary" className="gap-1">
<RefreshCw className="h-3 w-3" />
{listing.trade_item_quantity}x {listing.trade_item_name}
</Badge>
)}
</div>
</div>
<div className="flex flex-wrap gap-2">
<Button variant="outline" asChild>
<Link href={`/${locale}/market?listing=${listing.listing_id}`} target="_blank">
Abrir no marketplace
</Link>
</Button>
<Button
variant="default"
onClick={() => setShowChatModal(true)}
>
<MessageSquare className="h-4 w-4 mr-2" />
Continuar conversa
</Button>
</div>
</div>
</div>
</DialogContent>
</Dialog>
{listing && (
<ChatModal
open={showChatModal}
onOpenChange={setShowChatModal}
listingId={listing.listing_id}
chatId={chatId || undefined}
/>
)}
</>
);
}
interface MyPurchaseIntentionsPanelProps {
locale?: string;
}
export function MyPurchaseIntentionsPanel({ locale = "pt" }: MyPurchaseIntentionsPanelProps) {
const { user } = useSession();
const [filter, setFilter] = useState<PurchaseIntentionStatus | "all">("all");
const { intentions, isLoading, refetch } = useMyPurchaseIntentions(
filter === "all" ? undefined : filter
);
// Contar por status
const pendingCount = intentions.filter((i) => i.status === "pending").length;
const acceptedCount = intentions.filter((i) => i.status === "accepted").length;
const rejectedCount = intentions.filter((i) => i.status === "rejected").length;
const expiredCount = intentions.filter((i) => i.status === "expired").length;
const completedCount = intentions.filter((i) => i.status === "completed").length;
if (!user) {
return (
<div className="text-center py-12">
<p className="text-muted-foreground">Faça login para ver suas intenções de compra</p>
</div>
);
}
return (
<div className="space-y-6">
<div>
<h2 className="text-2xl font-bold mb-2">Minhas Intenções de Compra</h2>
<p className="text-muted-foreground">
Acompanhe suas intenções de compra e respostas dos vendedores
</p>
</div>
{/* Filtros */}
<div className="flex items-center gap-2 flex-wrap">
<Button
variant={filter === "all" ? "default" : "outline"}
size="sm"
onClick={() => setFilter("all")}
>
Todas ({intentions.length})
</Button>
<Button
variant={filter === "pending" ? "default" : "outline"}
size="sm"
onClick={() => setFilter("pending")}
>
Pendentes ({pendingCount})
</Button>
<Button
variant={filter === "accepted" ? "default" : "outline"}
size="sm"
onClick={() => setFilter("accepted")}
>
Aceitas ({acceptedCount})
</Button>
<Button
variant={filter === "rejected" ? "default" : "outline"}
size="sm"
onClick={() => setFilter("rejected")}
>
Rejeitadas ({rejectedCount})
</Button>
{expiredCount > 0 && (
<Button
variant={filter === "expired" ? "default" : "outline"}
size="sm"
onClick={() => setFilter("expired")}
>
Expiradas ({expiredCount})
</Button>
)}
{completedCount > 0 && (
<Button
variant={filter === "completed" ? "default" : "outline"}
size="sm"
onClick={() => setFilter("completed")}
>
Concluídas ({completedCount})
</Button>
)}
</div>
{/* Lista de intenções */}
{isLoading ? (
<div className="space-y-4">
{Array.from({ length: 3 }).map((_, i) => (
<Skeleton key={i} className="h-48 w-full" />
))}
</div>
) : intentions.length === 0 ? (
<div className="text-center py-12 border rounded-lg">
<ShoppingCart className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
<p className="text-lg font-medium mb-2">Nenhuma intenção de compra encontrada</p>
<p className="text-sm text-muted-foreground mb-4">
{filter === "all"
? "Quando você manifestar interesse em comprar um item, ele aparecerá aqui."
: `Não há intenções com status "${filter}" no momento.`}
</p>
<Button asChild variant="outline">
<Link href={`/${locale}/market`}>Explorar Marketplace</Link>
</Button>
</div>
) : (
<div className="space-y-4">
{intentions.map((intention) => (
<IntentionCard key={intention.intention_id} intention={intention} locale={locale} />
))}
</div>
)}
</div>
);
}
+101
View File
@@ -0,0 +1,101 @@
"use client";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Package, Clock } from "lucide-react";
import Image from "next/image";
import type { Chat } from "@/lib/hooks/use-chat";
import { formatTimeAgo } from "@/lib/utils";
interface ChatListItemProps {
chat: Chat;
currentUserId: number;
onChatClick: () => void;
}
export function ChatListItem({
chat,
currentUserId,
onChatClick,
}: ChatListItemProps) {
const otherUser =
chat.buyer_id === currentUserId
? chat.seller_cache
: chat.buyer_cache;
const unreadCount =
chat.buyer_id === currentUserId
? chat.buyer_unread_count
: chat.seller_unread_count;
const listing = chat.listing_cache;
return (
<Card
className="p-4 cursor-pointer hover:bg-accent transition-colors"
onClick={onChatClick}
>
<div className="flex items-start gap-3">
{/* Avatar do outro usuário */}
<Avatar className="h-12 w-12 flex-shrink-0">
<AvatarFallback>
{(otherUser.character_name || otherUser.username)
.charAt(0)
.toUpperCase()}
</AvatarFallback>
</Avatar>
{/* Conteúdo */}
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between mb-1">
<h4 className="font-semibold text-sm truncate">
{otherUser.character_name || otherUser.username}
</h4>
{unreadCount > 0 && (
<Badge variant="destructive" className="h-5 min-w-5 px-1.5 text-xs">
{unreadCount}
</Badge>
)}
</div>
{/* Preview do item */}
<div className="flex items-center gap-2 text-xs text-muted-foreground mb-1">
<Package className="h-3 w-3 flex-shrink-0" />
<span className="truncate">{listing.item_name}</span>
</div>
{/* Preview da última mensagem */}
{chat.last_message_preview && (
<p className="text-xs text-muted-foreground truncate mb-1">
{chat.last_message_preview}
</p>
)}
{/* Timestamp */}
{chat.last_message_at && (
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<Clock className="h-3 w-3" />
<span>{formatTimeAgo(new Date(chat.last_message_at))}</span>
</div>
)}
</div>
{/* Imagem do item (opcional) */}
{listing.item_image_url && (
<div className="relative w-12 h-12 rounded-lg bg-muted flex-shrink-0 overflow-hidden">
<Image
src={listing.item_image_url}
alt={listing.item_name}
fill
className="object-cover"
onError={(e) => {
e.currentTarget.style.display = "none";
}}
/>
</div>
)}
</div>
</Card>
);
}
+93
View File
@@ -0,0 +1,93 @@
"use client";
import { useState, useEffect } from "react";
import { MessageCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { useSession } from "@/lib/hooks/use-session";
import { MessagesPanel } from "./MessagesPanel";
interface MessagesBellProps {
className?: string;
}
export function MessagesBell({ className }: MessagesBellProps) {
const { user } = useSession();
const [unreadUsersCount, setUnreadUsersCount] = useState(0);
const [isOpen, setIsOpen] = useState(false);
// Buscar contagem de usuários únicos com mensagens não vistas
const fetchUnreadCount = async () => {
if (!user) return;
try {
const res = await fetch("/api/chats/unread-count", {
credentials: "include",
});
if (res.ok) {
const data = await res.json();
if (data.success) {
setUnreadUsersCount(data.count);
}
}
} catch (error) {
console.error("[CHAT-DEBUG] Erro ao buscar contagem de chats:", error);
}
};
// Polling automático a cada 30 segundos
useEffect(() => {
if (!user) return;
fetchUnreadCount();
const interval = setInterval(() => {
fetchUnreadCount();
}, 30000); // 30 segundos
return () => clearInterval(interval);
}, [user]);
// Atualizar contagem quando abrir/fechar
useEffect(() => {
if (isOpen) {
fetchUnreadCount();
}
}, [isOpen]);
// Marcar como visto quando abrir
const handleOpenChange = (open: boolean) => {
setIsOpen(open);
};
if (!user) {
return null;
}
return (
<>
<Button
variant="ghost"
size="icon"
className={`relative ${className}`}
onClick={() => handleOpenChange(true)}
>
<MessageCircle className="h-5 w-5" />
{unreadUsersCount > 0 && (
<Badge
variant="destructive"
className="absolute -top-1 -right-1 h-5 w-5 flex items-center justify-center p-0 text-xs rounded-full animate-pulse"
>
{unreadUsersCount > 99 ? "99+" : unreadUsersCount}
</Badge>
)}
</Button>
<MessagesPanel
open={isOpen}
onOpenChange={handleOpenChange}
onUnreadCountChange={setUnreadUsersCount}
/>
</>
);
}
+173
View File
@@ -0,0 +1,173 @@
"use client";
import { useState, useEffect } from "react";
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
import { ChatListItem } from "./ChatListItem";
import { Skeleton } from "@/components/ui/skeleton";
import { useSession } from "@/lib/hooks/use-session";
import { ChatModal } from "@/components/chat/ChatModal";
import type { Chat } from "@/lib/hooks/use-chat";
interface MessagesPanelProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onUnreadCountChange: (count: number) => void;
}
export function MessagesPanel({
open,
onOpenChange,
onUnreadCountChange,
}: MessagesPanelProps) {
const { user } = useSession();
const [chats, setChats] = useState<Chat[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [selectedChatId, setSelectedChatId] = useState<string | null>(null);
const [showChatModal, setShowChatModal] = useState(false);
// Buscar chats do usuário
const fetchChats = async () => {
if (!user) return;
setIsLoading(true);
try {
const res = await fetch("/api/chats", {
credentials: "include",
});
if (res.ok) {
const data = await res.json();
if (data.success) {
setChats(data.chats || []);
// Calcular contagem de usuários únicos com não lidas
const uniqueUsersWithUnread = new Set<number>();
data.chats.forEach((chat: Chat) => {
const unreadCount =
chat.buyer_id === user.userId
? chat.buyer_unread_count
: chat.seller_unread_count;
const otherUserId =
chat.buyer_id === user.userId
? chat.seller_id
: chat.buyer_id;
if (unreadCount > 0) {
uniqueUsersWithUnread.add(otherUserId);
}
});
onUnreadCountChange(uniqueUsersWithUnread.size);
}
}
} catch (error) {
console.error("[CHAT-DEBUG] Erro ao buscar chats:", error);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
if (open && user) {
fetchChats();
// Marcar todos como lidos ao abrir
markAllAsRead();
}
}, [open, user]);
const markAllAsRead = async () => {
try {
await fetch("/api/chats/mark-all-read", {
method: "POST",
credentials: "include",
});
// Atualizar estado local
setChats((prev) =>
prev.map((chat) => ({
...chat,
buyer_unread_count:
chat.buyer_id === user?.userId ? 0 : chat.buyer_unread_count,
seller_unread_count:
chat.seller_id === user?.userId ? 0 : chat.seller_unread_count,
}))
);
onUnreadCountChange(0);
} catch (error) {
console.error("[CHAT-DEBUG] Erro ao marcar como lido:", error);
}
};
const handleChatClick = (chatId: string, listingId: number) => {
setSelectedChatId(chatId);
setShowChatModal(true);
onOpenChange(false);
};
if (!user) {
return null;
}
return (
<>
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent side="right" className="w-full sm:max-w-lg p-0">
<SheetHeader className="px-6 pt-6 pb-4 border-b">
<SheetTitle>Mensagens</SheetTitle>
<SheetDescription>
Suas conversas com compradores e vendedores
</SheetDescription>
</SheetHeader>
<div className="mt-4 px-4 overflow-y-auto" style={{ maxHeight: "calc(100vh - 120px)" }}>
{isLoading ? (
<div className="space-y-4">
{Array.from({ length: 5 }).map((_, i) => (
<Skeleton key={i} className="h-20 w-full" />
))}
</div>
) : chats.length === 0 ? (
<div className="text-center py-12 text-muted-foreground">
<p>Nenhuma conversa ainda</p>
<p className="text-sm mt-2">
Comece uma conversa a partir de um anúncio
</p>
</div>
) : (
<div className="space-y-2">
{chats.map((chat) => (
<ChatListItem
key={chat.chat_id}
chat={chat}
currentUserId={user.userId}
onChatClick={() => handleChatClick(chat.chat_id, chat.listing_id)}
/>
))}
</div>
)}
</div>
</SheetContent>
</Sheet>
{selectedChatId && (
<ChatModal
open={showChatModal}
onOpenChange={(open) => {
setShowChatModal(open);
if (!open) {
setSelectedChatId(null);
// Recarregar chats quando fechar o modal
fetchChats();
}
}}
listingId={null}
chatId={selectedChatId || undefined}
/>
)}
</>
);
}
@@ -0,0 +1,181 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { RefreshCw, Loader2 } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
interface ChangePaymentMethodButtonProps {
intentionId: number;
currentPaymentMethod: string;
availableMethods: string[];
canChange: boolean;
}
function getPaymentMethodLabel(method: string): string {
switch (method) {
case "pix":
return "PIX";
case "tibia_coins":
return "Tibia Coins";
case "gold_coins":
return "Gold Coins";
case "trade":
return "Troca";
default:
return method.toUpperCase();
}
}
export function ChangePaymentMethodButton({
intentionId,
currentPaymentMethod,
availableMethods,
canChange,
}: ChangePaymentMethodButtonProps) {
const [open, setOpen] = useState(false);
const [selectedMethod, setSelectedMethod] = useState<string>(currentPaymentMethod);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const queryClient = useQueryClient();
// Filtrar métodos disponíveis (excluir o atual)
const availableOptions = availableMethods.filter(
(method) => method !== currentPaymentMethod
);
const handleChange = async () => {
if (selectedMethod === currentPaymentMethod) {
setError("Selecione um método de pagamento diferente do atual");
return;
}
setLoading(true);
setError(null);
try {
const res = await fetch(
`/api/purchase-intentions/${intentionId}/payment-method`,
{
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ payment_method: selectedMethod }),
}
);
const data = await res.json();
if (!res.ok || !data.success) {
throw new Error(data.error || "Erro ao trocar método de pagamento");
}
// Invalidar cache para atualizar a lista
queryClient.invalidateQueries({ queryKey: ["my-purchase-intentions"] });
queryClient.invalidateQueries({ queryKey: ["purchase-intentions"] });
queryClient.invalidateQueries({ queryKey: ["listings"] });
setOpen(false);
// Opcional: mostrar toast de sucesso
} catch (err) {
setError(err instanceof Error ? err.message : "Erro ao trocar método de pagamento");
} finally {
setLoading(false);
}
};
if (!canChange || availableOptions.length === 0) {
return null;
}
return (
<>
<Button
variant="outline"
size="sm"
onClick={() => {
setOpen(true);
setSelectedMethod(currentPaymentMethod);
setError(null);
}}
className="gap-2"
>
<RefreshCw className="h-4 w-4" />
Trocar Método
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Trocar Método de Pagamento</DialogTitle>
<DialogDescription>
Você pode trocar o método de pagamento apenas uma vez. Escolha o novo método:
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label>Método Atual</Label>
<div className="text-sm text-muted-foreground p-2 bg-muted rounded-md">
{getPaymentMethodLabel(currentPaymentMethod)}
</div>
</div>
<div className="space-y-2">
<Label htmlFor="new-method">Novo Método de Pagamento</Label>
<Select value={selectedMethod} onValueChange={setSelectedMethod}>
<SelectTrigger id="new-method">
<SelectValue placeholder="Selecione um método" />
</SelectTrigger>
<SelectContent>
{availableOptions.map((method) => (
<SelectItem key={method} value={method}>
{getPaymentMethodLabel(method)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{error && (
<div className="bg-destructive/10 text-destructive p-3 rounded-lg text-sm">
{error}
</div>
)}
<div className="flex gap-2 justify-end">
<Button variant="outline" onClick={() => setOpen(false)} disabled={loading}>
Cancelar
</Button>
<Button onClick={handleChange} disabled={loading || selectedMethod === currentPaymentMethod}>
{loading ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Trocando...
</>
) : (
"Confirmar Troca"
)}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</>
);
}
+2
View File
@@ -161,3 +161,5 @@ Apenas tipos primitivos JSON são suportados:
+2
View File
@@ -286,3 +286,5 @@ log: [
+2
View File
@@ -380,3 +380,5 @@ E aproveite a velocidade!
+1 -1
View File
@@ -36,7 +36,7 @@ function getJWTRefreshSecret(): string {
}
// Tempos de expiração
const ACCESS_TOKEN_EXPIRY = "15m"; // 15 minutos
const ACCESS_TOKEN_EXPIRY = "1h"; // 1 hora
const REFRESH_TOKEN_EXPIRY = "7d"; // 7 dias
/**
+139
View File
@@ -0,0 +1,139 @@
/**
* Funções para criar mensagens do sistema no chat
*/
import { connectMongoDB } from "@/lib/mongodb/connection";
import { Chat } from "@/lib/mongodb/models/Chat";
import { Message } from "@/lib/mongodb/models/Message";
import { getSocketIO } from "@/lib/socket/server";
import { secureLogger } from "@/lib/secure-logger";
interface CreateSystemMessageParams {
listingId: number;
buyerId: number;
sellerId: number;
message: string;
metadata?: {
action?: string;
[key: string]: any;
};
}
/**
* Cria uma mensagem do sistema no chat e notifica os participantes
*/
export async function createSystemMessageInChat(
params: CreateSystemMessageParams
): Promise<void> {
try {
await connectMongoDB();
// Gerar chat_id (mesmo formato usado na criação de chat)
const chatId = `${params.listingId}_${params.buyerId}_${params.sellerId}`;
// Buscar ou criar chat
let chat = await Chat.findOne({ chat_id: chatId });
if (!chat) {
// Se o chat não existe, criar (isso pode acontecer se a intenção foi criada antes do chat)
// Buscar dados do listing para cache
const { getListingById } = await import("@/lib/prisma/queries/listings");
const listing = await getListingById(params.listingId);
if (!listing) {
throw new Error("Listing não encontrado");
}
// Buscar dados dos usuários
const { getUserById } = await import("@/lib/prisma/queries/users");
const buyer = await getUserById(params.buyerId);
const seller = await getUserById(params.sellerId);
if (!buyer || !seller) {
throw new Error("Usuário não encontrado");
}
// Buscar personagem principal do comprador e vendedor
const { getMainCharacter } = await import("@/lib/prisma/queries/characters");
const buyerCharacter = await getMainCharacter(params.buyerId);
const sellerCharacter = await getMainCharacter(params.sellerId);
chat = new Chat({
chat_id: chatId,
listing_id: params.listingId,
buyer_id: params.buyerId,
seller_id: params.sellerId,
is_active: true,
buyer_unread_count: 0,
seller_unread_count: 1, // Vendedor será notificado
listing_cache: {
item_name: listing.item_name,
item_image_url: null, // Pode ser preenchido depois se necessário
price_pix: listing.price_pix ? Number(listing.price_pix) : undefined,
price_tibia_coins: listing.price_tibia_coins || undefined,
price_gold_coins: listing.price_gold_coins ? Number(listing.price_gold_coins) : undefined,
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();
}
// Criar mensagem do sistema
const systemMessage = new Message({
chat_id: chatId,
sender_id: 0, // 0 = sistema
content: params.message,
message_type: "system",
metadata: params.metadata || {},
});
await systemMessage.save();
// Atualizar chat
chat.last_message_at = new Date();
chat.last_message_preview = params.message.substring(0, 100);
chat.seller_unread_count += 1; // Notificar vendedor
await chat.save();
// Emitir mensagem via Socket.io para participantes do chat
const io = getSocketIO();
if (io) {
io.to(`chat:${chatId}`).emit("new_message", {
message: {
_id: systemMessage._id.toString(),
chat_id: systemMessage.chat_id,
sender_id: 0,
content: systemMessage.content,
created_at: systemMessage.created_at.toISOString(),
read_at: null,
message_type: "system",
metadata: systemMessage.metadata,
},
});
}
secureLogger.info("✅ Mensagem do sistema criada no chat", {
chatId,
message: params.message,
action: params.metadata?.action,
});
} catch (error) {
secureLogger.error("❌ Erro ao criar mensagem do sistema no chat", {
error: error instanceof Error ? error.message : "Erro desconhecido",
stack: error instanceof Error ? error.stack : undefined,
});
throw error;
}
}
@@ -0,0 +1,13 @@
-- Adicionar campo para contar trocas de método de pagamento
ALTER TABLE purchase_intentions
ADD COLUMN IF NOT EXISTS payment_method_change_count INT DEFAULT 0;
-- Atualizar registros existentes para 0
UPDATE purchase_intentions
SET payment_method_change_count = 0
WHERE payment_method_change_count IS NULL;
-- Adicionar índice para queries de verificação
CREATE INDEX IF NOT EXISTS idx_purchase_intentions_buyer_listing
ON purchase_intentions(buyer_id, listing_id, status);
+6 -3
View File
@@ -18,7 +18,8 @@ import { getPool, query, healthCheck } from "../index";
const MIGRATIONS_DIR = join(__dirname, ".");
// Lista de migrations em ordem
const MIGRATIONS = [ "001_users.sql",
const MIGRATIONS = [
"001_users.sql",
"002_servers.sql",
"003_fix_servers_location.sql",
"004_listings.sql",
@@ -33,9 +34,11 @@ const MIGRATIONS = [ "001_users.sql",
"013_add_trade_item_support.sql",
"014_add_bid_increment.sql",
"015_add_purchase_intentions.sql",
"016_add_payment_method_change_count.sql",
"016_create_unified_items_table.sql",
"017_add_items_foreign_key.sql",
"018_migrate_listings_to_unified_items.sql",];
"018_migrate_listings_to_unified_items.sql",
];
async function runMigrations() {
console.log("🚀 Iniciando execução de migrations...\n");
@@ -84,7 +87,7 @@ async function runMigrations() {
console.log(`📝 Executando migration: ${migrationFile}...`);
// Ler arquivo SQL
const sql = readFileSync(migrationPath, "utf-8");
const sql = readFileSync(migrationPath, "utf-8").replace(/^\uFEFF/, "");
// Executar migration
await query(sql);
+275
View File
@@ -0,0 +1,275 @@
"use client";
import { useState, useEffect, useCallback, useRef } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useSocket } from "./use-socket";
import { useSession } from "./use-session";
import type { Socket } from "socket.io-client";
export interface ChatMessage {
_id: string;
chat_id: string;
sender_id: number;
content: string;
created_at: string;
read_at: string | null;
edited_at: string | null;
message_type: "text" | "system";
metadata?: any;
}
export interface Chat {
chat_id: string;
listing_id: number;
buyer_id: number;
seller_id: number;
created_at: string;
updated_at: string;
last_message_at: string | null;
last_message_preview: string | null;
buyer_unread_count: number;
seller_unread_count: number;
is_active: boolean;
listing_cache: {
item_name: string;
item_image_url?: string;
price_pix?: number;
price_tibia_coins?: number;
price_gold_coins?: number;
server_name: string;
listing_status: string;
};
buyer_cache: {
user_id: number;
username: string;
character_name?: string;
};
seller_cache: {
user_id: number;
username: string;
character_name?: string;
};
}
interface UseChatReturn {
chat: Chat | null;
messages: ChatMessage[];
isLoading: boolean;
isSending: boolean;
error: string | null;
sendMessage: (content: string) => Promise<void>;
loadMoreMessages: () => Promise<void>;
hasMore: boolean;
isTyping: boolean;
otherUserTyping: boolean;
}
/**
* Hook para gerenciar um chat específico
*/
export function useChat(chatId: string | null): UseChatReturn {
const { user } = useSession();
const { socket, isConnected } = useSocket();
const queryClient = useQueryClient();
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [isSending, setIsSending] = useState(false);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(true);
const [isTyping, setIsTyping] = useState(false);
const [otherUserTyping, setOtherUserTyping] = useState(false);
const typingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
// Buscar dados do chat
const { data: chatData, isLoading: isLoadingChat } = useQuery<{
success: boolean;
chat: Chat;
}>({
queryKey: ["chat", chatId],
queryFn: async () => {
if (!chatId) return null;
const res = await fetch(`/api/chats/${chatId}`);
if (!res.ok) throw new Error("Erro ao buscar chat");
return res.json();
},
enabled: !!chatId && !!user,
staleTime: 1000 * 30,
});
// Buscar mensagens
const { data: messagesData, isLoading: isLoadingMessages } = useQuery<{
success: boolean;
messages: ChatMessage[];
pagination: {
page: number;
limit: number;
total: number;
totalPages: number;
};
}>({
queryKey: ["chat-messages", chatId, page],
queryFn: async () => {
if (!chatId) return null;
const res = await fetch(`/api/chats/${chatId}/messages?page=${page}&limit=50`);
if (!res.ok) throw new Error("Erro ao buscar mensagens");
return res.json();
},
enabled: !!chatId && !!user,
staleTime: 1000 * 10,
});
// Atualizar mensagens quando dados mudarem
useEffect(() => {
if (messagesData?.messages) {
if (page === 1) {
setMessages(messagesData.messages);
} else {
// Adicionar mensagens antigas no início
setMessages((prev) => [...messagesData.messages, ...prev]);
}
setHasMore(messagesData.pagination.page < messagesData.pagination.totalPages);
}
}, [messagesData, page]);
// Conectar ao Socket.io quando chatId mudar
useEffect(() => {
if (!socket || !isConnected || !chatId) return;
// Entrar no chat
socket.emit("join_chat", { chat_id: chatId });
// Listener para novas mensagens
const handleNewMessage = (data: { message: ChatMessage }) => {
console.log("[CHAT-DEBUG] useChat: new_message recebido", { message: data.message });
// Verificar se a mensagem já existe para evitar duplicação
setMessages((prev) => {
const messageExists = prev.some((msg) => msg._id === data.message._id);
if (messageExists) {
console.log("[CHAT-DEBUG] Mensagem já existe, ignorando duplicação", { messageId: data.message._id });
return prev;
}
return [...prev, data.message];
});
// Invalidar cache
queryClient.invalidateQueries({ queryKey: ["chat-messages", chatId] });
queryClient.invalidateQueries({ queryKey: ["chat", chatId] });
};
// Listener para indicador de digitação
const handleTyping = (data: { user_id: number; username: string; is_typing: boolean }) => {
if (data.user_id !== user?.userId) {
setOtherUserTyping(data.is_typing);
}
};
socket.on("new_message", handleNewMessage);
socket.on("user_typing", handleTyping);
return () => {
socket.off("new_message", handleNewMessage);
socket.off("user_typing", handleTyping);
};
}, [socket, isConnected, chatId, user, queryClient]);
// Função para enviar mensagem
const sendMessage = useCallback(
async (content: string) => {
if (!chatId || !socket || !isConnected || !content.trim()) return;
console.log("[CHAT-DEBUG] sendMessage chamado", { chatId, content, socketConnected: isConnected });
setIsSending(true);
try {
// Enviar via Socket.io
socket.emit("send_message", {
chat_id: chatId,
content: content.trim(),
});
// REMOVIDO: Otimistic update que causava duplicação
// A mensagem será adicionada automaticamente quando o servidor emitir "new_message"
// Parar de digitar
setIsTyping(false);
if (typingTimeoutRef.current) {
clearTimeout(typingTimeoutRef.current);
}
socket.emit("typing", { chat_id: chatId, is_typing: false });
} catch (error) {
console.error("[CHAT-DEBUG] Erro ao enviar mensagem:", error);
} finally {
setIsSending(false);
}
},
[chatId, socket, isConnected, user]
);
// Função para carregar mais mensagens
const loadMoreMessages = useCallback(async () => {
if (!hasMore || isLoadingMessages) return;
setPage((prev) => prev + 1);
}, [hasMore, isLoadingMessages]);
return {
chat: chatData?.chat || null,
messages,
isLoading: isLoadingChat || isLoadingMessages,
isSending,
error: null,
sendMessage,
loadMoreMessages,
hasMore,
isTyping,
otherUserTyping,
};
}
// Exportar handlers de digitação separadamente se necessário
export function useChatTyping(
socket: Socket | null,
isConnected: boolean,
chatId: string | null
) {
const [isTyping, setIsTyping] = useState(false);
const typingTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const handleTypingStart = useCallback(() => {
if (!socket || !isConnected || !chatId || isTyping) return;
setIsTyping(true);
socket.emit("typing", { chat_id: chatId, is_typing: true });
if (typingTimeoutRef.current) {
clearTimeout(typingTimeoutRef.current);
}
typingTimeoutRef.current = setTimeout(() => {
setIsTyping(false);
socket.emit("typing", { chat_id: chatId, is_typing: false });
}, 3000);
}, [socket, isConnected, chatId, isTyping]);
const handleTypingStop = useCallback(() => {
if (!socket || !isConnected || !chatId || !isTyping) return;
setIsTyping(false);
socket.emit("typing", { chat_id: chatId, is_typing: false });
if (typingTimeoutRef.current) {
clearTimeout(typingTimeoutRef.current);
}
}, [socket, isConnected, chatId, isTyping]);
useEffect(() => {
return () => {
if (typingTimeoutRef.current) {
clearTimeout(typingTimeoutRef.current);
}
};
}, []);
return { handleTypingStart, handleTypingStop };
}
+1
View File
@@ -24,6 +24,7 @@ export interface Listing {
image_url?: string | null;
item_category?: string | null;
seller_character_name?: string | null;
has_pending_intention_for_current_user?: boolean;
}
interface ListingsResponse {
+113
View File
@@ -0,0 +1,113 @@
"use client";
import { useQuery, useQueryClient } from "@tanstack/react-query";
export type PurchaseIntentionStatus =
| "pending"
| "accepted"
| "rejected"
| "expired"
| "completed";
export interface PurchaseIntentionListing {
listing_id: number;
item_id: number;
item_id_unified: number | null;
item_name: string;
quantity: number;
server_name: string;
seller_id: number;
price_pix: number | null;
price_tibia_coins: number | null;
price_gold_coins: number | null;
listing_status: string;
created_at: Date | string;
description: string | null;
trade_item_id: number | null;
trade_item_name: string | null;
trade_item_quantity: number | null;
views_count: number;
favorites_count: number;
is_featured: boolean;
image_url: string | null;
image_local_path: string | null;
item_category: string | null;
seller_character_name: string | null;
seller_username: string | null;
seller_email: string | null;
}
export interface PurchaseIntention {
intention_id: number;
listing_id: number;
buyer_id: number;
payment_method: string;
payment_method_change_count: number;
chat_id: string | null;
status: PurchaseIntentionStatus;
buyer_message: string | null;
seller_response: string | null;
created_at: Date | string;
updated_at: Date | string;
expires_at: Date | string | null;
accepted_at: Date | string | null;
rejected_at: Date | string | null;
listing: PurchaseIntentionListing | null;
}
interface PurchaseIntentionsResponse {
success: boolean;
intentions: PurchaseIntention[];
count: number;
}
/**
* Hook para buscar intenções de compra do usuário autenticado
* Atualiza automaticamente a cada 30 segundos
*/
export function useMyPurchaseIntentions(status?: PurchaseIntentionStatus) {
const queryParams = new URLSearchParams();
if (status) queryParams.set("status", status);
queryParams.set("limit", "100"); // Limite alto para mostrar todas
const { data, isLoading, error, refetch } = useQuery<PurchaseIntentionsResponse>({
queryKey: ["my-purchase-intentions", status],
queryFn: async () => {
const res = await fetch(`/api/purchase-intentions/my?${queryParams.toString()}`);
if (!res.ok) {
if (res.status === 401) {
throw new Error("Não autenticado");
}
throw new Error("Erro ao buscar intenções de compra");
}
return res.json();
},
staleTime: 1000 * 30, // 30 segundos
refetchInterval: 1000 * 30, // Refetch a cada 30 segundos
refetchOnWindowFocus: true,
refetchOnReconnect: true,
enabled: true, // Sempre habilitado (autenticação é verificada no backend)
});
return {
intentions: data?.intentions || [],
count: data?.count || 0,
isLoading,
error,
refetch,
};
}
/**
* Hook para invalidar cache de purchase intentions
*/
export function useInvalidatePurchaseIntentions() {
const queryClient = useQueryClient();
const invalidate = () => {
queryClient.invalidateQueries({ queryKey: ["my-purchase-intentions"] });
};
return invalidate;
}
+1
View File
@@ -6,6 +6,7 @@ export interface SessionUser {
userId: number;
username: string;
email: string;
characterName: string | null;
}
interface SessionResponse {
+93
View File
@@ -0,0 +1,93 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { io, Socket } from "socket.io-client";
import { useSession } from "./use-session";
interface UseSocketReturn {
socket: Socket | null;
isConnected: boolean;
error: string | null;
}
/**
* Hook para gerenciar conexão Socket.io
*/
export function useSocket(): UseSocketReturn {
const { user } = useSession();
const [socket, setSocket] = useState<Socket | null>(null);
const [isConnected, setIsConnected] = useState(false);
const [error, setError] = useState<string | null>(null);
const socketRef = useRef<Socket | null>(null);
useEffect(() => {
if (!user) {
// Desconectar se usuário não estiver autenticado
if (socketRef.current) {
socketRef.current.disconnect();
socketRef.current = null;
setSocket(null);
setIsConnected(false);
}
return;
}
// Conectar ao Socket.io
const connectSocket = async () => {
if (socketRef.current?.connected) {
return;
}
try {
const newSocket = io(process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000", {
path: "/api/socket",
transports: ["websocket", "polling"],
withCredentials: true, // Enviar cookies automaticamente
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: 5,
});
newSocket.on("connect", () => {
setIsConnected(true);
setError(null);
});
newSocket.on("disconnect", () => {
setIsConnected(false);
});
newSocket.on("connect_error", (err) => {
setError(err.message);
setIsConnected(false);
});
socketRef.current = newSocket;
setSocket(newSocket);
} catch (err) {
setError(err instanceof Error ? err.message : "Erro ao conectar");
setIsConnected(false);
}
};
connectSocket();
// Cleanup
return () => {
if (socketRef.current) {
socketRef.current.disconnect();
socketRef.current = null;
setSocket(null);
setIsConnected(false);
}
};
}, [user]);
return {
socket,
isConnected,
error,
};
}
+2 -21
View File
@@ -84,28 +84,9 @@ export function searchItems<T = any>(params: SearchParams): SearchResult<T> {
return { items: [], total: 0 } as SearchResult<T>;
}
try {
// Log básico do schema na primeira chamada
// Schema logging desabilitado para reduzir poluição do console
if (!schemaLogged) {
try {
const tables = db
.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
.all() as { name: string }[];
console.info("[items-db] Tabelas:", tables.map((t) => t.name));
for (const t of tables.slice(0, 5)) {
try {
const cols = db.prepare(`PRAGMA table_info(${t.name})`).all() as any[];
console.info(`[items-db] Colunas ${t.name}:`, cols.map((c) => `${c.name}:${c.type}`));
const sample = db.prepare(`SELECT * FROM ${t.name} LIMIT 3`).all();
console.info(`[items-db] Amostra ${t.name}:`, sample);
} catch (inner) {
console.warn(`[items-db] Falha ao inspecionar ${t.name}:`, (inner as any)?.message);
}
}
} catch (intErr) {
console.warn("[items-db] Falha ao ler schema:", (intErr as any)?.message);
} finally {
schemaLogged = true;
}
schemaLogged = true;
}
const where: string[] = [];
+82
View File
@@ -0,0 +1,82 @@
/**
* Conexão MongoDB usando Mongoose
* Singleton pattern para reutilizar conexão
*/
import mongoose from "mongoose";
function getMongoUrl(): string {
const url = process.env.MONGO_URL;
if (!url) {
throw new Error("MONGO_URL não está definida nas variáveis de ambiente");
}
return url;
}
interface MongooseCache {
conn: typeof mongoose | null;
promise: Promise<typeof mongoose> | null;
}
// Cache global para Next.js (evita múltiplas conexões em hot reload)
declare global {
// eslint-disable-next-line no-var
var mongoose: MongooseCache | undefined;
}
let cached: MongooseCache = global.mongoose || { conn: null, promise: null };
if (!global.mongoose) {
global.mongoose = cached;
}
/**
* Conecta ao MongoDB ou retorna conexão existente
*/
export async function connectMongoDB(): Promise<typeof mongoose> {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
};
cached.promise = mongoose
.connect(getMongoUrl(), opts)
.then((mongoose) => {
// Conexão MongoDB estabelecida (log desabilitado)
return mongoose;
})
.catch((error) => {
console.error("❌ Erro ao conectar MongoDB:", error);
cached.promise = null;
throw error;
});
}
try {
cached.conn = await cached.promise;
} catch (e) {
cached.promise = null;
throw e;
}
return cached.conn;
}
/**
* Desconecta do MongoDB (útil para testes)
*/
export async function disconnectMongoDB(): Promise<void> {
if (cached.conn) {
await mongoose.disconnect();
cached.conn = null;
cached.promise = null;
}
}
+138
View File
@@ -0,0 +1,138 @@
/**
* Model Chat - Representa uma conversa entre comprador e vendedor
*/
import mongoose, { Schema, model, models } from "mongoose";
export interface IChat {
chat_id: string; // ID único: `${listing_id}_${buyer_id}_${seller_id}`
listing_id: number; // ID do anúncio (PostgreSQL)
buyer_id: number; // ID do comprador (PostgreSQL)
seller_id: number; // ID do vendedor (PostgreSQL)
created_at: Date;
updated_at: Date;
last_message_at: Date | null;
last_message_preview: string | null;
buyer_unread_count: number;
seller_unread_count: number;
is_active: boolean; // Chat ativo (anúncio ainda disponível)
// Dados cached do anúncio (para performance)
listing_cache: {
item_name: string;
item_image_url?: string;
price_pix?: number;
price_tibia_coins?: number;
price_gold_coins?: number;
server_name: string;
listing_status: string;
};
// Dados cached dos usuários
buyer_cache: {
user_id: number;
username: string;
character_name?: string;
};
seller_cache: {
user_id: number;
username: string;
character_name?: string;
};
}
const ChatSchema = new Schema<IChat>(
{
chat_id: {
type: String,
required: true,
unique: true,
index: true,
},
listing_id: {
type: Number,
required: true,
index: true,
},
buyer_id: {
type: Number,
required: true,
index: true,
},
seller_id: {
type: Number,
required: true,
index: true,
},
created_at: {
type: Date,
default: Date.now,
index: true,
},
updated_at: {
type: Date,
default: Date.now,
},
last_message_at: {
type: Date,
default: null,
index: true,
},
last_message_preview: {
type: String,
default: null,
maxlength: 100,
},
buyer_unread_count: {
type: Number,
default: 0,
},
seller_unread_count: {
type: Number,
default: 0,
},
is_active: {
type: Boolean,
default: true,
index: true,
},
listing_cache: {
item_name: { type: String, required: true },
item_image_url: { type: String, default: null },
price_pix: { type: Number, default: null },
price_tibia_coins: { type: Number, default: null },
price_gold_coins: { type: Number, default: null },
server_name: { type: String, required: true },
listing_status: { type: String, required: true },
},
buyer_cache: {
user_id: { type: Number, required: true },
username: { type: String, required: true },
character_name: { type: String, default: null },
},
seller_cache: {
user_id: { type: Number, required: true },
username: { type: String, required: true },
character_name: { type: String, default: null },
},
},
{
timestamps: false, // Usamos campos manuais
collection: "chats",
}
);
// Índices compostos para queries eficientes
ChatSchema.index({ buyer_id: 1, updated_at: -1 });
ChatSchema.index({ seller_id: 1, updated_at: -1 });
ChatSchema.index({ listing_id: 1, buyer_id: 1, seller_id: 1 });
// Atualizar updated_at antes de salvar
ChatSchema.pre("save", function (next) {
this.updated_at = new Date();
next();
});
export const Chat = models.Chat || model<IChat>("Chat", ChatSchema);
+81
View File
@@ -0,0 +1,81 @@
/**
* Model Message - Representa uma mensagem em um chat
*/
import mongoose, { Schema, model, models } from "mongoose";
export interface IMessage {
chat_id: string; // Referência ao chat
sender_id: number; // ID do remetente (PostgreSQL)
content: string; // Conteúdo da mensagem (sanitizado)
created_at: Date;
read_at: Date | null; // Quando foi lida
edited_at: Date | null; // Se foi editada
deleted_at: Date | null; // Soft delete
// Metadados
message_type: "text" | "system"; // System para mensagens automáticas
metadata?: {
listing_id?: number;
action?: "listing_updated" | "listing_sold" | "price_changed";
};
}
const MessageSchema = new Schema<IMessage>(
{
chat_id: {
type: String,
required: true,
index: true,
},
sender_id: {
type: Number,
required: true,
index: true,
},
content: {
type: String,
required: true,
maxlength: 1000,
trim: true,
},
created_at: {
type: Date,
default: Date.now,
index: true,
},
read_at: {
type: Date,
default: null,
},
edited_at: {
type: Date,
default: null,
},
deleted_at: {
type: Date,
default: null,
},
message_type: {
type: String,
enum: ["text", "system"],
default: "text",
},
metadata: {
type: Schema.Types.Mixed,
default: null,
},
},
{
timestamps: false, // Usamos campos manuais
collection: "messages",
}
);
// Índices compostos para queries eficientes
MessageSchema.index({ chat_id: 1, created_at: -1 }); // Para buscar mensagens de um chat ordenadas
MessageSchema.index({ chat_id: 1, sender_id: 1, created_at: -1 });
MessageSchema.index({ sender_id: 1, created_at: -1 });
export const Message = models.Message || model<IMessage>("Message", MessageSchema);
+1 -4
View File
@@ -12,10 +12,7 @@ const globalForPrisma = globalThis as unknown as {
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log:
process.env.NODE_ENV === "development"
? ["query", "error", "warn"]
: ["error"],
log: ["error"], // Apenas erros, sem queries
});
if (process.env.NODE_ENV !== "production") {
+15
View File
@@ -69,6 +69,21 @@ export async function getUserCharacters(userId: number): Promise<Character[]> {
});
}
/**
* Busca personagem principal de um usuário
*/
export async function getMainCharacter(userId: number): Promise<Character | null> {
return await prisma.userCharacter.findFirst({
where: {
user_id: userId,
is_main: true,
},
orderBy: [
{ created_at: "asc" },
],
});
}
/**
* Busca personagem principal de um usuário em um servidor específico
*/
-6
View File
@@ -36,7 +36,6 @@ export interface SearchItemsParams {
* Busca um item por ID unificado
*/
export async function getItemById(itemId: number): Promise<Item | null> {
// @ts-expect-error - Prisma Client pode não ter sido gerado ainda
const item = await prisma.item.findUnique({
where: { item_id: itemId },
});
@@ -56,7 +55,6 @@ export async function getItemById(itemId: number): Promise<Item | null> {
* Busca um item por nome (exato ou similar)
*/
export async function getItemByName(itemName: string): Promise<Item | null> {
// @ts-expect-error - Prisma Client pode não ter sido gerado ainda
const item = await prisma.item.findFirst({
where: {
item_name: {
@@ -91,7 +89,6 @@ export async function searchItems(
pageSize = 24,
} = params;
// @ts-expect-error - ItemWhereInput pode não estar disponível se Prisma Client não foi gerado
const where: Prisma.ItemWhereInput = {};
if (q) {
@@ -109,10 +106,8 @@ export async function searchItems(
where.rarity = rarity;
}
// @ts-expect-error - Prisma Client pode não ter sido gerado ainda
const total = await prisma.item.count({ where });
// @ts-expect-error - Prisma Client pode não ter sido gerado ainda
const items = await prisma.item.findMany({
where,
orderBy: { item_name: "asc" },
@@ -138,7 +133,6 @@ export async function getItemBySource(
sourceTableName: string,
sourceTableId: number
): Promise<Item | null> {
// @ts-expect-error - Prisma Client pode não ter sido gerado ainda
const item = await prisma.item.findUnique({
where: {
source_table_name_source_table_id: {
+121
View File
@@ -20,6 +20,7 @@ export interface PurchaseIntention {
listing_id: number;
buyer_id: number;
payment_method: string;
payment_method_change_count: number;
status: PurchaseIntentionStatus;
buyer_message: string | null;
seller_response: string | null;
@@ -251,3 +252,123 @@ export async function hasPendingIntention(
return count > 0;
}
/**
* Busca intenção pendente de um comprador para um listing específico
*/
export async function getPendingIntentionByBuyerAndListing(
listingId: number,
buyerId: number
): Promise<PurchaseIntention | null> {
return await prisma.purchaseIntention.findFirst({
where: {
listing_id: listingId,
buyer_id: buyerId,
status: "pending",
},
include: {
listing: {
select: {
listing_id: true,
item_name: true,
seller_id: true,
},
},
buyer: {
select: {
user_id: true,
username: true,
email: true,
},
},
},
orderBy: {
created_at: "desc",
},
}) as PurchaseIntention | null;
}
/**
* Atualiza o método de pagamento de uma intenção
*/
export async function updatePurchaseIntentionPaymentMethod(
intentionId: number,
newPaymentMethod: PaymentMethod
): Promise<PurchaseIntention> {
// Buscar intenção atual
const intention = await prisma.purchaseIntention.findUnique({
where: { intention_id: intentionId },
});
if (!intention) {
throw new Error("Intenção não encontrada");
}
// Verificar se pode trocar (máximo 1 troca)
if (intention.payment_method_change_count >= 1) {
throw new Error("Você já atingiu o limite de trocas de método de pagamento");
}
// Verificar se o novo método é diferente
if (intention.payment_method === newPaymentMethod) {
throw new Error("O novo método de pagamento deve ser diferente do atual");
}
// Atualizar
return await prisma.purchaseIntention.update({
where: { intention_id: intentionId },
data: {
payment_method: newPaymentMethod,
payment_method_change_count: intention.payment_method_change_count + 1,
updated_at: new Date(),
},
include: {
listing: {
select: {
listing_id: true,
item_name: true,
seller_id: true,
},
},
buyer: {
select: {
user_id: true,
username: true,
email: true,
},
},
},
}) as PurchaseIntention;
}
/**
* Retorna os IDs de anúncios com intenções pendentes para um comprador
*/
export async function getPendingIntentionListingIdsForBuyer(
buyerId: number,
listingIds: number[]
): Promise<number[]> {
if (listingIds.length === 0) {
return [];
}
const intentions = await prisma.purchaseIntention.findMany({
where: {
buyer_id: buyerId,
status: "pending",
listing_id: {
in: listingIds,
},
},
select: {
listing_id: true,
},
});
const uniqueIds = new Set<number>();
intentions.forEach((intention) => {
uniqueIds.add(intention.listing_id);
});
return Array.from(uniqueIds);
}
+270
View File
@@ -0,0 +1,270 @@
/**
* Socket.io Server
* Integrado com Next.js
*/
import { Server as SocketIOServer } from "socket.io";
import type { Server as HTTPServer } from "http";
import { verifyAccessToken } from "@/lib/auth/jwt";
import { secureLogger } from "@/lib/secure-logger";
import { Message } from "@/lib/mongodb/models/Message";
import { Chat } from "@/lib/mongodb/models/Chat";
import { connectMongoDB } from "@/lib/mongodb/connection";
let io: SocketIOServer | null = null;
/**
* Inicializa o servidor Socket.io
*/
export function initSocketIO(httpServer?: HTTPServer): SocketIOServer {
if (io) {
return io;
}
if (!httpServer) {
throw new Error("HTTP Server é necessário para inicializar Socket.io");
}
io = new SocketIOServer(httpServer, {
path: "/api/socket",
addTrailingSlash: false,
cors: {
origin: process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true,
},
});
// Middleware de autenticação
io.use(async (socket, next) => {
try {
// Tentar obter token do auth primeiro
const token = socket.handshake.auth.token;
if (token) {
const payload = verifyAccessToken(token);
if (payload) {
socket.data.userId = payload.userId;
socket.data.username = payload.username;
return next();
}
}
// Se não tiver token, tentar via cookie sessionId
const cookies = socket.handshake.headers.cookie;
if (cookies) {
const sessionIdMatch = cookies.match(/sessionId=([^;]+)/);
if (sessionIdMatch) {
const sessionId = sessionIdMatch[1];
const { getSession } = await import("@/lib/redis/session");
const session = await getSession(sessionId);
if (session) {
const payload = verifyAccessToken(session.accessToken);
if (payload) {
socket.data.userId = payload.userId;
socket.data.username = payload.username;
return next();
}
}
}
}
return next(new Error("Token não fornecido ou inválido"));
} catch (error) {
secureLogger.error("Erro na autenticação Socket.io", {
error: error instanceof Error ? error.message : "Erro desconhecido",
});
next(new Error("Erro na autenticação"));
}
});
// Event handlers
io.on("connection", (socket) => {
const userId = socket.data.userId;
const username = socket.data.username;
// Cliente conectado (log desabilitado para reduzir poluição do console)
// Entrar em rooms dos chats do usuário
socket.on("join_chats", async () => {
try {
await connectMongoDB();
// Buscar todos os chats do usuário
const chats = await Chat.find({
$or: [{ buyer_id: userId }, { seller_id: userId }],
is_active: true,
}).select("chat_id");
chats.forEach((chat) => {
socket.join(`chat:${chat.chat_id}`);
});
// Usuário entrou nos chats (log desabilitado)
} catch (error) {
secureLogger.error("Erro ao entrar em chats", {
userId,
error: error instanceof Error ? error.message : "Erro desconhecido",
});
}
});
// Entrar em um chat específico
socket.on("join_chat", async (data: { chat_id: string }) => {
try {
const { chat_id } = data;
// Verificar se o usuário pertence ao chat
await connectMongoDB();
const chat = await Chat.findOne({ chat_id });
if (!chat) {
socket.emit("error", { message: "Chat não encontrado" });
return;
}
if (chat.buyer_id !== userId && chat.seller_id !== userId) {
socket.emit("error", { message: "Você não tem permissão para acessar este chat" });
return;
}
socket.join(`chat:${chat_id}`);
// Marcar mensagens como lidas
await Message.updateMany(
{
chat_id,
sender_id: { $ne: userId },
read_at: null,
},
{
$set: { read_at: new Date() },
}
);
// Atualizar contador de não lidas
if (chat.buyer_id === userId) {
chat.buyer_unread_count = 0;
} else {
chat.seller_unread_count = 0;
}
await chat.save();
// Usuário entrou no chat (log desabilitado)
} catch (error) {
secureLogger.error("Erro ao entrar no chat", {
userId,
error: error instanceof Error ? error.message : "Erro desconhecido",
});
socket.emit("error", { message: "Erro ao entrar no chat" });
}
});
// Enviar mensagem
socket.on("send_message", async (data: { chat_id: string; content: string }) => {
try {
const { chat_id, content } = data;
if (!content || content.trim().length === 0) {
socket.emit("error", { message: "Mensagem não pode estar vazia" });
return;
}
if (content.length > 1000) {
socket.emit("error", { message: "Mensagem muito longa (máximo 1000 caracteres)" });
return;
}
await connectMongoDB();
// Verificar se o chat existe e o usuário pertence a ele
const chat = await Chat.findOne({ chat_id });
if (!chat) {
socket.emit("error", { message: "Chat não encontrado" });
return;
}
if (chat.buyer_id !== userId && chat.seller_id !== userId) {
socket.emit("error", { message: "Você não tem permissão para enviar mensagens neste chat" });
return;
}
// Criar mensagem
const message = new Message({
chat_id,
sender_id: userId,
content: content.trim(),
message_type: "text",
});
await message.save();
// Atualizar chat
chat.last_message_at = new Date();
chat.last_message_preview = content.substring(0, 100);
// Atualizar contador de não lidas
if (chat.buyer_id === userId) {
chat.seller_unread_count += 1;
} else {
chat.buyer_unread_count += 1;
}
await chat.save();
// Enviar mensagem para todos no chat (exceto o remetente)
io!.to(`chat:${chat_id}`).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,
read_at: message.read_at,
message_type: message.message_type,
},
});
// Confirmar para o remetente
socket.emit("message_sent", {
message_id: message._id.toString(),
});
// Mensagem enviada (log desabilitado)
} catch (error) {
secureLogger.error("Erro ao enviar mensagem", {
userId,
error: error instanceof Error ? error.message : "Erro desconhecido",
});
socket.emit("error", { message: "Erro ao enviar mensagem" });
}
});
// Indicador de "digitando..."
socket.on("typing", (data: { chat_id: string; is_typing: boolean }) => {
const { chat_id, is_typing } = data;
socket.to(`chat:${chat_id}`).emit("user_typing", {
user_id: userId,
username: username,
is_typing,
});
});
// Desconexão
socket.on("disconnect", () => {
// Cliente desconectado (log desabilitado)
});
});
return io;
}
/**
* Obtém a instância do servidor Socket.io
*/
export function getSocketIO(): SocketIOServer | null {
return io;
}
+19
View File
@@ -4,3 +4,22 @@ import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
/**
* Formata uma data para string relativa (ex: "há 2 horas")
*/
export function formatTimeAgo(date: Date | string): string {
const dateObj = typeof date === "string" ? new Date(date) : date;
const seconds = Math.floor((new Date().getTime() - dateObj.getTime()) / 1000);
if (seconds < 60) return "há alguns segundos";
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `há ${minutes} ${minutes === 1 ? "minuto" : "minutos"}`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `há ${hours} ${hours === 1 ? "hora" : "horas"}`;
const days = Math.floor(hours / 24);
if (days < 30) return `há ${days} ${days === 1 ? "dia" : "dias"}`;
const months = Math.floor(days / 30);
if (months < 12) return `há ${months} ${months === 1 ? "mês" : "meses"}`;
const years = Math.floor(months / 12);
return `há ${years} ${years === 1 ? "ano" : "anos"}`;
}
+28
View File
@@ -0,0 +1,28 @@
/**
* Schemas de validação para Chat usando Zod
*/
import { z } from "zod";
import sanitizeHtml from "sanitize-html";
// Schema para criar chat
export const createChatSchema = z.object({
listing_id: z.number().int().positive(),
buyer_message: z.string().max(1000).optional(),
});
// Schema para enviar mensagem
export const sendMessageSchema = z.object({
content: z
.string()
.min(1, "Mensagem não pode estar vazia")
.max(1000, "Mensagem muito longa (máximo 1000 caracteres)")
.transform((val) => sanitizeHtml(val.trim(), { allowedTags: [], allowedAttributes: {} })),
});
// Schema para query params de mensagens
export const getMessagesSchema = z.object({
page: z.coerce.number().int().positive().default(1),
limit: z.coerce.number().int().positive().max(100).default(50),
});
+7 -2
View File
@@ -3,9 +3,11 @@
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"dev": "tsx server.ts",
"dev:next": "next dev --turbopack",
"build": "next build --turbopack",
"start": "next start",
"start": "NODE_ENV=production tsx server.ts",
"start:next": "next start",
"lint": "biome check",
"format": "biome format --write",
"db:migrate": "tsx lib/db/migrations/run-migrations.ts",
@@ -53,6 +55,7 @@
"cobe": "^0.6.5",
"jsonwebtoken": "^9.0.2",
"lucide-react": "^0.540.0",
"mongoose": "^8.19.3",
"motion": "^12.23.24",
"next": "15.5.0",
"next-intl": "^4.4.0",
@@ -66,6 +69,8 @@
"recharts": "^3.3.0",
"redis": "^5.9.0",
"sanitize-html": "^2.17.0",
"socket.io": "^4.8.1",
"socket.io-client": "^4.8.1",
"tailwind-merge": "^3.3.1",
"validator": "^13.15.20",
"zod": "^4.1.12"
+377
View File
@@ -86,6 +86,9 @@ importers:
lucide-react:
specifier: ^0.540.0
version: 0.540.0([email protected])
mongoose:
specifier: ^8.19.3
version: 8.19.3
motion:
specifier: ^12.23.24
version: 12.23.24([email protected]([email protected]))([email protected])
@@ -125,6 +128,12 @@ importers:
sanitize-html:
specifier: ^2.17.0
version: 2.17.0
socket.io:
specifier: ^4.8.1
version: 4.8.1
socket.io-client:
specifier: ^4.8.1
version: 4.8.1
tailwind-merge:
specifier: ^3.3.1
version: 3.3.1
@@ -568,6 +577,9 @@ packages:
'@jridgewell/[email protected]':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
'@mongodb-js/[email protected]':
resolution: {integrity: sha512-QgA5AySqB27cGTXBFmnpifAi7HxoGUeezwo6p9dI03MuDB6Pp33zgclqVb6oVK3j6I9Vesg0+oojW2XxB59SGg==}
'@next/[email protected]':
resolution: {integrity: sha512-sDaprBAfzCQiOgo2pO+LhnV0Wt2wBgartjrr+dpcTORYVnnXD0gwhHhiiyIih9hQbq+JnbqH4odgcFWhqCGidw==}
@@ -1126,6 +1138,9 @@ packages:
'@schummar/[email protected]':
resolution: {integrity: sha512-bXHSaW5jRTmke9Vd0h5P7BtWZG9Znqb8gSDxZnxaGSJnGwPLDPfS+3g0BKzeWqzgZPsIVZkM7m2tbo18cm5HBw==}
'@socket.io/[email protected]':
resolution: {integrity: sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==}
'@standard-schema/[email protected]':
resolution: {integrity: sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==}
@@ -1246,6 +1261,9 @@ packages:
'@types/[email protected]':
resolution: {integrity: sha512-aBGj/dULrimR1XDZLtG9JwxX1b4HPRF6CX9Yfwh3NvstZEm1ZL7RBnel4keCPSqs1ANRu1u2Aoz9R+VmtjYuTg==}
'@types/[email protected]':
resolution: {integrity: sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==}
'@types/[email protected]':
resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==}
@@ -1302,6 +1320,16 @@ packages:
'@types/[email protected]':
resolution: {integrity: sha512-7bcUmDyS6PN3EuD9SlGGOxM77F8WLVsrwkxyWxKnxzmXoequ6c7741QBrANq6htVRGOITJ7z72mTP6Z4XyuG+Q==}
'@types/[email protected]':
resolution: {integrity: sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==}
'@types/[email protected]':
resolution: {integrity: sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==}
[email protected]:
resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==}
engines: {node: '>= 0.6'}
[email protected]:
resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==}
engines: {node: '>=10'}
@@ -1309,6 +1337,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
[email protected]:
resolution: {integrity: sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==}
engines: {node: ^4.5.0 || >= 5.9}
[email protected]:
resolution: {integrity: sha512-cU8v/EGSrnH+HnxV2z0J7/blxH8gq7Xh2JFT6Aroax7UohdmiJJlxApMxtKfuI7z68NvvVcmR78k2LbT6efhRg==}
engines: {node: '>= 18'}
@@ -1323,6 +1355,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==}
[email protected]:
resolution: {integrity: sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==}
engines: {node: '>=16.20.1'}
[email protected]:
resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==}
@@ -1377,6 +1413,14 @@ packages:
resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==}
engines: {node: ^14.18.0 || >=16.10.0}
[email protected]:
resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}
engines: {node: '>= 0.6'}
[email protected]:
resolution: {integrity: sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==}
engines: {node: '>= 0.10'}
[email protected]:
resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==}
@@ -1424,6 +1468,24 @@ packages:
resolution: {integrity: sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==}
engines: {node: '>=12'}
[email protected]:
resolution: {integrity: sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==}
engines: {node: '>=6.0'}
peerDependencies:
supports-color: '*'
peerDependenciesMeta:
supports-color:
optional: true
[email protected]:
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
engines: {node: '>=6.0'}
peerDependencies:
supports-color: '*'
peerDependenciesMeta:
supports-color:
optional: true
[email protected]:
resolution: {integrity: sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==}
@@ -1493,6 +1555,17 @@ packages:
[email protected]:
resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}
[email protected]:
resolution: {integrity: sha512-T0iLjnyNWahNyv/lcjS2y4oE358tVS/SYQNxYXGAJ9/GLgH4VCvOQ/mhTjqU88mLZCQgiG8RIegFHYCdVC+j5w==}
[email protected]:
resolution: {integrity: sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==}
engines: {node: '>=10.0.0'}
[email protected]:
resolution: {integrity: sha512-ZCkIjSYNDyGn0R6ewHDtXgns/Zre/NT6Agvq1/WobF7JXgFff4SeDroKiCO3fNJreU9YG429Sc81o4w5ok/W5g==}
engines: {node: '>=10.2.0'}
[email protected]:
resolution: {integrity: sha512-d4lC8xfavMeBjzGr2vECC3fsGXziXZQyJxD868h2M/mBI3PwAuODxAkLkq5HYuvrPYcUtiLzsTo8U3PgX3Ocww==}
engines: {node: '>=10.13.0'}
@@ -1612,6 +1685,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==}
[email protected]:
resolution: {integrity: sha512-C3iHfuGUXK2u8/ipq9LfjFfXFxAZMQJJq7vLS45r3D9Y2xQ/m4S8zaR4zMLFWh9AsNPXmcFfUDhTEO8UIC/V6Q==}
engines: {node: '>=12.0.0'}
[email protected]:
resolution: {integrity: sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A==}
engines: {node: '>= 12.0.0'}
@@ -1715,6 +1792,17 @@ packages:
[email protected]:
resolution: {integrity: sha512-2N21sPY9Ws53PZvsEpVtNuSW+ScYbQdp4b9qUaL+9QkHUrGFKo56Lg9Emg5s9V/qrtNBmiR01sYhUOwu3H+VOw==}
[email protected]:
resolution: {integrity: sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==}
[email protected]:
resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}
engines: {node: '>= 0.6'}
[email protected]:
resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}
engines: {node: '>= 0.6'}
[email protected]:
resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==}
engines: {node: '>=10'}
@@ -1725,6 +1813,40 @@ packages:
[email protected]:
resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==}
[email protected]:
resolution: {integrity: sha512-rMO7CGo/9BFwyZABcKAWL8UJwH/Kc2x0g72uhDWzG48URRax5TCIcJ7Rc3RZqffZzO/Gwff/jyKwCU9TN8gehA==}
[email protected]:
resolution: {integrity: sha512-Tl6MEIU3K4Rq3TSHd+sZQqRBoGlFsOgNrH5ltAcFBV62Re3Fd+FcaVf8uSEQFOJ51SDowDVttBTONMfoYWrWlQ==}
engines: {node: '>=16.20.1'}
peerDependencies:
'@aws-sdk/credential-providers': ^3.188.0
'@mongodb-js/zstd': ^1.1.0 || ^2.0.0
gcp-metadata: ^5.2.0
kerberos: ^2.0.1
mongodb-client-encryption: '>=6.0.0 <7'
snappy: ^7.3.2
socks: ^2.7.1
peerDependenciesMeta:
'@aws-sdk/credential-providers':
optional: true
'@mongodb-js/zstd':
optional: true
gcp-metadata:
optional: true
kerberos:
optional: true
mongodb-client-encryption:
optional: true
snappy:
optional: true
socks:
optional: true
[email protected]:
resolution: {integrity: sha512-fTAGaIohkk8wCggMuBuqTVD4YrM1/J8cBr1ekqzFqtz65qkLjtX2dcy3NH1e+2rk2365dyrrsPAnt4YTxBhEiQ==}
engines: {node: '>=16.20.1'}
[email protected]:
resolution: {integrity: sha512-n5yolOs0TQQBRUFImrRfs/+6X4p3Q4n1dUEqt/H58Vx7OW6RF+foWEgmTVDhIWJIMXOuNNL0apKH2S16en9eiA==}
@@ -1745,6 +1867,14 @@ packages:
react-dom:
optional: true
[email protected]:
resolution: {integrity: sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==}
engines: {node: '>=4.0.0'}
[email protected]:
resolution: {integrity: sha512-iQMncpmEK8R8ncT8HJGsGc9Dsp8xcgYMVSbs5jgnm1lFHTZqMJTUWTDx1LBO8+mK3tPNZWFLBghQEIOULSTHZg==}
engines: {node: '>=14.0.0'}
[email protected]:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
@@ -1756,6 +1886,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==}
[email protected]:
resolution: {integrity: sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==}
engines: {node: '>= 0.6'}
[email protected]:
resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==}
engines: {node: '>= 0.6'}
@@ -1924,6 +2058,10 @@ packages:
[email protected]:
resolution: {integrity: sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==}
[email protected]:
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
engines: {node: '>=6'}
[email protected]:
resolution: {integrity: sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==}
@@ -2051,16 +2189,37 @@ packages:
resolution: {integrity: sha512-FUH39xp3SBPnxWvd5iib1X8XY7J0K0X7d93sie9CJg2PO8/7gmg89Nve6OjItK53/MlAushNNxteBYfM6DEuoA==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
[email protected]:
resolution: {integrity: sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==}
[email protected]:
resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==}
[email protected]:
resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==}
[email protected]:
resolution: {integrity: sha512-eLDQas5dzPgOWCk9GuuJC2lBqItuhKI4uxGgo9aIV7MYbk2h9Q6uULEh8WBzThoI7l+qU9Ast9fVUmkqPP9wYg==}
[email protected]:
resolution: {integrity: sha512-hJVXfu3E28NmzGk8o1sHhN3om52tRvwYeidbj7xKy2eIIse5IoKX3USlS6Tqt3BHAtflLIkCQBkzVrEEfWUyYQ==}
engines: {node: '>=10.0.0'}
[email protected]:
resolution: {integrity: sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==}
engines: {node: '>=10.0.0'}
[email protected]:
resolution: {integrity: sha512-oZ7iUCxph8WYRHHcjBEc9unw3adt5CmSNlppj/5Q4k2RIrhl8Z5yY2Xr4j9zj0+wzVZ0bxmYoGSzKJnRl6A4yg==}
engines: {node: '>=10.2.0'}
[email protected]:
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
[email protected]:
resolution: {integrity: sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==}
[email protected]:
resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==}
engines: {node: '>= 10.x'}
@@ -2109,6 +2268,10 @@ packages:
resolution: {integrity: sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==}
engines: {node: '>=18'}
[email protected]:
resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==}
engines: {node: '>=18'}
[email protected]:
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
@@ -2168,12 +2331,40 @@ packages:
resolution: {integrity: sha512-KxPOq3V2LmfQPP4eqf3Mq/zrT0Dqp2Vmx2Bn285LwVahLc+CsxOM0crBHczm8ijlcjZ0Q5Xd6LW3z3odTPnlrw==}
engines: {node: '>= 0.10'}
[email protected]:
resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==}
engines: {node: '>= 0.8'}
[email protected]:
resolution: {integrity: sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==}
[email protected]:
resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==}
engines: {node: '>=12'}
[email protected]:
resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==}
engines: {node: '>=18'}
[email protected]:
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
[email protected]:
resolution: {integrity: sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==}
engines: {node: '>=10.0.0'}
peerDependencies:
bufferutil: ^4.0.1
utf-8-validate: '>=5.0.2'
peerDependenciesMeta:
bufferutil:
optional: true
utf-8-validate:
optional: true
[email protected]:
resolution: {integrity: sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==}
engines: {node: '>=0.4.0'}
[email protected]:
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
engines: {node: '>=0.4'}
@@ -2458,6 +2649,10 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.5
'@mongodb-js/[email protected]':
dependencies:
sparse-bitfield: 3.0.3
'@next/[email protected]': {}
'@next/[email protected]':
@@ -2990,6 +3185,8 @@ snapshots:
'@schummar/[email protected]': {}
'@socket.io/[email protected]': {}
'@standard-schema/[email protected]': {}
'@standard-schema/[email protected]': {}
@@ -3088,6 +3285,10 @@ snapshots:
'@types/[email protected]': {}
'@types/[email protected]':
dependencies:
'@types/node': 20.19.23
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -3145,12 +3346,25 @@ snapshots:
'@types/[email protected]': {}
'@types/[email protected]': {}
'@types/[email protected]':
dependencies:
'@types/webidl-conversions': 7.0.3
[email protected]:
dependencies:
mime-types: 2.1.35
negotiator: 0.6.3
[email protected]:
dependencies:
tslib: 2.8.1
[email protected]: {}
[email protected]: {}
[email protected]:
dependencies:
node-addon-api: 8.5.0
@@ -3171,6 +3385,8 @@ snapshots:
inherits: 2.0.4
readable-stream: 3.6.2
[email protected]: {}
[email protected]: {}
[email protected]:
@@ -3225,6 +3441,13 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]:
dependencies:
object-assign: 4.1.1
vary: 1.1.2
[email protected]: {}
[email protected]:
@@ -3265,6 +3488,14 @@ snapshots:
[email protected]: {}
[email protected]:
dependencies:
ms: 2.1.3
[email protected]:
dependencies:
ms: 2.1.3
[email protected]: {}
[email protected]: {}
@@ -3324,6 +3555,36 @@ snapshots:
dependencies:
once: 1.4.0
[email protected]:
dependencies:
'@socket.io/component-emitter': 3.1.2
debug: 4.3.7
engine.io-parser: 5.2.3
ws: 8.17.1
xmlhttprequest-ssl: 2.1.2
transitivePeerDependencies:
- bufferutil
- supports-color
- utf-8-validate
[email protected]: {}
[email protected]:
dependencies:
'@types/cors': 2.8.19
'@types/node': 20.19.23
accepts: 1.3.8
base64id: 2.0.0
cookie: 0.7.2
cors: 2.8.5
debug: 4.3.7
engine.io-parser: 5.2.3
ws: 8.17.1
transitivePeerDependencies:
- bufferutil
- supports-color
- utf-8-validate
[email protected]:
dependencies:
graceful-fs: 4.2.11
@@ -3463,6 +3724,8 @@ snapshots:
jwa: 1.4.2
safe-buffer: 5.2.1
[email protected]: {}
[email protected]:
optional: true
@@ -3538,12 +3801,50 @@ snapshots:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
[email protected]: {}
[email protected]: {}
[email protected]:
dependencies:
mime-db: 1.52.0
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]:
dependencies:
'@types/whatwg-url': 11.0.5
whatwg-url: 14.2.0
[email protected]:
dependencies:
'@mongodb-js/saslprep': 1.3.2
bson: 6.10.4
mongodb-connection-string-url: 3.0.2
[email protected]:
dependencies:
bson: 6.10.4
kareem: 2.6.3
mongodb: 6.20.0
mpath: 0.9.0
mquery: 5.0.0
ms: 2.1.3
sift: 17.1.3
transitivePeerDependencies:
- '@aws-sdk/credential-providers'
- '@mongodb-js/zstd'
- gcp-metadata
- kerberos
- mongodb-client-encryption
- snappy
- socks
- supports-color
[email protected]:
dependencies:
motion-utils: 12.23.6
@@ -3558,12 +3859,22 @@ snapshots:
react: 19.1.0
react-dom: 19.1.0([email protected])
[email protected]: {}
[email protected]:
dependencies:
debug: 4.4.3
transitivePeerDependencies:
- supports-color
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]):
@@ -3738,6 +4049,8 @@ snapshots:
end-of-stream: 1.4.5
once: 1.4.0
[email protected]: {}
[email protected]: {}
[email protected]: {}
@@ -3898,6 +4211,8 @@ snapshots:
'@img/sharp-win32-x64': 0.34.4
optional: true
[email protected]: {}
[email protected]: {}
[email protected]:
@@ -3906,8 +4221,53 @@ snapshots:
once: 1.4.0
simple-concat: 1.0.1
[email protected]:
dependencies:
debug: 4.3.7
ws: 8.17.1
transitivePeerDependencies:
- bufferutil
- supports-color
- utf-8-validate
[email protected]:
dependencies:
'@socket.io/component-emitter': 3.1.2
debug: 4.3.7
engine.io-client: 6.6.3
socket.io-parser: 4.2.4
transitivePeerDependencies:
- bufferutil
- supports-color
- utf-8-validate
[email protected]:
dependencies:
'@socket.io/component-emitter': 3.1.2
debug: 4.3.7
transitivePeerDependencies:
- supports-color
[email protected]:
dependencies:
accepts: 1.3.8
base64id: 2.0.0
cors: 2.8.5
debug: 4.3.7
engine.io: 6.6.4
socket.io-adapter: 2.5.5
socket.io-parser: 4.2.4
transitivePeerDependencies:
- bufferutil
- supports-color
- utf-8-validate
[email protected]: {}
[email protected]:
dependencies:
memory-pager: 1.5.0
[email protected]: {}
[email protected]:
@@ -3946,6 +4306,10 @@ snapshots:
[email protected]: {}
[email protected]:
dependencies:
punycode: 2.3.1
[email protected]: {}
[email protected]:
@@ -3995,6 +4359,8 @@ snapshots:
[email protected]: {}
[email protected]: {}
[email protected]:
dependencies:
'@types/d3-array': 3.2.2
@@ -4012,8 +4378,19 @@ snapshots:
d3-time: 3.1.0
d3-timer: 3.0.1
[email protected]: {}
[email protected]:
dependencies:
tr46: 5.1.1
webidl-conversions: 7.0.0
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
[email protected]: {}
+53 -38
View File
@@ -1,6 +1,3 @@
// Prisma Schema para PostgreSQL (Banco Principal da Aplicação)
// URL: DATABASE_URL_APP
generator client {
provider = "prisma-client-js"
}
@@ -37,10 +34,7 @@ model User {
inventory UserInventory[]
favorites UserFavorite[]
telemetry_events TelemetryEvent[]
purchaseIntentions PurchaseIntention[]
item Item? @relation("ListingItem", fields: [item_id_unified], references: [item_id], onDelete: SetNull)
tradeItem Item? @relation("TradeItem", fields: [trade_item_id_unified], references: [item_id], onDelete: SetNull) @relation("BuyerIntentions")
purchaseIntentions PurchaseIntention[] @relation("BuyerIntentions")
@@index([email])
@@index([username])
@@ -104,7 +98,6 @@ model Item {
updated_at DateTime @default(now()) @updatedAt
listings Listing[] @relation("ListingItem")
tradeListings Listing[] @relation("TradeItem")
@@unique([source_table_name, source_table_id])
@@index([item_name])
@@ -114,27 +107,47 @@ model Item {
}
model Listing {
listing_id Int @id @default(autoincrement())
seller_id Int
item_id Int // Legacy - manter para compatibilidade
item_id_unified Int? // Nova referência para tabela items
item_name String @db.VarChar(255)
quantity Int @default(1) Int?
min_bid_increment Decimal? @db.Decimal(10, 2)
initial_price_pix Decimal? @db.Decimal(10, 2)
listing_id Int @id @default(autoincrement())
seller_id Int
item_id Int // Legacy - manter para compatibilidade
item_id_unified Int?
item_name String @db.VarChar(255)
quantity Int @default(1)
server_name String @db.VarChar(50)
price_pix Decimal? @db.Decimal(10, 2)
price_tibia_coins Int?
price_gold_coins BigInt?
is_auction Boolean @default(false)
current_bid_amount Decimal? @db.Decimal(10, 2)
current_bidder_id Int?
auction_ends_at DateTime?
description String? @db.Text
listing_status String @default("active") @db.VarChar(20)
created_at DateTime @default(now())
updated_at DateTime @default(now()) @updatedAt
sold_at DateTime?
views_count Int @default(0)
is_featured Boolean @default(false)
favorites_count Int @default(0)
inquiries_count Int @default(0)
price_history Json?
expires_at DateTime?
trade_item_id Int?
trade_item_name String?
trade_item_quantity Int?
min_bid_increment Decimal? @db.Decimal(10, 2)
initial_price_pix Decimal? @db.Decimal(10, 2)
initial_price_tibia_coins Int?
initial_price_gold_coins BigInt?
seller User @relation(fields: [seller_id], references: [user_id], onDelete: Cascade)
bids Bid[]
transactions Transaction[]
analytics AdAnalytics?
telemetry_events TelemetryEvent[]
favorites UserFavorite[]
purchaseIntentions PurchaseIntention[]
item Item? @relation("ListingItem", fields: [item_id_unified], references: [item_id], onDelete: SetNull)
tradeItem Item? @relation("TradeItem", fields: [trade_item_id_unified], references: [item_id], onDelete: SetNull)
seller User @relation(fields: [seller_id], references: [user_id], onDelete: Cascade)
bids Bid[]
transactions Transaction[]
analytics AdAnalytics?
telemetry_events TelemetryEvent[]
favorites UserFavorite[]
purchaseIntentions PurchaseIntention[]
item Item? @relation("ListingItem", fields: [item_id_unified], references: [item_id], onDelete: SetNull)
@@index([listing_status])
@@index([item_id])
@@ -290,18 +303,19 @@ model UserFavorite {
}
model PurchaseIntention {
intention_id Int @id @default(autoincrement())
listing_id Int
buyer_id Int
payment_method String @db.VarChar(20)
status String @default("pending") @db.VarChar(20)
buyer_message String? @db.Text
seller_response String? @db.Text
created_at DateTime @default(now())
updated_at DateTime @updatedAt
expires_at DateTime?
accepted_at DateTime?
rejected_at DateTime?
intention_id Int @id @default(autoincrement())
listing_id Int
buyer_id Int
payment_method String @db.VarChar(20)
payment_method_change_count Int @default(0)
status String @default("pending") @db.VarChar(20)
buyer_message String? @db.Text
seller_response String? @db.Text
created_at DateTime @default(now())
updated_at DateTime @updatedAt
expires_at DateTime?
accepted_at DateTime?
rejected_at DateTime?
listing Listing @relation(fields: [listing_id], references: [listing_id], onDelete: Cascade)
buyer User @relation("BuyerIntentions", fields: [buyer_id], references: [user_id], onDelete: Cascade)
@@ -310,6 +324,7 @@ model PurchaseIntention {
@@index([buyer_id])
@@index([status])
@@index([created_at(sort: Desc)])
@@index([buyer_id, listing_id, status])
@@map("purchase_intentions")
}
+2
View File
@@ -36,3 +36,5 @@ if ($LASTEXITCODE -eq 0) {
+2
View File
@@ -37,3 +37,5 @@ fi
+42
View File
@@ -0,0 +1,42 @@
/**
* Custom Server para Next.js 15
* Inicializa Socket.io junto com o servidor HTTP
*/
import { createServer } from "http";
import { parse } from "url";
import next from "next";
import { initSocketIO } from "./lib/socket/server";
const dev = process.env.NODE_ENV !== "production";
const hostname = process.env.HOSTNAME || "localhost";
const port = parseInt(process.env.PORT || "3000", 10);
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const httpServer = createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url!, true);
await handle(req, res, parsedUrl);
} catch (err) {
console.error("Error occurred handling", req.url, err);
res.statusCode = 500;
res.end("internal server error");
}
});
// Inicializar Socket.io
initSocketIO(httpServer);
httpServer
.once("error", (err: NodeJS.ErrnoException) => {
console.error(err);
process.exit(1);
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
});
});