feat(market): add Minha Intenções tab with panel, hook, and badge
- Introduced "Minhas Intenções" tab visible only to logged-in users. - Integrated MyPurchaseIntentionsPanel and useMyPurchaseIntentions hook. - Added tab badge showing count of pending intentions. - Extended session API to include user’s main character for downstream features.
This commit is contained in:
1 parent
f35fee944d
commit
7f42def478
55 files changed
+4906
-95
No files matched your search
@@ -0,0 +1,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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user