525 lines
16 KiB
TypeScript
525 lines
16 KiB
TypeScript
"use client";
|
|
|
|
import { useQueryClient } from "@tanstack/react-query";
|
|
import {
|
|
CheckCircle2,
|
|
Clock,
|
|
Loader2,
|
|
MessageSquare,
|
|
ShoppingBag,
|
|
ShoppingCart,
|
|
User,
|
|
XCircle,
|
|
} from "lucide-react";
|
|
import { useEffect, useState } from "react";
|
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
|
import { Badge } from "@/components/ui/badge";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "@/components/ui/dialog";
|
|
import { Label } from "@/components/ui/label";
|
|
import { Separator } from "@/components/ui/separator";
|
|
import { Textarea } from "@/components/ui/textarea";
|
|
import { useSession } from "@/lib/hooks/use-session";
|
|
|
|
interface PurchaseIntention {
|
|
intention_id: number;
|
|
buyer_id: number;
|
|
payment_method: string;
|
|
status: "pending" | "accepted" | "rejected" | "expired" | "completed";
|
|
buyer_message: string | null;
|
|
seller_response: string | null;
|
|
created_at: string;
|
|
custom_offer_amount: number | null;
|
|
custom_offer_currency: string | null;
|
|
custom_offer_created_at: string | null;
|
|
buyer?: {
|
|
user_id: number;
|
|
username: string;
|
|
email: string;
|
|
};
|
|
}
|
|
|
|
interface IntentionDetailModalProps {
|
|
open: boolean;
|
|
onOpenChange: (open: boolean) => void;
|
|
intention: PurchaseIntention;
|
|
listingId: number;
|
|
onUpdate?: () => void;
|
|
}
|
|
|
|
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();
|
|
}
|
|
}
|
|
|
|
function getStatusBadge(status: string) {
|
|
switch (status) {
|
|
case "pending":
|
|
return (
|
|
<Badge
|
|
variant="secondary"
|
|
className="bg-yellow-500/20 text-yellow-700 dark:text-yellow-400"
|
|
>
|
|
<Clock className="h-3 w-3 mr-1" />
|
|
Pendente
|
|
</Badge>
|
|
);
|
|
case "accepted":
|
|
return (
|
|
<Badge
|
|
variant="secondary"
|
|
className="bg-green-500/20 text-green-700 dark:text-green-400"
|
|
>
|
|
<CheckCircle2 className="h-3 w-3 mr-1" />
|
|
Aceita
|
|
</Badge>
|
|
);
|
|
case "rejected":
|
|
return (
|
|
<Badge
|
|
variant="secondary"
|
|
className="bg-red-500/20 text-red-700 dark:text-red-400"
|
|
>
|
|
<XCircle className="h-3 w-3 mr-1" />
|
|
Rejeitada
|
|
</Badge>
|
|
);
|
|
default:
|
|
return <Badge variant="secondary">{status}</Badge>;
|
|
}
|
|
}
|
|
|
|
function formatCustomOffer(
|
|
intention: PurchaseIntention,
|
|
): { value: string; date: string | null } | null {
|
|
if (
|
|
intention.custom_offer_amount === null ||
|
|
intention.custom_offer_amount === undefined ||
|
|
!intention.custom_offer_currency
|
|
) {
|
|
return null;
|
|
}
|
|
|
|
const amount = intention.custom_offer_amount;
|
|
let value: string;
|
|
|
|
switch (intention.custom_offer_currency) {
|
|
case "pix":
|
|
value = `R$ ${amount.toFixed(2)}`;
|
|
break;
|
|
case "tibia_coins":
|
|
value = `${Math.round(amount).toLocaleString("pt-BR")} TC`;
|
|
break;
|
|
case "gold_coins":
|
|
value = `${Math.round(amount).toLocaleString("pt-BR")} GP`;
|
|
break;
|
|
default:
|
|
value = amount.toLocaleString("pt-BR");
|
|
}
|
|
|
|
return {
|
|
value,
|
|
date: intention.custom_offer_created_at
|
|
? new Date(intention.custom_offer_created_at).toLocaleString("pt-BR")
|
|
: null,
|
|
};
|
|
}
|
|
|
|
export function IntentionDetailModal({
|
|
open,
|
|
onOpenChange,
|
|
intention,
|
|
listingId,
|
|
onUpdate,
|
|
}: IntentionDetailModalProps) {
|
|
const { user } = useSession();
|
|
const queryClient = useQueryClient();
|
|
const [sellerResponse, setSellerResponse] = useState("");
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [listing, setListing] = useState<{
|
|
seller_id: number;
|
|
listing_status: string;
|
|
} | null>(null);
|
|
const [showMarkSoldDialog, setShowMarkSoldDialog] = useState(false);
|
|
const [markingSold, setMarkingSold] = useState(false);
|
|
|
|
// Buscar detalhes do listing para verificar se usuário é dono e status
|
|
useEffect(() => {
|
|
if (open && listingId) {
|
|
fetch(`/api/listings/${listingId}`)
|
|
.then((res) => res.json())
|
|
.then((data) => {
|
|
if (data.success && data.listing) {
|
|
setListing(data.listing);
|
|
}
|
|
})
|
|
.catch((err) => console.error("Erro ao buscar listing:", err));
|
|
}
|
|
}, [open, listingId]);
|
|
|
|
const isOwner = user && listing && user.userId === listing.seller_id;
|
|
const canMarkAsSold =
|
|
isOwner &&
|
|
listing &&
|
|
(listing.listing_status === "active" ||
|
|
listing.listing_status === "in_escrow");
|
|
const canAcceptOrReject = intention.status === "pending";
|
|
const customOffer = formatCustomOffer(intention);
|
|
|
|
useEffect(() => {
|
|
if (open) {
|
|
setSellerResponse(intention.seller_response ?? "");
|
|
}
|
|
}, [open, intention.seller_response]);
|
|
|
|
const handleAccept = async () => {
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
try {
|
|
const res = await fetch(
|
|
`/api/listings/${listingId}/intentions/${intention.intention_id}`,
|
|
{
|
|
method: "PATCH",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
status: "accepted",
|
|
seller_response: sellerResponse || undefined,
|
|
}),
|
|
},
|
|
);
|
|
|
|
const data = await res.json();
|
|
|
|
if (!res.ok || !data.success) {
|
|
throw new Error(data.error || "Erro ao aceitar intenção");
|
|
}
|
|
|
|
if (onUpdate) onUpdate();
|
|
onOpenChange(false);
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : "Erro ao aceitar intenção");
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleReject = async () => {
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
try {
|
|
const res = await fetch(
|
|
`/api/listings/${listingId}/intentions/${intention.intention_id}`,
|
|
{
|
|
method: "PATCH",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
status: "rejected",
|
|
seller_response: sellerResponse || undefined,
|
|
}),
|
|
},
|
|
);
|
|
|
|
const data = await res.json();
|
|
|
|
if (!res.ok || !data.success) {
|
|
throw new Error(data.error || "Erro ao rejeitar intenção");
|
|
}
|
|
|
|
if (onUpdate) onUpdate();
|
|
onOpenChange(false);
|
|
} catch (err) {
|
|
setError(
|
|
err instanceof Error ? err.message : "Erro ao rejeitar intenção",
|
|
);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleMarkAsSold = async () => {
|
|
setMarkingSold(true);
|
|
try {
|
|
const res = await fetch(`/api/listings/${listingId}/mark-sold`, {
|
|
method: "POST",
|
|
});
|
|
|
|
if (!res.ok) {
|
|
const data = await res.json();
|
|
throw new Error(data.error || "Erro ao marcar como vendido");
|
|
}
|
|
|
|
// Invalidar cache para atualizar a lista
|
|
queryClient.invalidateQueries({ queryKey: ["listings"] });
|
|
queryClient.invalidateQueries({ queryKey: ["my-listings"] });
|
|
|
|
if (onUpdate) onUpdate();
|
|
setShowMarkSoldDialog(false);
|
|
onOpenChange(false);
|
|
} catch (error) {
|
|
console.error("Erro ao marcar como vendido:", error);
|
|
alert(
|
|
error instanceof Error ? error.message : "Erro ao marcar como vendido",
|
|
);
|
|
} finally {
|
|
setMarkingSold(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
|
<DialogContent className="sm:max-w-[600px]">
|
|
<DialogHeader>
|
|
<DialogTitle className="flex items-center gap-2">
|
|
Intenção de Compra
|
|
{getStatusBadge(intention.status)}
|
|
</DialogTitle>
|
|
<DialogDescription>
|
|
Detalhes da intenção de compra de{" "}
|
|
{intention.buyer?.username || "usuário"}
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
<div className="space-y-4">
|
|
{/* Informações do comprador */}
|
|
<div className="bg-muted p-4 rounded-lg">
|
|
<div className="flex items-center gap-3">
|
|
<Avatar className="h-12 w-12">
|
|
<AvatarFallback>
|
|
{intention.buyer?.username.charAt(0).toUpperCase() || "?"}
|
|
</AvatarFallback>
|
|
</Avatar>
|
|
<div className="flex-1">
|
|
<div className="flex items-center gap-2 mb-1">
|
|
<User className="h-4 w-4 text-muted-foreground" />
|
|
<span className="font-semibold">
|
|
{intention.buyer?.username || "Usuário"}
|
|
</span>
|
|
</div>
|
|
<p className="text-sm text-muted-foreground">
|
|
{intention.buyer?.email || "Email não disponível"}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<Separator />
|
|
|
|
{/* Informações da intenção */}
|
|
<div className="space-y-3">
|
|
<div className="grid grid-cols-2 gap-4">
|
|
<div>
|
|
<Label className="text-xs text-muted-foreground">
|
|
Método de Pagamento
|
|
</Label>
|
|
<div className="flex items-center gap-2 mt-1">
|
|
<ShoppingCart className="h-4 w-4 text-muted-foreground" />
|
|
<span className="font-medium">
|
|
{getPaymentMethodLabel(intention.payment_method)}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
<div>
|
|
<Label className="text-xs text-muted-foreground">
|
|
Data de Criação
|
|
</Label>
|
|
<div className="flex items-center gap-2 mt-1">
|
|
<Clock className="h-4 w-4 text-muted-foreground" />
|
|
<span className="text-sm">
|
|
{new Date(intention.created_at).toLocaleString("pt-BR")}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{customOffer && (
|
|
<div className="bg-primary/5 border border-primary/20 rounded-lg p-3 space-y-1">
|
|
<Label className="text-xs text-primary uppercase tracking-wide">
|
|
Oferta do Comprador
|
|
</Label>
|
|
<div className="text-base font-semibold text-primary">
|
|
{customOffer.value}
|
|
</div>
|
|
{customOffer.date && (
|
|
<p className="text-[11px] text-primary/70">
|
|
Enviada em {customOffer.date}
|
|
</p>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{/* Mensagem do comprador */}
|
|
{intention.buyer_message && (
|
|
<div>
|
|
<Label className="text-xs text-muted-foreground mb-1 block">
|
|
Mensagem do Comprador
|
|
</Label>
|
|
<div className="bg-muted p-3 rounded-lg">
|
|
<div className="flex items-start gap-2">
|
|
<MessageSquare className="h-4 w-4 text-muted-foreground mt-0.5" />
|
|
<p className="text-sm flex-1">{intention.buyer_message}</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Resposta do vendedor */}
|
|
{intention.seller_response && (
|
|
<div>
|
|
<Label className="text-xs text-muted-foreground mb-1 block">
|
|
Sua Resposta
|
|
</Label>
|
|
<div className="bg-muted p-3 rounded-lg">
|
|
<p className="text-sm">{intention.seller_response}</p>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Campo de resposta (apenas se pendente) */}
|
|
{canAcceptOrReject && (
|
|
<div className="space-y-2">
|
|
<Label htmlFor="seller-response">Resposta (Opcional)</Label>
|
|
<Textarea
|
|
id="seller-response"
|
|
placeholder="Deixe uma mensagem para o comprador..."
|
|
value={sellerResponse}
|
|
onChange={(e) => setSellerResponse(e.target.value)}
|
|
rows={3}
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{error && (
|
|
<div className="bg-destructive/10 text-destructive p-3 rounded-lg text-sm">
|
|
{error}
|
|
</div>
|
|
)}
|
|
|
|
<Separator />
|
|
|
|
{/* Botões de ação */}
|
|
<div className="flex gap-2 justify-end flex-wrap">
|
|
{canMarkAsSold && (
|
|
<Button
|
|
variant="default"
|
|
onClick={() => setShowMarkSoldDialog(true)}
|
|
disabled={loading || markingSold}
|
|
className="bg-green-600 hover:bg-green-700"
|
|
>
|
|
<ShoppingBag className="h-4 w-4 mr-2" />
|
|
Marcar como Vendido
|
|
</Button>
|
|
)}
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => onOpenChange(false)}
|
|
disabled={loading || markingSold}
|
|
>
|
|
Fechar
|
|
</Button>
|
|
{canAcceptOrReject && (
|
|
<>
|
|
<Button
|
|
variant="destructive"
|
|
onClick={handleReject}
|
|
disabled={loading || markingSold}
|
|
>
|
|
{loading ? (
|
|
<>
|
|
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
|
Rejeitando...
|
|
</>
|
|
) : (
|
|
<>
|
|
<XCircle className="h-4 w-4 mr-2" />
|
|
Rejeitar
|
|
</>
|
|
)}
|
|
</Button>
|
|
<Button
|
|
onClick={handleAccept}
|
|
disabled={loading || markingSold}
|
|
>
|
|
{loading ? (
|
|
<>
|
|
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
|
Aceitando...
|
|
</>
|
|
) : (
|
|
<>
|
|
<CheckCircle2 className="h-4 w-4 mr-2" />
|
|
Aceitar
|
|
</>
|
|
)}
|
|
</Button>
|
|
</>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</DialogContent>
|
|
|
|
{/* Dialog de confirmação para marcar como vendido */}
|
|
<Dialog open={showMarkSoldDialog} onOpenChange={setShowMarkSoldDialog}>
|
|
<DialogContent>
|
|
<DialogHeader>
|
|
<DialogTitle>Marcar anúncio como vendido?</DialogTitle>
|
|
<DialogDescription>
|
|
Ao marcar este anúncio como vendido, as seguintes ações serão
|
|
executadas:
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
<div className="space-y-2 pt-2">
|
|
<ul className="list-disc list-inside space-y-1 text-sm text-muted-foreground">
|
|
<li>O anúncio será marcado como "Vendido"</li>
|
|
<li>O anúncio continuará visível na lista por mais 1 hora</li>
|
|
<li>
|
|
Após 1 hora, o anúncio sairá automaticamente da lista de
|
|
anúncios ativos
|
|
</li>
|
|
<li>Nenhuma interação (comprar, dar lance) será permitida</li>
|
|
</ul>
|
|
<p className="pt-2 font-medium text-foreground">
|
|
Tem certeza que deseja marcar este anúncio como vendido?
|
|
</p>
|
|
</div>
|
|
<div className="flex gap-2 justify-end pt-4">
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => setShowMarkSoldDialog(false)}
|
|
disabled={markingSold}
|
|
>
|
|
Cancelar
|
|
</Button>
|
|
<Button
|
|
onClick={handleMarkAsSold}
|
|
disabled={markingSold}
|
|
className="bg-green-600 hover:bg-green-700"
|
|
>
|
|
{markingSold ? "Marcando..." : "Sim, marcar como vendido"}
|
|
</Button>
|
|
</div>
|
|
</DialogContent>
|
|
</Dialog>
|
|
</Dialog>
|
|
);
|
|
}
|