feat: enhance purchase intentions with chat integration and offer tracking

- Added MongoDB chat/message integration for seller responses
- Improved seller response validation and default messaging
- Integrated automatic chat creation/update when responding to intentions
- Added highest custom offer fields to listing queries and models
- Enhanced listing data with top offer information for buyers
This commit is contained in:
Evandro Fonseca Junior committed 2025-11-08 11:51:21 -03:00
1 parent d27526e026
commit d8e7d5d7e6
19 files changed
+806 -58

No files matched your search

@@ -7,6 +7,11 @@ import {
updatePurchaseIntentionStatus,
} from "@/lib/prisma/queries/purchase-intentions";
import { createNotification } from "@/lib/prisma/queries/notifications";
import { connectMongoDB } from "@/lib/mongodb/connection";
import { Chat } from "@/lib/mongodb/models/Chat";
import { Message } from "@/lib/mongodb/models/Message";
import { getUserById } from "@/lib/prisma/queries/users";
import { getMainCharacter } from "@/lib/prisma/queries/characters";
/**
* GET /api/listings/[id]/intentions/[intentionId]
@@ -88,6 +93,10 @@ export async function PATCH(
const body = await request.json();
const { status, seller_response } = body;
const sellerResponse =
typeof seller_response === "string" && seller_response.trim().length > 0
? seller_response
: undefined;
if (!status || !["accepted", "rejected"].includes(status)) {
return NextResponse.json(
@@ -134,9 +143,17 @@ export async function PATCH(
const updatedIntention = await updatePurchaseIntentionStatus(
intentionId,
status,
seller_response
sellerResponse
);
await sendSellerResponseToChat({
listing,
intention,
status,
sellerResponse,
sellerId: authResult.userId,
});
// Criar notificação para o comprador
await createNotification({
user_id: intention.buyer_id,
@@ -177,3 +194,94 @@ export async function PATCH(
}
}
async function sendSellerResponseToChat({
listing,
intention,
status,
sellerResponse,
sellerId,
}: {
listing: Awaited<ReturnType<typeof getListingById>>;
intention: Exclude<Awaited<ReturnType<typeof getPurchaseIntentionById>>, null>;
status: "accepted" | "rejected";
sellerResponse?: string;
sellerId: number;
}) {
try {
if (!listing) return;
const contentBase = sellerResponse?.trim()
? sellerResponse.trim()
: status === "accepted"
? "O vendedor aceitou sua intenção de compra."
: "O vendedor rejeitou sua intenção de compra.";
const content = `[Intenções] ${contentBase}`;
if (!content.trim()) return;
const chatId = `${listing.listing_id}_${intention.buyer_id}_${listing.seller_id}`;
await connectMongoDB();
let chat = await Chat.findOne({ chat_id: chatId });
if (!chat) {
const [buyer, seller, buyerCharacter, sellerCharacter] = await Promise.all([
getUserById(intention.buyer_id),
getUserById(listing.seller_id),
getMainCharacter(intention.buyer_id),
getMainCharacter(listing.seller_id),
]);
chat = new Chat({
chat_id: chatId,
listing_id: listing.listing_id,
buyer_id: intention.buyer_id,
seller_id: listing.seller_id,
buyer_unread_count: 0,
seller_unread_count: 0,
is_active: listing.listing_status === "active",
listing_cache: {
item_name: listing.item_name,
item_image_url: null,
price_pix: listing.price_pix ?? null,
price_tibia_coins: listing.price_tibia_coins ?? null,
price_gold_coins: listing.price_gold_coins ?? null,
server_name: listing.server_name,
listing_status: listing.listing_status,
},
buyer_cache: {
user_id: buyer?.user_id ?? intention.buyer_id,
username: buyer?.username ?? intention.buyer?.username ?? "Comprador",
character_name: buyerCharacter?.character_name || null,
},
seller_cache: {
user_id: seller?.user_id ?? listing.seller_id,
username: seller?.username ?? "Vendedor",
character_name: sellerCharacter?.character_name || null,
},
});
await chat.save();
}
const message = new Message({
chat_id: chat.chat_id,
sender_id: sellerId,
content,
message_type: "text",
});
await message.save();
chat.last_message_at = new Date();
chat.last_message_preview = content.substring(0, 100);
chat.buyer_unread_count = (chat.buyer_unread_count || 0) + 1;
chat.is_active = listing.listing_status === "active";
await chat.save();
} catch (error) {
secureLogger.error("❌ Falha ao enviar resposta para o chat", {
error: error instanceof Error ? error.message : "Erro desconhecido",
stack: error instanceof Error ? error.stack : undefined,
});
}
}