Integração com o banco de dados
This commit is contained in:
@@ -2,7 +2,7 @@ import { useState, useEffect } from "react";
|
||||
import { ChatHeader } from "@/components/ChatHeader";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Download, Trash2, Sparkles, Clock, Search } from "lucide-react";
|
||||
import { Download, Trash2, Sparkles, Clock, Search, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
@@ -14,41 +14,61 @@ import {
|
||||
} from "@/components/ui/select";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { imageGenerationService, IMAGE_SIZE_OPTIONS, ImageSize } from "@/services/imageGeneration";
|
||||
|
||||
interface GeneratedImage {
|
||||
id: string;
|
||||
url: string;
|
||||
prompt: string;
|
||||
size: ImageSize;
|
||||
timestamp: Date;
|
||||
}
|
||||
import {
|
||||
imageGenerationService,
|
||||
IMAGE_SIZE_OPTIONS,
|
||||
ImageSize,
|
||||
ImageRecord
|
||||
} from "@/services/imageGeneration";
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationItem,
|
||||
PaginationLink,
|
||||
} from "@/components/ui/pagination";
|
||||
|
||||
export const ImageView = () => {
|
||||
const [prompt, setPrompt] = useState("");
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
const [selectedSize, setSelectedSize] = useState<ImageSize>("1024x1024");
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [images, setImages] = useState<GeneratedImage[]>([]);
|
||||
const [images, setImages] = useState<ImageRecord[]>([]);
|
||||
const [lastGeneratedImage, setLastGeneratedImage] = useState<ImageRecord | null>(null);
|
||||
const [isLoadingImages, setIsLoadingImages] = useState(false);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(10);
|
||||
const { toast } = useToast();
|
||||
|
||||
// Carrega histórico do localStorage ao montar o componente
|
||||
useEffect(() => {
|
||||
const savedImages = localStorage.getItem('imageHistory');
|
||||
if (savedImages) {
|
||||
try {
|
||||
const parsedImages = JSON.parse(savedImages);
|
||||
// Converte strings de data de volta para Date objects
|
||||
const imagesWithDates = parsedImages.map((img: any) => ({
|
||||
...img,
|
||||
timestamp: new Date(img.timestamp),
|
||||
}));
|
||||
setImages(imagesWithDates);
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar histórico de imagens:', error);
|
||||
// Carrega imagens do banco de dados ao montar o componente
|
||||
const loadImages = async (page: number = currentPage, limit: number = perPage) => {
|
||||
setIsLoadingImages(true);
|
||||
try {
|
||||
const fetchedImages = await imageGenerationService.getImages(undefined, page, limit);
|
||||
|
||||
// Garante que sempre seja um array
|
||||
if (Array.isArray(fetchedImages)) {
|
||||
setImages(fetchedImages);
|
||||
} else {
|
||||
console.warn('Resposta da API não é um array:', fetchedImages);
|
||||
setImages([]);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao carregar imagens:', error);
|
||||
toast({
|
||||
title: "Erro ao carregar histórico",
|
||||
description: error.message || "Não foi possível carregar o histórico de imagens.",
|
||||
variant: "destructive",
|
||||
});
|
||||
setImages([]);
|
||||
} finally {
|
||||
setIsLoadingImages(false);
|
||||
}
|
||||
}, []);
|
||||
};
|
||||
|
||||
// Carrega imagens ao montar e quando a paginação mudar
|
||||
useEffect(() => {
|
||||
loadImages();
|
||||
}, [currentPage, perPage]);
|
||||
|
||||
const handleGenerate = async () => {
|
||||
// Valida a descrição antes de enviar
|
||||
@@ -73,28 +93,36 @@ export const ImageView = () => {
|
||||
|
||||
// Verifica se a geração foi bem-sucedida
|
||||
if (response.success) {
|
||||
// Log da URL da imagem para debug
|
||||
console.log('URL da imagem gerada:', response.image_url);
|
||||
|
||||
const newImage: GeneratedImage = {
|
||||
id: response.image_generation_id,
|
||||
url: response.image_url,
|
||||
prompt: response.message,
|
||||
size: selectedSize,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
const newHistory = [newImage, ...images].slice(0, 20); // Mantém apenas as últimas 20 imagens
|
||||
setImages(newHistory);
|
||||
localStorage.setItem('imageHistory', JSON.stringify(newHistory));
|
||||
|
||||
toast({
|
||||
title: "Imagem gerada com sucesso",
|
||||
description: `Tamanho: ${IMAGE_SIZE_OPTIONS[selectedSize].label}`,
|
||||
});
|
||||
|
||||
// Cria objeto da imagem recém-gerada para exibição imediata
|
||||
const newGeneratedImage: ImageRecord = {
|
||||
id: response.image_generation_id,
|
||||
user_email: '', // Será preenchido pelo backend
|
||||
estabelecimento_id: 0, // Será preenchido pelo backend
|
||||
description: response.message, // Descrição original
|
||||
model: 'dall-e-3', // Modelo padrão
|
||||
image_url: response.image_url,
|
||||
size: selectedSize,
|
||||
cost_usd: '0',
|
||||
total_tokens: 0,
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
// Salva a última imagem gerada para exibição
|
||||
setLastGeneratedImage(newGeneratedImage);
|
||||
|
||||
// Limpa o campo de descrição após sucesso
|
||||
setPrompt("");
|
||||
|
||||
// Recarrega a lista de imagens (sem aguardar para não bloquear a UI)
|
||||
loadImages(1, perPage);
|
||||
setCurrentPage(1);
|
||||
} else {
|
||||
throw new Error('Erro ao gerar imagem');
|
||||
}
|
||||
@@ -111,22 +139,41 @@ export const ImageView = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = (id: string) => {
|
||||
const newHistory = images.filter((img) => img.id !== id);
|
||||
setImages(newHistory);
|
||||
localStorage.setItem('imageHistory', JSON.stringify(newHistory));
|
||||
const handleDelete = async (id: string) => {
|
||||
try {
|
||||
const result = await imageGenerationService.deleteImage(id);
|
||||
|
||||
toast({
|
||||
title: "Imagem removida",
|
||||
description: "A imagem foi removida do histórico.",
|
||||
});
|
||||
if (result.success) {
|
||||
toast({
|
||||
title: "Imagem removida",
|
||||
description: "A imagem foi removida com sucesso.",
|
||||
});
|
||||
|
||||
// Se a imagem deletada for a última gerada, limpa o preview
|
||||
if (lastGeneratedImage && lastGeneratedImage.id === id) {
|
||||
setLastGeneratedImage(null);
|
||||
}
|
||||
|
||||
// Recarrega a lista de imagens
|
||||
await loadImages();
|
||||
} else {
|
||||
throw new Error(result.message || 'Erro ao deletar imagem');
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao deletar imagem:', error);
|
||||
toast({
|
||||
title: "Erro ao remover",
|
||||
description: error.message || "Não foi possível remover a imagem.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownload = async (image: GeneratedImage) => {
|
||||
const handleDownload = async (image: ImageRecord) => {
|
||||
try {
|
||||
await imageGenerationService.downloadImage(
|
||||
image.url,
|
||||
`${image.prompt.substring(0, 30)}_${image.size}.png`
|
||||
image.image_url,
|
||||
`${image.description.substring(0, 30)}_${image.size}.png`
|
||||
);
|
||||
|
||||
toast({
|
||||
@@ -142,9 +189,20 @@ export const ImageView = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const filteredImages = images.filter((img) =>
|
||||
img.prompt.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
);
|
||||
const handlePageChange = (page: number) => {
|
||||
setCurrentPage(page);
|
||||
};
|
||||
|
||||
const handlePerPageChange = (value: string) => {
|
||||
setPerPage(parseInt(value));
|
||||
setCurrentPage(1); // Reset para primeira página ao mudar itens por página
|
||||
};
|
||||
|
||||
const filteredImages = Array.isArray(images)
|
||||
? images.filter((img) =>
|
||||
img.description.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full pb-16 md:pb-0">
|
||||
@@ -227,11 +285,11 @@ export const ImageView = () => {
|
||||
)}
|
||||
|
||||
{/* Recent Images Preview */}
|
||||
{!isGenerating && images.length > 0 && (
|
||||
{!isGenerating && lastGeneratedImage && (
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-4">Última Geração</h3>
|
||||
<ImageCard
|
||||
image={images[0]}
|
||||
image={lastGeneratedImage}
|
||||
onDelete={handleDelete}
|
||||
onDownload={handleDownload}
|
||||
/>
|
||||
@@ -241,36 +299,102 @@ export const ImageView = () => {
|
||||
|
||||
{/* History Tab */}
|
||||
<TabsContent value="history" className="space-y-4">
|
||||
{/* Search */}
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder="Buscar por descrição..."
|
||||
className="pl-9"
|
||||
/>
|
||||
{/* Search and Filters */}
|
||||
<div className="flex flex-col md:flex-row gap-3">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder="Buscar por descrição..."
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Select value={perPage.toString()} onValueChange={handlePerPageChange}>
|
||||
<SelectTrigger className="w-full md:w-[180px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="glass-effect bg-popover border-border z-50">
|
||||
<SelectItem value="5">5 por página</SelectItem>
|
||||
<SelectItem value="10">10 por página</SelectItem>
|
||||
<SelectItem value="20">20 por página</SelectItem>
|
||||
<SelectItem value="50">50 por página</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Images Grid */}
|
||||
{filteredImages.length > 0 ? (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{filteredImages.map((image) => (
|
||||
<ImageCard
|
||||
key={image.id}
|
||||
image={image}
|
||||
onDelete={handleDelete}
|
||||
onDownload={handleDownload}
|
||||
/>
|
||||
))}
|
||||
{/* Loading State */}
|
||||
{isLoadingImages ? (
|
||||
<div className="glass-effect rounded-xl p-12 flex flex-col items-center justify-center space-y-4">
|
||||
<div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
|
||||
<p className="text-muted-foreground">Carregando imagens...</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="glass-effect rounded-xl p-12 text-center">
|
||||
<Clock className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
{searchQuery ? "Nenhuma imagem encontrada" : "Nenhuma imagem gerada ainda"}
|
||||
</p>
|
||||
</div>
|
||||
<>
|
||||
{/* Images Grid */}
|
||||
{filteredImages.length > 0 ? (
|
||||
<>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{filteredImages.map((image) => (
|
||||
<ImageCard
|
||||
key={image.id}
|
||||
image={image}
|
||||
onDelete={handleDelete}
|
||||
onDownload={handleDownload}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{!searchQuery && images.length >= perPage && (
|
||||
<div className="flex items-center justify-center gap-4 mt-6">
|
||||
<Pagination>
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handlePageChange(currentPage - 1)}
|
||||
disabled={currentPage === 1}
|
||||
className="gap-1"
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
<span className="hidden md:inline">Anterior</span>
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
|
||||
<PaginationItem>
|
||||
<span className="text-sm text-muted-foreground px-4">
|
||||
Página {currentPage}
|
||||
</span>
|
||||
</PaginationItem>
|
||||
|
||||
<PaginationItem>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handlePageChange(currentPage + 1)}
|
||||
disabled={images.length < perPage}
|
||||
className="gap-1"
|
||||
>
|
||||
<span className="hidden md:inline">Próxima</span>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="glass-effect rounded-xl p-12 text-center">
|
||||
<Clock className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
|
||||
<p className="text-muted-foreground">
|
||||
{searchQuery ? "Nenhuma imagem encontrada" : "Nenhuma imagem gerada ainda"}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
@@ -282,9 +406,9 @@ export const ImageView = () => {
|
||||
};
|
||||
|
||||
interface ImageCardProps {
|
||||
image: GeneratedImage;
|
||||
image: ImageRecord;
|
||||
onDelete: (id: string) => void;
|
||||
onDownload: (image: GeneratedImage) => void;
|
||||
onDownload: (image: ImageRecord) => void;
|
||||
}
|
||||
|
||||
const ImageCard = ({ image, onDelete, onDownload }: ImageCardProps) => {
|
||||
@@ -292,9 +416,10 @@ const ImageCard = ({ image, onDelete, onDownload }: ImageCardProps) => {
|
||||
const [imageLoading, setImageLoading] = useState(true);
|
||||
|
||||
// Calcula tempo relativo
|
||||
const getRelativeTime = (timestamp: Date) => {
|
||||
const getRelativeTime = (timestamp: string) => {
|
||||
const now = new Date();
|
||||
const diff = now.getTime() - new Date(timestamp).getTime();
|
||||
const date = new Date(timestamp);
|
||||
const diff = now.getTime() - date.getTime();
|
||||
const minutes = Math.floor(diff / 60000);
|
||||
const hours = Math.floor(diff / 3600000);
|
||||
const days = Math.floor(diff / 86400000);
|
||||
@@ -306,13 +431,13 @@ const ImageCard = ({ image, onDelete, onDownload }: ImageCardProps) => {
|
||||
};
|
||||
|
||||
const handleImageError = () => {
|
||||
console.warn('Erro CORS ao carregar imagem:', image.url);
|
||||
console.warn('Erro CORS ao carregar imagem:', image.image_url);
|
||||
setImageError(true);
|
||||
setImageLoading(false);
|
||||
};
|
||||
|
||||
const handleImageLoad = () => {
|
||||
console.log('Imagem carregada com sucesso:', image.url);
|
||||
console.log('Imagem carregada com sucesso:', image.image_url);
|
||||
setImageLoading(false);
|
||||
setImageError(false);
|
||||
};
|
||||
@@ -332,7 +457,7 @@ const ImageCard = ({ image, onDelete, onDownload }: ImageCardProps) => {
|
||||
<p className="text-xs text-center mb-2">A imagem foi gerada, mas não pode ser exibida aqui</p>
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
<a
|
||||
href={image.url}
|
||||
href={image.image_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-xs text-center bg-primary text-primary-foreground px-3 py-2 rounded-md hover:bg-primary/90 transition-colors"
|
||||
@@ -340,7 +465,7 @@ const ImageCard = ({ image, onDelete, onDownload }: ImageCardProps) => {
|
||||
Abrir imagem em nova aba
|
||||
</a>
|
||||
<button
|
||||
onClick={() => navigator.clipboard.writeText(image.url)}
|
||||
onClick={() => navigator.clipboard.writeText(image.image_url)}
|
||||
className="text-xs text-center bg-secondary text-secondary-foreground px-3 py-1 rounded-md hover:bg-secondary/80 transition-colors"
|
||||
>
|
||||
Copiar URL
|
||||
@@ -349,8 +474,8 @@ const ImageCard = ({ image, onDelete, onDownload }: ImageCardProps) => {
|
||||
</div>
|
||||
) : (
|
||||
<img
|
||||
src={image.url}
|
||||
alt={image.prompt}
|
||||
src={image.image_url}
|
||||
alt={image.description}
|
||||
className="w-full h-full object-cover"
|
||||
onError={handleImageError}
|
||||
onLoad={handleImageLoad}
|
||||
@@ -360,10 +485,10 @@ const ImageCard = ({ image, onDelete, onDownload }: ImageCardProps) => {
|
||||
)}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/0 to-black/0 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<div className="absolute bottom-0 left-0 right-0 p-4 space-y-2">
|
||||
<p className="text-sm text-white line-clamp-2">{image.prompt}</p>
|
||||
<p className="text-sm text-white line-clamp-2">{image.description}</p>
|
||||
<div className="flex items-center justify-between text-xs text-white/70">
|
||||
<span>{IMAGE_SIZE_OPTIONS[image.size].label}</span>
|
||||
<span>{getRelativeTime(image.timestamp)}</span>
|
||||
<span>{IMAGE_SIZE_OPTIONS[image.size as ImageSize]?.label || image.size}</span>
|
||||
<span>{getRelativeTime(image.created_at)}</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
|
||||
Reference in New Issue
Block a user