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,
});
}
}
+50 -2
View File
@@ -34,7 +34,12 @@ export async function POST(
}
const body = await request.json();
const { payment_method, buyer_message } = body;
const {
payment_method,
buyer_message,
custom_offer_amount,
custom_offer_currency,
} = body;
if (!payment_method || !["pix", "tibia_coins", "gold_coins", "trade"].includes(payment_method)) {
return NextResponse.json(
@@ -94,6 +99,42 @@ export async function POST(
);
}
let normalizedOfferValue: number | null = null;
let normalizedOfferCurrency: string | null = null;
if (custom_offer_amount !== undefined && custom_offer_amount !== null) {
if (!["pix", "tibia_coins", "gold_coins"].includes(payment_method)) {
return NextResponse.json(
{
success: false,
error: "Ofertas personalizadas só são permitidas para métodos monetários (PIX, Tibia Coins ou Gold Coins).",
},
{ status: 400 }
);
}
const numericOffer = Number(custom_offer_amount);
if (Number.isNaN(numericOffer) || numericOffer <= 0) {
return NextResponse.json(
{
success: false,
error: "Valor da oferta personalizada deve ser numérico e maior que zero.",
},
{ status: 400 }
);
}
normalizedOfferCurrency =
custom_offer_currency && ["pix", "tibia_coins", "gold_coins"].includes(custom_offer_currency)
? custom_offer_currency
: payment_method;
normalizedOfferValue =
normalizedOfferCurrency === "pix"
? Number(numericOffer.toFixed(2))
: Math.floor(numericOffer);
}
// Verificar se já existe uma intenção pendente
const existingIntention = await getPendingIntentionByBuyerAndListing(listingId, auth.userId);
if (existingIntention) {
@@ -130,6 +171,8 @@ export async function POST(
buyer_id: auth.userId,
payment_method: payment_method as any,
buyer_message: buyer_message || undefined,
custom_offer_amount: normalizedOfferValue ?? undefined,
custom_offer_currency: normalizedOfferCurrency as any,
});
// Criar notificação para o vendedor
@@ -137,7 +180,10 @@ export async function POST(
user_id: listing.seller_id,
notification_type: "purchase",
title: "Nova intenção de compra!",
message: `Alguém manifestou interesse em comprar seu item "${listing.item_name}" por ${payment_method.toUpperCase()}`,
message:
normalizedOfferValue && normalizedOfferCurrency
? `Alguém fez uma oferta de ${normalizedOfferCurrency === "pix" ? `R$ ${normalizedOfferValue.toFixed(2)}` : `${normalizedOfferValue.toLocaleString()} ${normalizedOfferCurrency === "tibia_coins" ? "TC" : "GP"}`} pelo item "${listing.item_name}".`
: `Alguém manifestou interesse em comprar seu item "${listing.item_name}" por ${payment_method.toUpperCase()}`,
related_id: listingId,
send_whatsapp: false,
});
@@ -152,6 +198,8 @@ export async function POST(
listing_price_pix: listing.price_pix ? Number(listing.price_pix) : null,
listing_price_tc: listing.price_tibia_coins || null,
listing_price_gp: listing.price_gold_coins ? Number(listing.price_gold_coins) : null,
custom_offer_amount: normalizedOfferValue,
custom_offer_currency: normalizedOfferCurrency,
},
});
+50 -2
View File
@@ -33,7 +33,12 @@ export async function POST(
}
const body = await request.json();
const { payment_method, buyer_message } = body; // 'pix' | 'tc' | 'gp' | 'trade'
const {
payment_method,
buyer_message,
custom_offer_amount,
custom_offer_currency,
} = body;
if (!payment_method) {
return NextResponse.json(
@@ -98,6 +103,42 @@ export async function POST(
);
}
let normalizedOfferValue: number | null = null;
let normalizedOfferCurrency: string | null = null;
if (custom_offer_amount !== undefined && custom_offer_amount !== null) {
if (!["pix", "tibia_coins", "gold_coins"].includes(normalizedMethod)) {
return NextResponse.json(
{
success: false,
error: "Ofertas personalizadas só são permitidas para métodos monetários (PIX, Tibia Coins ou Gold Coins).",
},
{ status: 400 }
);
}
const numericOffer = Number(custom_offer_amount);
if (Number.isNaN(numericOffer) || numericOffer <= 0) {
return NextResponse.json(
{
success: false,
error: "Valor da oferta personalizada deve ser numérico e maior que zero.",
},
{ status: 400 }
);
}
normalizedOfferCurrency =
custom_offer_currency && ["pix", "tibia_coins", "gold_coins"].includes(custom_offer_currency)
? custom_offer_currency
: normalizedMethod;
normalizedOfferValue =
normalizedOfferCurrency === "pix"
? Number(numericOffer.toFixed(2))
: Math.floor(numericOffer);
}
// Verificar se já existe uma intenção pendente
const existingIntention = await getPendingIntentionByBuyerAndListing(listingId, auth.userId);
if (existingIntention) {
@@ -134,6 +175,8 @@ export async function POST(
buyer_id: auth.userId,
payment_method: normalizedMethod as any,
buyer_message: buyer_message || undefined,
custom_offer_amount: normalizedOfferValue ?? undefined,
custom_offer_currency: normalizedOfferCurrency as any,
});
// Criar notificação para o vendedor
@@ -141,7 +184,10 @@ export async function POST(
user_id: listing.seller_id,
notification_type: "purchase",
title: "Nova intenção de compra!",
message: `Alguém manifestou interesse em comprar seu item "${listing.item_name}" por ${normalizedMethod.toUpperCase()}`,
message:
normalizedOfferValue && normalizedOfferCurrency
? `Alguém fez uma oferta de ${normalizedOfferCurrency === "pix" ? `R$ ${normalizedOfferValue.toFixed(2)}` : `${normalizedOfferValue.toLocaleString()} ${normalizedOfferCurrency === "tibia_coins" ? "TC" : "GP"}`} pelo item "${listing.item_name}".`
: `Alguém manifestou interesse em comprar seu item "${listing.item_name}" por ${normalizedMethod.toUpperCase()}.`,
related_id: listingId,
send_whatsapp: false,
});
@@ -156,6 +202,8 @@ export async function POST(
listing_price_pix: listing.price_pix ? Number(listing.price_pix) : null,
listing_price_tc: listing.price_tibia_coins || null,
listing_price_gp: listing.price_gold_coins ? Number(listing.price_gold_coins) : null,
custom_offer_amount: normalizedOfferValue,
custom_offer_currency: normalizedOfferCurrency,
},
});