- 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.
176 lines
5.5 KiB
TypeScript
176 lines
5.5 KiB
TypeScript
/**
|
|
* 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 }
|
|
);
|
|
}
|
|
}
|
|
|