- wrap root layout with QueryProvider for React Query - replace market UnderConstruction placeholder with MarketClient and real data fetching - implement search, pagination, and sort via search params using getActiveListings - add necessary client components and queries - update dependencies (e.g., prisma, pkg-types)
178 lines
5.5 KiB
TypeScript
178 lines
5.5 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { secureLogger } from "@/lib/secure-logger";
|
|
import { requireAuth } from "@/lib/auth/middleware";
|
|
import { getListingById } from "@/lib/prisma/queries/listings";
|
|
import {
|
|
getPurchaseIntentionById,
|
|
updatePurchaseIntentionStatus,
|
|
} from "@/lib/prisma/queries/purchase-intentions";
|
|
import { createNotification } from "@/lib/prisma/queries/notifications";
|
|
|
|
/**
|
|
* GET /api/listings/[id]/intentions/[intentionId]
|
|
* Busca uma intenção específica
|
|
*/
|
|
export async function GET(
|
|
request: NextRequest,
|
|
{ params }: { params: { id: string; intentionId: string } }
|
|
) {
|
|
try {
|
|
const authResult = await requireAuth(request);
|
|
if (authResult instanceof NextResponse) return authResult;
|
|
|
|
const intentionId = parseInt(params.intentionId, 10);
|
|
if (isNaN(intentionId)) {
|
|
return NextResponse.json(
|
|
{ success: false, error: "ID de intenção inválido" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const intention = await getPurchaseIntentionById(intentionId);
|
|
if (!intention) {
|
|
return NextResponse.json(
|
|
{ success: false, error: "Intenção não encontrada" },
|
|
{ status: 404 }
|
|
);
|
|
}
|
|
|
|
// Verificar permissões: vendedor ou comprador
|
|
if (intention.listing?.seller_id !== authResult.userId && intention.buyer_id !== authResult.userId) {
|
|
return NextResponse.json(
|
|
{ success: false, error: "Você não tem permissão para ver esta intenção" },
|
|
{ status: 403 }
|
|
);
|
|
}
|
|
|
|
return NextResponse.json(
|
|
{
|
|
success: true,
|
|
intention,
|
|
},
|
|
{ status: 200 }
|
|
);
|
|
} catch (error) {
|
|
secureLogger.error("❌ Erro ao buscar intenção", {
|
|
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ção" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* PATCH /api/listings/[id]/intentions/[intentionId]
|
|
* Atualiza o status de uma intenção (aceitar/rejeitar)
|
|
*/
|
|
export async function PATCH(
|
|
request: NextRequest,
|
|
{ params }: { params: { id: string; intentionId: string } }
|
|
) {
|
|
try {
|
|
const authResult = await requireAuth(request);
|
|
if (authResult instanceof NextResponse) return authResult;
|
|
|
|
const intentionId = parseInt(params.intentionId, 10);
|
|
if (isNaN(intentionId)) {
|
|
return NextResponse.json(
|
|
{ success: false, error: "ID de intenção inválido" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const body = await request.json();
|
|
const { status, seller_response } = body;
|
|
|
|
if (!status || !["accepted", "rejected"].includes(status)) {
|
|
return NextResponse.json(
|
|
{ success: false, error: "Status inválido. Use 'accepted' ou 'rejected'" },
|
|
{ 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 vendedor
|
|
if (intention.listing?.seller_id !== authResult.userId) {
|
|
return NextResponse.json(
|
|
{ success: false, error: "Apenas o vendedor pode aceitar ou rejeitar intenções" },
|
|
{ status: 403 }
|
|
);
|
|
}
|
|
|
|
// Verificar se a intenção ainda está pendente
|
|
if (intention.status !== "pending") {
|
|
return NextResponse.json(
|
|
{ success: false, error: `Esta intenção já foi ${intention.status}` },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Verificar se o anúncio ainda está disponível (ativo ou em escrow)
|
|
const listing = await getListingById(intention.listing_id);
|
|
if (!listing || (listing.listing_status !== "active" && listing.listing_status !== "in_escrow")) {
|
|
return NextResponse.json(
|
|
{ success: false, error: "Anúncio não está mais disponível" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
// Atualizar status da intenção (não altera status do listing)
|
|
const updatedIntention = await updatePurchaseIntentionStatus(
|
|
intentionId,
|
|
status,
|
|
seller_response
|
|
);
|
|
|
|
// Criar notificação para o comprador
|
|
await createNotification({
|
|
user_id: intention.buyer_id,
|
|
notification_type: status === "accepted" ? "purchase" : "system",
|
|
title: status === "accepted" ? "Intenção aceita!" : "Intenção rejeitada",
|
|
message: status === "accepted"
|
|
? `O vendedor aceitou sua intenção de compra do item "${intention.listing?.item_name}"`
|
|
: `O vendedor rejeitou sua intenção de compra do item "${intention.listing?.item_name}"`,
|
|
related_id: intention.listing_id,
|
|
send_whatsapp: false,
|
|
});
|
|
|
|
secureLogger.info(`✅ Intenção ${status === "accepted" ? "aceita" : "rejeitada"}`, {
|
|
userId: authResult.userId,
|
|
intentionId,
|
|
listingId: intention.listing_id,
|
|
buyerId: intention.buyer_id,
|
|
});
|
|
|
|
return NextResponse.json(
|
|
{
|
|
success: true,
|
|
intention: updatedIntention,
|
|
message: `Intenção ${status === "accepted" ? "aceita" : "rejeitada"} com sucesso`,
|
|
},
|
|
{ status: 200 }
|
|
);
|
|
} catch (error) {
|
|
secureLogger.error("❌ Erro ao atualizar intenção", {
|
|
error: error instanceof Error ? error.message : "Erro desconhecido",
|
|
stack: error instanceof Error ? error.stack : undefined,
|
|
});
|
|
|
|
return NextResponse.json(
|
|
{ success: false, error: "Erro ao atualizar intenção" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|