Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 189a2a8f2c | |||
| 50aca767d7 | |||
| 76cbd80eef | |||
| ee7204982c | |||
| a28b780718 | |||
| 0fa382ef0e | |||
| c2aa536660 | |||
| c4b281abd5 | |||
| 45ea53b364 | |||
| 9f75feb69a | |||
| a85465e332 | |||
| 8a9096470f |
Generated
+17
-1
@@ -2911,6 +2911,7 @@
|
||||
"integrity": "sha512-bJFoMATwIGaxxx8VJPeM8TonI8t579oRvgAuT8zFugJsJZgzqv0Fu8Mhp68iecjzG7cnN3mO2dJQ5uUM2EFrgQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
@@ -2928,6 +2929,7 @@
|
||||
"integrity": "sha512-/LDXMQh55EzZQ0uVAZmKKhfENivEvWz6E+EYzh+/MCjMhNsotd+ZHhBGIjFDTi6+fz0OhQQQLbTgdQIxxCsC0w==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/prop-types": "*",
|
||||
"csstype": "^3.0.2"
|
||||
@@ -2939,6 +2941,7 @@
|
||||
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"peerDependencies": {
|
||||
"@types/react": "^18.0.0"
|
||||
}
|
||||
@@ -2989,6 +2992,7 @@
|
||||
"integrity": "sha512-Zhy8HCvBUEfBECzIl1PKqF4p11+d0aUJS1GeUiuqK9WmOug8YCmC4h4bjyBvMyAMI9sbRczmrYL5lKg/YMbrcQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@typescript-eslint/scope-manager": "8.38.0",
|
||||
"@typescript-eslint/types": "8.38.0",
|
||||
@@ -3221,6 +3225,7 @@
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -3442,6 +3447,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"caniuse-lite": "^1.0.30001726",
|
||||
"electron-to-chromium": "^1.5.173",
|
||||
@@ -3800,6 +3806,7 @@
|
||||
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-3.6.0.tgz",
|
||||
"integrity": "sha512-fRHTG8g/Gif+kSh50gaGEdToemgfj74aRX3swtiouboip5JDLAyDE9F11nHMIcvOaXeOC6D7SpNhi7uFyB7Uww==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/kossnocorp"
|
||||
@@ -3904,7 +3911,8 @@
|
||||
"version": "8.6.0",
|
||||
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
|
||||
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/embla-carousel-react": {
|
||||
"version": "8.6.0",
|
||||
@@ -4047,6 +4055,7 @@
|
||||
"integrity": "sha512-LSehfdpgMeWcTZkWZVIJl+tkZ2nuSkyyB9C27MZqFWXuph7DvaowgcTvKqxvpLW1JZIk8PN7hFY3Rj9LQ7m7lg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@eslint-community/eslint-utils": "^4.2.0",
|
||||
"@eslint-community/regexpp": "^4.12.1",
|
||||
@@ -5742,6 +5751,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.11",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -5934,6 +5944,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
|
||||
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0"
|
||||
},
|
||||
@@ -5960,6 +5971,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
|
||||
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"loose-envify": "^1.1.0",
|
||||
"scheduler": "^0.23.2"
|
||||
@@ -5973,6 +5985,7 @@
|
||||
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.61.1.tgz",
|
||||
"integrity": "sha512-2vbXUFDYgqEgM2RcXcAT2PwDW/80QARi+PKmHy5q2KhuKvOlG8iIYgf7eIlIANR5trW9fJbP4r5aub3a4egsew==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
@@ -6526,6 +6539,7 @@
|
||||
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
|
||||
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@alloc/quick-lru": "^5.2.0",
|
||||
"arg": "^5.0.2",
|
||||
@@ -6650,6 +6664,7 @@
|
||||
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -6829,6 +6844,7 @@
|
||||
"integrity": "sha512-qO3aKv3HoQC8QKiNSTuUM1l9o/XX3+c+VTgLHbJWHZGeTPVAg2XwazI9UWzoxjIJCGCV2zU60uqMzjeLZuULqA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.21.3",
|
||||
"postcss": "^8.4.43",
|
||||
|
||||
+6
-2
@@ -9,6 +9,7 @@ import NotFound from "./pages/NotFound";
|
||||
import Redirect from "./pages/Redirect";
|
||||
import { GlobalFunctions } from "./GlobalFunctions";
|
||||
import React from "react";
|
||||
import IntelligenceIAApp from "./modules/intelligence-ia/App";
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
@@ -25,8 +26,11 @@ const App = () => (
|
||||
element={<Redirect />}
|
||||
/>
|
||||
|
||||
<Route path="/*" element={GlobalFunctions.isUsuarioLogado() ? <Index /> : <HGTXLogin />} />
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
{/* Módulo Intelligence IA como subpath*/}
|
||||
<Route path="/intelligence-ia/*" element={<IntelligenceIAApp />} />
|
||||
|
||||
<Route path="/*" element={<Index />} />
|
||||
|
||||
<Route path="*" element={<NotFound />} />
|
||||
<Route path="/404" element={<NotFound />} />
|
||||
</Routes>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ChevronDown, UserCog } from "lucide-react";
|
||||
import { ChevronDown, UserCog, Loader2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -15,7 +15,11 @@ import {
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { fetchModelsFromDatabase, ModelConfig } from "@/config/models";
|
||||
|
||||
// Texto padrão da personalidade (mesmo valor usado em ChatView)
|
||||
const DEFAULT_SYSTEM_PROMPT = "Você é um assistente útil e prestativo.";
|
||||
|
||||
interface ChatHeaderProps {
|
||||
showModelSelector?: boolean;
|
||||
@@ -29,25 +33,30 @@ export const ChatHeader = ({
|
||||
showModelSelector = false,
|
||||
selectedModel = "GPT-4o",
|
||||
onModelChange,
|
||||
systemPrompt = "Você é um assistente útil e prestativo.",
|
||||
systemPrompt = DEFAULT_SYSTEM_PROMPT,
|
||||
onSystemPromptChange
|
||||
}: ChatHeaderProps) => {
|
||||
const [isPersonalityOpen, setIsPersonalityOpen] = useState(false);
|
||||
const [tempSystemPrompt, setTempSystemPrompt] = useState(systemPrompt);
|
||||
const [models, setModels] = useState<ModelConfig[]>([]);
|
||||
const [isLoadingModels, setIsLoadingModels] = useState(true);
|
||||
|
||||
const models = [
|
||||
"GPT-4.1",
|
||||
"GPT-4o",
|
||||
"GPT-5 Mini",
|
||||
"Gemini 2.0 Flash",
|
||||
"Claude Sonnet 4.5",
|
||||
"DeepSeek V3.2 Chat",
|
||||
"DeepSeek V3.2 Reasoner",
|
||||
"Gemini 2.5 Flash",
|
||||
"Gemini 2.5 Flash-Lite",
|
||||
"Claude Haiku 4.5",
|
||||
"GPT-4o Mini",
|
||||
];
|
||||
// Carrega modelos da API ao montar o componente
|
||||
useEffect(() => {
|
||||
const loadModels = async () => {
|
||||
setIsLoadingModels(true);
|
||||
try {
|
||||
const modelsFromAPI = await fetchModelsFromDatabase();
|
||||
setModels(modelsFromAPI);
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar modelos:', error);
|
||||
} finally {
|
||||
setIsLoadingModels(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadModels();
|
||||
}, []);
|
||||
|
||||
const handleSavePersonality = () => {
|
||||
if (onSystemPromptChange) {
|
||||
@@ -67,19 +76,37 @@ export const ChatHeader = ({
|
||||
{showModelSelector && onModelChange && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" className="gap-1 md:gap-2 glass-effect text-xs md:text-sm">
|
||||
<span className="font-medium truncate max-w-[80px] md:max-w-none">{selectedModel}</span>
|
||||
<ChevronDown className="w-3 h-3 md:w-4 md:h-4" />
|
||||
<Button
|
||||
variant="outline"
|
||||
className="gap-1 md:gap-2 glass-effect text-xs md:text-sm"
|
||||
disabled={isLoadingModels}
|
||||
>
|
||||
{isLoadingModels ? (
|
||||
<>
|
||||
<Loader2 className="w-3 h-3 md:w-4 md:h-4 animate-spin" />
|
||||
<span className="font-medium">Carregando...</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="font-medium truncate max-w-[80px] md:max-w-none">{selectedModel}</span>
|
||||
<ChevronDown className="w-3 h-3 md:w-4 md:h-4" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" className="glass-effect bg-popover border-border z-50">
|
||||
{models.map((model) => (
|
||||
<DropdownMenuItem
|
||||
key={model}
|
||||
key={model.id}
|
||||
className="cursor-pointer"
|
||||
onClick={() => onModelChange(model)}
|
||||
onClick={() => onModelChange(model.name)}
|
||||
>
|
||||
{model}
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{model.name}</span>
|
||||
{model.description && (
|
||||
<span className="text-xs text-muted-foreground">{model.description}</span>
|
||||
)}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
|
||||
@@ -21,7 +21,7 @@ export const Layout = ({ children, activeTab, onTabChange }: LayoutProps) => {
|
||||
{ id: "images" as TabType, label: "Imagens", icon: Image },
|
||||
{ id: "transcription" as TabType, label: "Transcrição de Áudio", icon: AudioLines },
|
||||
{ id: "generation" as TabType, label: "Geração de Áudio", icon: Mic },
|
||||
{ id: "bots" as TabType, label: "Bots", icon: Bot },
|
||||
//{ id: "bots" as TabType, label: "Bots", icon: Bot },
|
||||
{ id: "agent" as TabType, label: "Agente de Parecer", icon: Brain },
|
||||
];
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { Search, FileText } from "lucide-react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -12,77 +12,70 @@ import {
|
||||
PaginationNext,
|
||||
PaginationPrevious,
|
||||
} from "@/components/ui/pagination";
|
||||
import { LegalOpinion } from "./AgentView";
|
||||
import { agentService, OpinionRecord } from "@/services/agent";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
|
||||
interface AgentSearchProps {
|
||||
onSelectOpinion: (opinion: LegalOpinion) => void;
|
||||
onSelectOpinion: (opinion: OpinionRecord) => void;
|
||||
}
|
||||
|
||||
// Simulação de base de pareceres
|
||||
const mockOpinionsDatabase: LegalOpinion[] = [
|
||||
{
|
||||
id: "base-1",
|
||||
title: "Análise Contratual - Prestação de Serviços Continuados",
|
||||
content: "Parecer completo sobre prestação de serviços...",
|
||||
createdAt: new Date("2024-01-15"),
|
||||
category: "Direito Civil",
|
||||
},
|
||||
{
|
||||
id: "base-2",
|
||||
title: "Rescisão de Contrato de Trabalho - Justa Causa",
|
||||
content: "Análise jurídica sobre rescisão contratual...",
|
||||
createdAt: new Date("2024-02-20"),
|
||||
category: "Direito Trabalhista",
|
||||
},
|
||||
{
|
||||
id: "base-3",
|
||||
title: "Responsabilidade Civil - Acidente de Trânsito",
|
||||
content: "Parecer sobre responsabilidade civil em acidentes...",
|
||||
createdAt: new Date("2024-03-10"),
|
||||
category: "Direito Civil",
|
||||
},
|
||||
{
|
||||
id: "base-4",
|
||||
title: "Dissolução de Sociedade - Procedimentos e Requisitos",
|
||||
content: "Análise completa sobre dissolução societária...",
|
||||
createdAt: new Date("2024-01-25"),
|
||||
category: "Direito Empresarial",
|
||||
},
|
||||
{
|
||||
id: "base-5",
|
||||
title: "Direitos do Consumidor - Vícios em Produtos",
|
||||
content: "Parecer sobre direitos do consumidor e garantias...",
|
||||
createdAt: new Date("2024-02-05"),
|
||||
category: "Direito do Consumidor",
|
||||
},
|
||||
];
|
||||
|
||||
export const AgentSearch = ({ onSelectOpinion }: AgentSearchProps) => {
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [searchResults, setSearchResults] = useState<LegalOpinion[]>([]);
|
||||
const [searchResults, setSearchResults] = useState<OpinionRecord[]>([]);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [itemsPerPage, setItemsPerPage] = useState(5);
|
||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
const handleSearch = () => {
|
||||
// Busca pareceres da API
|
||||
const handleSearch = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const data = await agentService.getOpinions({
|
||||
page: currentPage,
|
||||
per_page: itemsPerPage,
|
||||
search: searchTerm,
|
||||
});
|
||||
setSearchResults(data);
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao buscar pareceres:', error);
|
||||
toast({
|
||||
title: "Erro ao buscar pareceres",
|
||||
description: error.message || "Não foi possível buscar os pareceres.",
|
||||
variant: "destructive",
|
||||
});
|
||||
setSearchResults([]);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Busca automaticamente quando a página ou itemsPerPage mudam
|
||||
useEffect(() => {
|
||||
if (searchTerm.trim()) {
|
||||
handleSearch();
|
||||
}
|
||||
}, [currentPage, itemsPerPage]);
|
||||
|
||||
// Debounce para busca automática
|
||||
useEffect(() => {
|
||||
if (!searchTerm.trim()) {
|
||||
setSearchResults([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const results = mockOpinionsDatabase.filter(
|
||||
(opinion) =>
|
||||
opinion.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
opinion.content.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
opinion.category?.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
);
|
||||
const timer = setTimeout(() => {
|
||||
if (currentPage === 1) {
|
||||
handleSearch();
|
||||
} else {
|
||||
setCurrentPage(1); // Volta para primeira página ao buscar
|
||||
}
|
||||
}, 500);
|
||||
|
||||
setSearchResults(results);
|
||||
setCurrentPage(1);
|
||||
};
|
||||
return () => clearTimeout(timer);
|
||||
}, [searchTerm]);
|
||||
|
||||
const totalPages = Math.ceil(searchResults.length / itemsPerPage);
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
const paginatedResults = searchResults.slice(startIndex, startIndex + itemsPerPage);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full bg-background">
|
||||
@@ -92,24 +85,30 @@ export const AgentSearch = ({ onSelectOpinion }: AgentSearchProps) => {
|
||||
<Input
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
placeholder="Digite título, frase ou categoria..."
|
||||
placeholder="Digite título ou categoria..."
|
||||
onKeyDown={(e) => e.key === "Enter" && handleSearch()}
|
||||
/>
|
||||
<Button onClick={handleSearch} className="gap-2">
|
||||
<Button onClick={handleSearch} className="gap-2" disabled={isLoading}>
|
||||
<Search className="w-4 h-4" />
|
||||
Buscar
|
||||
{isLoading ? 'Buscando...' : 'Buscar'}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Base com {mockOpinionsDatabase.length} pareceres disponíveis
|
||||
</p>
|
||||
{searchResults.length > 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{searchResults.length} {searchResults.length === 1 ? 'parecer encontrado' : 'pareceres encontrados'}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 flex flex-col">
|
||||
<ScrollArea className="flex-1 p-6">
|
||||
{searchResults.length > 0 ? (
|
||||
{isLoading ? (
|
||||
<div className="text-center text-muted-foreground py-12">
|
||||
<p>Buscando pareceres...</p>
|
||||
</div>
|
||||
) : searchResults.length > 0 ? (
|
||||
<div className="space-y-3">
|
||||
{paginatedResults.map((opinion) => (
|
||||
{searchResults.map((opinion) => (
|
||||
<div
|
||||
key={opinion.id}
|
||||
className="p-4 border border-border rounded-lg hover:bg-accent/50 cursor-pointer transition-colors"
|
||||
@@ -118,13 +117,13 @@ export const AgentSearch = ({ onSelectOpinion }: AgentSearchProps) => {
|
||||
<div className="flex items-start gap-3">
|
||||
<FileText className="w-5 h-5 text-primary mt-1" />
|
||||
<div className="flex-1">
|
||||
<h3 className="font-semibold text-foreground">{opinion.title}</h3>
|
||||
<h3 className="font-semibold text-foreground">{opinion.titulo}</h3>
|
||||
<div className="flex gap-4 mt-2 text-sm text-muted-foreground">
|
||||
<span>{opinion.category}</span>
|
||||
<span>{new Date(opinion.createdAt).toLocaleDateString('pt-BR')}</span>
|
||||
<span>{opinion.categoria || '-'}</span>
|
||||
<span>{new Date(opinion.created_at).toLocaleDateString('pt-BR')}</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-2 line-clamp-2">
|
||||
{opinion.content}
|
||||
{opinion.instrucoes}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useState } from "react";
|
||||
import { Plus, Search, Eye, Trash2, ArrowUpDown } from "lucide-react";
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Plus, Search, Eye, Trash2, ArrowUpDown, Download, Loader2, CheckCircle2, XCircle } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -17,30 +18,113 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { OpinionDialog } from "./OpinionDialog";
|
||||
import { AgentSearch } from "./AgentSearch";
|
||||
import { agentService, OpinionRecord } from "@/services/agent";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
|
||||
export interface LegalOpinion {
|
||||
id: string;
|
||||
title: string;
|
||||
content: string;
|
||||
createdAt: Date;
|
||||
category?: string;
|
||||
}
|
||||
|
||||
type SortField = "title" | "createdAt" | "category";
|
||||
type SortField = "titulo" | "created_at" | "categoria";
|
||||
type SortOrder = "asc" | "desc";
|
||||
|
||||
export const AgentView = () => {
|
||||
const [opinions, setOpinions] = useState<LegalOpinion[]>([]);
|
||||
const [opinions, setOpinions] = useState<OpinionRecord[]>([]);
|
||||
const [pendingOpinions, setPendingOpinions] = useState<OpinionRecord[]>([]); // Registros temporários sendo processados
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [itemsPerPage, setItemsPerPage] = useState(10);
|
||||
const [sortField, setSortField] = useState<SortField>("createdAt");
|
||||
const [sortField, setSortField] = useState<SortField>("created_at");
|
||||
const [sortOrder, setSortOrder] = useState<SortOrder>("desc");
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const [selectedOpinion, setSelectedOpinion] = useState<LegalOpinion | null>(null);
|
||||
const [selectedOpinion, setSelectedOpinion] = useState<OpinionRecord | null>(null);
|
||||
const [showSearch, setShowSearch] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [opinionToDelete, setOpinionToDelete] = useState<OpinionRecord | null>(null);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
// Carrega pareceres da API
|
||||
const loadOpinions = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const data = await agentService.getOpinions({
|
||||
page: currentPage,
|
||||
per_page: itemsPerPage,
|
||||
search: searchTerm,
|
||||
});
|
||||
|
||||
// Adiciona status aos pareceres da API
|
||||
const opinionsWithStatus = data.map(opinion => ({
|
||||
...opinion,
|
||||
status: (opinion.file_url || opinion.file_url_melhoria) ? 'concluido' : 'processando' as const,
|
||||
}));
|
||||
|
||||
setOpinions(opinionsWithStatus);
|
||||
|
||||
// Remove registros temporários que agora estão na API
|
||||
setPendingOpinions(prev =>
|
||||
prev.filter(pending =>
|
||||
!opinionsWithStatus.some(opinion =>
|
||||
opinion.titulo === pending.titulo &&
|
||||
opinion.created_at.substring(0, 10) === pending.created_at.substring(0, 10)
|
||||
)
|
||||
)
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao carregar pareceres:', error);
|
||||
toast({
|
||||
title: "Erro ao carregar pareceres",
|
||||
description: error.message || "Não foi possível carregar a lista de pareceres.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [currentPage, itemsPerPage, searchTerm, toast]);
|
||||
|
||||
// Polling automático para atualizar status dos pareceres
|
||||
useEffect(() => {
|
||||
// Carrega imediatamente
|
||||
loadOpinions();
|
||||
|
||||
// Configura polling a cada 10 segundos se houver pareceres pendentes
|
||||
const interval = setInterval(() => {
|
||||
if (pendingOpinions.length > 0) {
|
||||
console.log('Polling: Atualizando lista de pareceres...');
|
||||
loadOpinions();
|
||||
}
|
||||
}, 10000); // 10 segundos
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [currentPage, itemsPerPage, pendingOpinions.length, loadOpinions]);
|
||||
|
||||
// Debounce para busca
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
if (currentPage === 1) {
|
||||
loadOpinions();
|
||||
} else {
|
||||
setCurrentPage(1); // Volta para a primeira página ao buscar
|
||||
}
|
||||
}, 500);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [searchTerm, loadOpinions]);
|
||||
|
||||
const handleSort = (field: SortField) => {
|
||||
if (sortField === field) {
|
||||
@@ -51,17 +135,14 @@ export const AgentView = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const filteredOpinions = opinions.filter(
|
||||
(op) =>
|
||||
op.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
op.category?.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
);
|
||||
// Mescla pareceres da API com registros temporários
|
||||
const allOpinions = [...pendingOpinions, ...opinions];
|
||||
|
||||
const sortedOpinions = [...filteredOpinions].sort((a, b) => {
|
||||
const sortedOpinions = [...allOpinions].sort((a, b) => {
|
||||
const multiplier = sortOrder === "asc" ? 1 : -1;
|
||||
|
||||
if (sortField === "createdAt") {
|
||||
return multiplier * (new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
||||
if (sortField === "created_at") {
|
||||
return multiplier * (new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
|
||||
}
|
||||
|
||||
const aValue = a[sortField] || "";
|
||||
@@ -70,20 +151,18 @@ export const AgentView = () => {
|
||||
});
|
||||
|
||||
const totalPages = Math.ceil(sortedOpinions.length / itemsPerPage);
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
const paginatedOpinions = sortedOpinions.slice(startIndex, startIndex + itemsPerPage);
|
||||
|
||||
const handleOpinionCreated = (newOpinion: LegalOpinion) => {
|
||||
setOpinions([newOpinion, ...opinions]);
|
||||
setIsDialogOpen(false);
|
||||
setSelectedOpinion(null);
|
||||
// Callback quando um parecer está sendo criado (registro temporário)
|
||||
const handleOpinionCreating = (tempOpinion: OpinionRecord) => {
|
||||
setPendingOpinions(prev => [tempOpinion, ...prev]);
|
||||
};
|
||||
|
||||
const handleDeleteOpinion = (id: string) => {
|
||||
setOpinions(opinions.filter(op => op.id !== id));
|
||||
// Callback quando um parecer foi criado (recarrega da API)
|
||||
const handleOpinionCreated = () => {
|
||||
loadOpinions();
|
||||
};
|
||||
|
||||
const handleViewOpinion = (opinion: LegalOpinion) => {
|
||||
const handleViewOpinion = (opinion: OpinionRecord) => {
|
||||
setSelectedOpinion(opinion);
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
@@ -93,12 +172,69 @@ export const AgentView = () => {
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleSelectFromSearch = (opinion: LegalOpinion) => {
|
||||
const handleSelectFromSearch = (opinion: OpinionRecord) => {
|
||||
setSelectedOpinion(opinion);
|
||||
setShowSearch(false);
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDownloadVersion = async (opinion: OpinionRecord, version: 'v1' | 'v2') => {
|
||||
const fileUrl = version === 'v1' ? opinion.file_url : opinion.file_url_melhoria;
|
||||
|
||||
if (!fileUrl) {
|
||||
toast({
|
||||
title: "Arquivo não disponível",
|
||||
description: `A ${version === 'v1' ? 'versão 1' : 'versão melhorada'} ainda não está disponível.`,
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const fileName = `${opinion.titulo}_${version === 'v1' ? 'v1' : 'melhorada'}.docx`;
|
||||
await agentService.downloadOpinion(fileUrl, fileName);
|
||||
|
||||
toast({
|
||||
title: "Download iniciado",
|
||||
description: "O parecer está sendo baixado.",
|
||||
});
|
||||
} catch (error: any) {
|
||||
toast({
|
||||
title: "Erro ao fazer download",
|
||||
description: error.message || "Não foi possível baixar o arquivo.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteOpinion = async () => {
|
||||
if (!opinionToDelete) return;
|
||||
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
await agentService.deleteOpinion(opinionToDelete.id);
|
||||
|
||||
toast({
|
||||
title: "Parecer excluído",
|
||||
description: "O parecer foi excluído com sucesso.",
|
||||
});
|
||||
|
||||
// Recarrega a lista de pareceres
|
||||
await loadOpinions();
|
||||
|
||||
// Fecha o diálogo de confirmação
|
||||
setOpinionToDelete(null);
|
||||
} catch (error: any) {
|
||||
toast({
|
||||
title: "Erro ao excluir parecer",
|
||||
description: error.message || "Não foi possível excluir o parecer.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (showSearch) {
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
@@ -116,7 +252,7 @@ export const AgentView = () => {
|
||||
<div className="flex flex-col h-full bg-background pb-16 md:pb-0">
|
||||
<div className="p-3 md:p-6 border-b border-border">
|
||||
<div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-3 mb-4">
|
||||
<h1 className="text-xl md:text-3xl font-bold text-foreground">Agente de Parecer Jurídico</h1>
|
||||
<h1 className="text-xl md:text-3xl font-bold text-foreground">Gerador de Modelos de Parecer Jurídico</h1>
|
||||
<div className="flex gap-2 w-full md:w-auto">
|
||||
<Button onClick={() => setShowSearch(true)} variant="outline" className="gap-1 md:gap-2 flex-1 md:flex-none text-xs md:text-sm">
|
||||
<Search className="w-3 h-3 md:w-4 md:h-4" />
|
||||
@@ -169,7 +305,7 @@ export const AgentView = () => {
|
||||
<TableHead className="min-w-[200px]">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => handleSort("title")}
|
||||
onClick={() => handleSort("titulo")}
|
||||
className="flex items-center gap-1 font-semibold text-xs md:text-sm p-1 md:p-2"
|
||||
>
|
||||
Título
|
||||
@@ -179,17 +315,20 @@ export const AgentView = () => {
|
||||
<TableHead className="hidden md:table-cell">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => handleSort("category")}
|
||||
onClick={() => handleSort("categoria")}
|
||||
className="flex items-center gap-1 font-semibold text-sm"
|
||||
>
|
||||
Categoria
|
||||
<ArrowUpDown className="w-4 h-4" />
|
||||
</Button>
|
||||
</TableHead>
|
||||
<TableHead className="hidden lg:table-cell text-center">
|
||||
<span className="font-semibold text-xs md:text-sm">Status</span>
|
||||
</TableHead>
|
||||
<TableHead className="hidden sm:table-cell">
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={() => handleSort("createdAt")}
|
||||
onClick={() => handleSort("created_at")}
|
||||
className="flex items-center gap-1 font-semibold text-xs md:text-sm p-1 md:p-2"
|
||||
>
|
||||
Data
|
||||
@@ -200,21 +339,47 @@ export const AgentView = () => {
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{paginatedOpinions.length === 0 ? (
|
||||
{isLoading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="text-center py-12 text-muted-foreground">
|
||||
<TableCell colSpan={5} className="text-center py-12 text-muted-foreground">
|
||||
Carregando pareceres...
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : sortedOpinions.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center py-12 text-muted-foreground">
|
||||
{searchTerm
|
||||
? "Nenhum parecer encontrado"
|
||||
: "Nenhum parecer criado ainda. Clique em 'Novo Parecer' para começar."}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
paginatedOpinions.map((opinion) => (
|
||||
sortedOpinions.map((opinion) => (
|
||||
<TableRow key={opinion.id}>
|
||||
<TableCell className="font-medium text-xs md:text-sm">{opinion.title}</TableCell>
|
||||
<TableCell className="hidden md:table-cell text-sm">{opinion.category || "-"}</TableCell>
|
||||
<TableCell className="font-medium text-xs md:text-sm">{opinion.titulo}</TableCell>
|
||||
<TableCell className="hidden md:table-cell text-sm">{opinion.categoria || "-"}</TableCell>
|
||||
<TableCell className="hidden lg:table-cell text-center">
|
||||
{opinion.status === 'processando' && (
|
||||
<Badge variant="secondary" className="gap-1 bg-yellow-100 text-yellow-800 hover:bg-yellow-100">
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
Gerando...
|
||||
</Badge>
|
||||
)}
|
||||
{opinion.status === 'concluido' && (
|
||||
<Badge variant="secondary" className="gap-1 bg-green-100 text-green-800 hover:bg-green-100">
|
||||
<CheckCircle2 className="w-3 h-3" />
|
||||
Concluído
|
||||
</Badge>
|
||||
)}
|
||||
{opinion.status === 'erro' && (
|
||||
<Badge variant="destructive" className="gap-1">
|
||||
<XCircle className="w-3 h-3" />
|
||||
Erro
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="hidden sm:table-cell text-xs md:text-sm">
|
||||
{new Date(opinion.createdAt).toLocaleDateString("pt-BR")}
|
||||
{new Date(opinion.created_at).toLocaleDateString("pt-BR")}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
@@ -224,15 +389,46 @@ export const AgentView = () => {
|
||||
onClick={() => handleViewOpinion(opinion)}
|
||||
title="Visualizar"
|
||||
className="h-7 w-7 md:h-9 md:w-9"
|
||||
disabled={opinion.isLocalPending || opinion.status === 'processando'}
|
||||
>
|
||||
<Eye className="w-3 h-3 md:w-4 md:h-4" />
|
||||
</Button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
title="Baixar"
|
||||
className="h-7 w-7 md:h-9 md:w-9"
|
||||
disabled={opinion.isLocalPending || opinion.status === 'processando'}
|
||||
>
|
||||
<Download className="w-3 h-3 md:w-4 md:h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleDownloadVersion(opinion, 'v1')}
|
||||
disabled={!opinion.file_url}
|
||||
>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
Versão 1
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleDownloadVersion(opinion, 'v2')}
|
||||
disabled={!opinion.file_url_melhoria}
|
||||
>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
Versão Melhorada
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleDeleteOpinion(opinion.id)}
|
||||
className="text-destructive hover:text-destructive h-7 w-7 md:h-9 md:w-9"
|
||||
onClick={() => setOpinionToDelete(opinion)}
|
||||
title="Excluir"
|
||||
className="h-7 w-7 md:h-9 md:w-9 text-destructive hover:text-destructive"
|
||||
disabled={opinion.isLocalPending}
|
||||
>
|
||||
<Trash2 className="w-3 h-3 md:w-4 md:h-4" />
|
||||
</Button>
|
||||
@@ -245,10 +441,10 @@ export const AgentView = () => {
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{totalPages > 1 && (
|
||||
{sortedOpinions.length > 0 && (
|
||||
<div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-2 mt-4">
|
||||
<p className="text-xs md:text-sm text-muted-foreground text-center sm:text-left">
|
||||
{startIndex + 1}-{Math.min(startIndex + itemsPerPage, sortedOpinions.length)} de {sortedOpinions.length}
|
||||
Mostrando {sortedOpinions.length} {sortedOpinions.length === 1 ? 'parecer' : 'pareceres'}
|
||||
</p>
|
||||
<div className="flex gap-1 md:gap-2 justify-center">
|
||||
<Button
|
||||
@@ -306,7 +502,29 @@ export const AgentView = () => {
|
||||
onOpenChange={setIsDialogOpen}
|
||||
selectedOpinion={selectedOpinion}
|
||||
onOpinionCreated={handleOpinionCreated}
|
||||
onOpinionCreating={handleOpinionCreating}
|
||||
/>
|
||||
|
||||
<AlertDialog open={!!opinionToDelete} onOpenChange={(open) => !open && setOpinionToDelete(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Confirmar exclusão</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Tem certeza que deseja excluir o parecer "{opinionToDelete?.titulo}"? Esta ação não pode ser desfeita.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={isDeleting}>Cancelar</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDeleteOpinion}
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting ? "Excluindo..." : "Excluir"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import axios from "axios";
|
||||
import { Download, Sparkles } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -14,13 +13,15 @@ import { Textarea } from "@/components/ui/textarea";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { LegalOpinion } from "./AgentView";
|
||||
import { ToastAction } from "@/components/ui/toast";
|
||||
import { agentService, OpinionRecord } from "@/services/agent";
|
||||
|
||||
interface OpinionDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
selectedOpinion: LegalOpinion | null;
|
||||
onOpinionCreated: (opinion: LegalOpinion) => void;
|
||||
selectedOpinion: OpinionRecord | null;
|
||||
onOpinionCreated: () => void;
|
||||
onOpinionCreating?: (tempOpinion: OpinionRecord) => void; // Callback para adicionar registro temporário
|
||||
}
|
||||
|
||||
export const OpinionDialog = ({
|
||||
@@ -28,27 +29,28 @@ export const OpinionDialog = ({
|
||||
onOpenChange,
|
||||
selectedOpinion,
|
||||
onOpinionCreated,
|
||||
onOpinionCreating,
|
||||
}: OpinionDialogProps) => {
|
||||
const [title, setTitle] = useState("");
|
||||
const [category, setCategory] = useState("");
|
||||
const [instructions, setInstructions] = useState("");
|
||||
const [generatedContent, setGeneratedContent] = useState("");
|
||||
const [isGenerating, setIsGenerating] = useState(false);
|
||||
const [createdOpinion, setCreatedOpinion] = useState<OpinionRecord | null>(null);
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedOpinion) {
|
||||
setTitle(selectedOpinion.title);
|
||||
setCategory(selectedOpinion.category || "");
|
||||
setGeneratedContent(selectedOpinion.content);
|
||||
setInstructions("");
|
||||
setTitle(selectedOpinion.titulo);
|
||||
setCategory(selectedOpinion.categoria || "");
|
||||
setInstructions(selectedOpinion.instrucoes || "");
|
||||
setCreatedOpinion(selectedOpinion);
|
||||
} else {
|
||||
setTitle("");
|
||||
setCategory("");
|
||||
setInstructions("");
|
||||
setGeneratedContent("");
|
||||
setCreatedOpinion(null);
|
||||
}
|
||||
}, [selectedOpinion]);
|
||||
}, [selectedOpinion, open]);
|
||||
|
||||
const handleGenerate = async () => {
|
||||
if (!instructions.trim()) {
|
||||
@@ -69,80 +71,129 @@ export const OpinionDialog = ({
|
||||
return;
|
||||
}
|
||||
|
||||
setIsGenerating(true);
|
||||
// Criar registro temporário para adicionar na tabela imediatamente
|
||||
const tempId = `temp-${Date.now()}`;
|
||||
const tempOpinion: OpinionRecord = {
|
||||
id: tempId,
|
||||
estabelecimento_id: 0,
|
||||
user_email: '',
|
||||
titulo: title,
|
||||
categoria: category,
|
||||
instrucoes: instructions,
|
||||
file_url: '',
|
||||
file_url_melhoria: '',
|
||||
created_at: new Date().toISOString(),
|
||||
status: 'processando',
|
||||
isLocalPending: true,
|
||||
};
|
||||
|
||||
// Adiciona o registro temporário na tabela
|
||||
if (onOpinionCreating) {
|
||||
onOpinionCreating(tempOpinion);
|
||||
}
|
||||
|
||||
// Criar toast de progresso que não fecha automaticamente
|
||||
const loadingToast = toast({
|
||||
title: "Gerando parecer jurídico...",
|
||||
description: "O parecer está sendo processado. Isso pode levar alguns minutos.",
|
||||
duration: Infinity, // Toast não fecha automaticamente
|
||||
});
|
||||
|
||||
// Fecha o dialog imediatamente
|
||||
setIsGenerating(false);
|
||||
onOpenChange(false);
|
||||
|
||||
// Limpa os campos
|
||||
setTitle("");
|
||||
setCategory("");
|
||||
setInstructions("");
|
||||
setCreatedOpinion(null);
|
||||
|
||||
// Executar requisição em background
|
||||
try {
|
||||
const response = await axios.post(
|
||||
"https://prod-hgtx-intelligence-n8n.hgtx.com.br/webhook/codex/gepam/parecer-tecnico",
|
||||
{
|
||||
titulo: title,
|
||||
categoria: category,
|
||||
instrucoes: instructions,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const content = response.data.parecer || response.data.content || JSON.stringify(response.data, null, 2);
|
||||
|
||||
setGeneratedContent(content);
|
||||
setIsGenerating(false);
|
||||
|
||||
const newOpinion: LegalOpinion = {
|
||||
id: selectedOpinion?.id || Date.now().toString(),
|
||||
title: title,
|
||||
content: content,
|
||||
createdAt: new Date(),
|
||||
category: category || undefined,
|
||||
};
|
||||
|
||||
onOpinionCreated(newOpinion);
|
||||
|
||||
toast({
|
||||
title: "Parecer gerado com sucesso!",
|
||||
description: "O parecer está pronto para download.",
|
||||
const response = await agentService.createOpinion({
|
||||
titulo: tempOpinion.titulo,
|
||||
categoria: tempOpinion.categoria,
|
||||
instrucoes: tempOpinion.instrucoes,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Erro ao gerar parecer:", error);
|
||||
setIsGenerating(false);
|
||||
|
||||
let errorMessage = "Não foi possível gerar o parecer. Tente novamente.";
|
||||
if (response.success) {
|
||||
// Recarrega a lista para pegar o parecer real da API
|
||||
onOpinionCreated();
|
||||
|
||||
if (axios.isAxiosError(error)) {
|
||||
if (error.response) {
|
||||
errorMessage = error.response.data?.message || `Erro do servidor: ${error.response.status}`;
|
||||
} else if (error.request) {
|
||||
errorMessage = "Sem resposta do servidor. Verifique sua conexão.";
|
||||
}
|
||||
// Atualizar toast para sucesso
|
||||
loadingToast.update({
|
||||
id: loadingToast.id,
|
||||
title: "Parecer gerado com sucesso!",
|
||||
description: "O parecer foi criado e está disponível para download.",
|
||||
duration: 8000, // Toast fecha após 8 segundos
|
||||
action: (
|
||||
<ToastAction altText="Fechar notificação" onClick={() => loadingToast.dismiss()}>
|
||||
OK
|
||||
</ToastAction>
|
||||
),
|
||||
});
|
||||
} else {
|
||||
throw new Error('Falha ao criar parecer');
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error("Erro ao gerar parecer:", error);
|
||||
|
||||
toast({
|
||||
const errorMessage = error.message || "Não foi possível gerar o parecer. Tente novamente.";
|
||||
|
||||
// Recarrega a lista para remover o registro temporário e tentar pegar dados reais
|
||||
onOpinionCreated();
|
||||
|
||||
// Atualizar toast para erro
|
||||
loadingToast.update({
|
||||
id: loadingToast.id,
|
||||
title: "Erro ao gerar parecer",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
duration: 10000, // Toast de erro fecha após 10 segundos
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownloadDocx = () => {
|
||||
const content = generatedContent;
|
||||
const blob = new Blob([content], { type: "text/plain" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${title || "parecer"}.txt`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
const handleDownloadVersion = async (version: 'v1' | 'v2') => {
|
||||
if (!createdOpinion && !selectedOpinion) {
|
||||
toast({
|
||||
title: "Nenhum parecer disponível",
|
||||
description: "Por favor, gere um parecer primeiro.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Download iniciado",
|
||||
description: "O parecer está sendo baixado.",
|
||||
});
|
||||
const opinion = createdOpinion || selectedOpinion;
|
||||
if (!opinion) return;
|
||||
|
||||
const fileUrl = version === 'v1' ? opinion.file_url : opinion.file_url_melhoria;
|
||||
|
||||
if (!fileUrl) {
|
||||
toast({
|
||||
title: "Arquivo não disponível",
|
||||
description: `A ${version === 'v1' ? 'versão 1' : 'versão melhorada'} ainda não está disponível.`,
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const fileName = `${opinion.titulo}_${version === 'v1' ? 'v1' : 'melhorada'}.docx`;
|
||||
await agentService.downloadOpinion(fileUrl, fileName);
|
||||
|
||||
toast({
|
||||
title: "Download iniciado",
|
||||
description: "O parecer está sendo baixado.",
|
||||
});
|
||||
} catch (error: any) {
|
||||
toast({
|
||||
title: "Erro ao fazer download",
|
||||
description: error.message || "Não foi possível baixar o arquivo.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -150,11 +201,11 @@ export const OpinionDialog = ({
|
||||
<DialogContent className="max-w-[95vw] md:max-w-4xl max-h-[90vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{selectedOpinion ? "Gerar Novo Modelo do Parecer" : "Novo Parecer Jurídico"}
|
||||
{selectedOpinion ? "Visualizar Parecer" : "Novo Parecer Jurídico"}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{selectedOpinion
|
||||
? "Forneça instruções para gerar um novo modelo baseado neste parecer"
|
||||
? "Visualize os detalhes do parecer e faça o download das versões disponíveis"
|
||||
: "Preencha os dados e instruções para gerar um novo parecer com IA"}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
@@ -196,40 +247,46 @@ export const OpinionDialog = ({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleGenerate}
|
||||
disabled={isGenerating}
|
||||
className="w-full gap-2"
|
||||
>
|
||||
{isGenerating ? (
|
||||
<>Gerando parecer...</>
|
||||
) : (
|
||||
<>
|
||||
<Sparkles className="w-4 h-4" />
|
||||
Gerar Parecer com IA
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{!selectedOpinion && (
|
||||
<Button
|
||||
onClick={handleGenerate}
|
||||
disabled={isGenerating}
|
||||
className="w-full gap-2"
|
||||
>
|
||||
{isGenerating ? (
|
||||
<>Gerando parecer...</>
|
||||
) : (
|
||||
<>
|
||||
<Sparkles className="w-4 h-4" />
|
||||
Gerar Parecer com IA
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{generatedContent && (
|
||||
<div className="space-y-2 pt-4 border-t">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>Parecer Gerado</Label>
|
||||
{selectedOpinion && (
|
||||
<div className="space-y-3 pt-4 border-t">
|
||||
<Label>Downloads Disponíveis</Label>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Button
|
||||
onClick={handleDownloadDocx}
|
||||
onClick={() => handleDownloadVersion('v1')}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-2"
|
||||
className="w-full gap-2 justify-start"
|
||||
disabled={!selectedOpinion.file_url}
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
Baixar DOCX
|
||||
Baixar Versão 1
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleDownloadVersion('v2')}
|
||||
variant="outline"
|
||||
className="w-full gap-2 justify-start"
|
||||
disabled={!selectedOpinion.file_url_melhoria}
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
Baixar Versão Melhorada
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-[300px] rounded-md border p-4">
|
||||
<pre className="whitespace-pre-wrap font-sans text-sm">
|
||||
{generatedContent}
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ChatHeader } from "@/components/ChatHeader";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Mic, Play, Download, Trash2, Search } from "lucide-react";
|
||||
import { Mic, Download, Trash2, Search, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import {
|
||||
@@ -13,33 +13,56 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationItem,
|
||||
} from "@/components/ui/pagination";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { audioGenerationService, VOICE_OPTIONS, VoiceType } from "@/services/audioGeneration";
|
||||
|
||||
interface GeneratedAudio {
|
||||
id: string;
|
||||
text: string;
|
||||
voice: string;
|
||||
voiceLabel: string;
|
||||
audioUrl: string;
|
||||
timestamp: Date;
|
||||
}
|
||||
import { audioGenerationService, VOICE_OPTIONS, VoiceType, AudioRecord } from "@/services/audioGeneration";
|
||||
|
||||
export const GenerationView = () => {
|
||||
const [textToSpeech, setTextToSpeech] = useState("");
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
const [selectedVoice, setSelectedVoice] = useState<VoiceType>("alloy");
|
||||
const [generatedAudio, setGeneratedAudio] = useState<GeneratedAudio | null>(null);
|
||||
const [audioHistory, setAudioHistory] = useState<GeneratedAudio[]>([]);
|
||||
const [lastGeneratedAudio, setLastGeneratedAudio] = useState<AudioRecord | null>(null);
|
||||
const [audioHistory, setAudioHistory] = useState<AudioRecord[]>([]);
|
||||
const [isLoadingAudios, setIsLoadingAudios] = useState(false);
|
||||
const [audioSearchQuery, setAudioSearchQuery] = useState("");
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(10);
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
const savedAudios = localStorage.getItem('audioHistory');
|
||||
if (savedAudios) {
|
||||
setAudioHistory(JSON.parse(savedAudios));
|
||||
// Carrega áudios do banco de dados
|
||||
const loadAudios = async (page: number = currentPage, limit: number = perPage) => {
|
||||
setIsLoadingAudios(true);
|
||||
try {
|
||||
const fetchedAudios = await audioGenerationService.getAudios(undefined, page, limit);
|
||||
|
||||
// Garante que sempre seja um array
|
||||
if (Array.isArray(fetchedAudios)) {
|
||||
setAudioHistory(fetchedAudios);
|
||||
} else {
|
||||
console.warn('Resposta da API não é um array:', fetchedAudios);
|
||||
setAudioHistory([]);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao carregar áudios:', error);
|
||||
toast({
|
||||
title: "Erro ao carregar histórico",
|
||||
description: error.message || "Não foi possível carregar o histórico de áudios.",
|
||||
variant: "destructive",
|
||||
});
|
||||
setAudioHistory([]);
|
||||
} finally {
|
||||
setIsLoadingAudios(false);
|
||||
}
|
||||
}, []);
|
||||
};
|
||||
|
||||
// Carrega áudios ao montar e quando a paginação mudar
|
||||
useEffect(() => {
|
||||
loadAudios();
|
||||
}, [currentPage, perPage]);
|
||||
|
||||
const handleGenerateAudio = async () => {
|
||||
// Valida o texto antes de enviar
|
||||
@@ -66,20 +89,23 @@ export const GenerationView = () => {
|
||||
if (response.success) {
|
||||
console.log('URL do áudio gerado:', response.audio_url);
|
||||
|
||||
const audio: GeneratedAudio = {
|
||||
// Cria objeto do áudio recém-gerado para exibição imediata
|
||||
const newGeneratedAudio: AudioRecord = {
|
||||
id: response.audio_generation_id,
|
||||
text: response.message,
|
||||
user_email: '',
|
||||
estabelecimento_id: 0,
|
||||
input_text: response.message,
|
||||
model: 'tts-1',
|
||||
voice: selectedVoice,
|
||||
voiceLabel: VOICE_OPTIONS[selectedVoice].label,
|
||||
audioUrl: response.audio_url,
|
||||
timestamp: new Date(),
|
||||
audio_url: response.audio_url,
|
||||
duration_seconds: null,
|
||||
file_size: 0,
|
||||
cost_usd: '0',
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
setGeneratedAudio(audio);
|
||||
|
||||
const newHistory = [audio, ...audioHistory].slice(0, 10);
|
||||
setAudioHistory(newHistory);
|
||||
localStorage.setItem('audioHistory', JSON.stringify(newHistory));
|
||||
// Salva o último áudio gerado para exibição
|
||||
setLastGeneratedAudio(newGeneratedAudio);
|
||||
|
||||
toast({
|
||||
title: "Áudio gerado com sucesso",
|
||||
@@ -88,6 +114,10 @@ export const GenerationView = () => {
|
||||
|
||||
// Limpa o campo de texto após sucesso
|
||||
setTextToSpeech("");
|
||||
|
||||
// Recarrega a lista de áudios (sem aguardar para não bloquear a UI)
|
||||
loadAudios(1, perPage);
|
||||
setCurrentPage(1);
|
||||
} else {
|
||||
throw new Error('Erro ao gerar áudio');
|
||||
}
|
||||
@@ -104,10 +134,10 @@ export const GenerationView = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownloadAudio = (audio: GeneratedAudio) => {
|
||||
const handleDownloadAudio = (audio: AudioRecord) => {
|
||||
const a = document.createElement('a');
|
||||
a.href = audio.audioUrl;
|
||||
a.download = `audio_${audio.voiceLabel}_${new Date(audio.timestamp).getTime()}.mp3`;
|
||||
a.href = audio.audio_url;
|
||||
a.download = `audio_${audio.voice}_${new Date(audio.created_at).getTime()}.mp3`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
@@ -118,24 +148,51 @@ export const GenerationView = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const handleDeleteAudio = (audioId: string) => {
|
||||
if (generatedAudio?.id === audioId) {
|
||||
setGeneratedAudio(null);
|
||||
}
|
||||
const newHistory = audioHistory.filter(a => a.id !== audioId);
|
||||
setAudioHistory(newHistory);
|
||||
localStorage.setItem('audioHistory', JSON.stringify(newHistory));
|
||||
const handleDeleteAudio = async (audioId: string) => {
|
||||
try {
|
||||
const result = await audioGenerationService.deleteAudio(audioId);
|
||||
|
||||
toast({
|
||||
title: "Áudio removido",
|
||||
description: "O áudio foi removido do histórico.",
|
||||
});
|
||||
if (result.success) {
|
||||
toast({
|
||||
title: "Áudio removido",
|
||||
description: "O áudio foi removido com sucesso.",
|
||||
});
|
||||
|
||||
// Se o áudio deletado for o último gerado, limpa o preview
|
||||
if (lastGeneratedAudio && lastGeneratedAudio.id === audioId) {
|
||||
setLastGeneratedAudio(null);
|
||||
}
|
||||
|
||||
// Recarrega a lista de áudios
|
||||
await loadAudios();
|
||||
} else {
|
||||
throw new Error(result.message || 'Erro ao deletar áudio');
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao deletar áudio:', error);
|
||||
toast({
|
||||
title: "Erro ao remover",
|
||||
description: error.message || "Não foi possível remover o áudio.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const filteredAudios = audioHistory.filter(item =>
|
||||
item.voiceLabel.toLowerCase().includes(audioSearchQuery.toLowerCase()) ||
|
||||
item.text.toLowerCase().includes(audioSearchQuery.toLowerCase())
|
||||
);
|
||||
const handlePageChange = (page: number) => {
|
||||
setCurrentPage(page);
|
||||
};
|
||||
|
||||
const handlePerPageChange = (value: string) => {
|
||||
setPerPage(parseInt(value));
|
||||
setCurrentPage(1);
|
||||
};
|
||||
|
||||
const filteredAudios = Array.isArray(audioHistory)
|
||||
? audioHistory.filter(item =>
|
||||
(VOICE_OPTIONS[item.voice]?.label || item.voice).toLowerCase().includes(audioSearchQuery.toLowerCase()) ||
|
||||
item.input_text.toLowerCase().includes(audioSearchQuery.toLowerCase())
|
||||
)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full pb-16 md:pb-0">
|
||||
@@ -222,13 +279,13 @@ export const GenerationView = () => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{generatedAudio && (
|
||||
{lastGeneratedAudio && (
|
||||
<div className="glass-effect rounded-xl p-6 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h4 className="font-semibold">Áudio Gerado</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Voz: {generatedAudio.voiceLabel}
|
||||
Voz: {VOICE_OPTIONS[lastGeneratedAudio.voice]?.label || lastGeneratedAudio.voice}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
@@ -236,7 +293,7 @@ export const GenerationView = () => {
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="gap-1"
|
||||
onClick={() => handleDownloadAudio(generatedAudio)}
|
||||
onClick={() => handleDownloadAudio(lastGeneratedAudio)}
|
||||
>
|
||||
<Download className="w-3 h-3" />
|
||||
Baixar
|
||||
@@ -245,7 +302,7 @@ export const GenerationView = () => {
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
className="gap-1"
|
||||
onClick={() => handleDeleteAudio(generatedAudio.id)}
|
||||
onClick={() => handleDeleteAudio(lastGeneratedAudio.id)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
Excluir
|
||||
@@ -254,14 +311,14 @@ export const GenerationView = () => {
|
||||
</div>
|
||||
|
||||
<div className="bg-muted/30 rounded-lg p-4">
|
||||
<p className="text-sm mb-3">{generatedAudio.text}</p>
|
||||
<p className="text-sm mb-3">{lastGeneratedAudio.input_text}</p>
|
||||
<audio
|
||||
key={generatedAudio.id}
|
||||
key={lastGeneratedAudio.id}
|
||||
controls
|
||||
className="w-full"
|
||||
preload="metadata"
|
||||
>
|
||||
<source src={generatedAudio.audioUrl} type="audio/mpeg" />
|
||||
<source src={lastGeneratedAudio.audio_url} type="audio/mpeg" />
|
||||
Seu navegador não suporta o elemento de áudio.
|
||||
</audio>
|
||||
</div>
|
||||
@@ -269,16 +326,10 @@ export const GenerationView = () => {
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="history" className="space-y-6">
|
||||
<div className="glass-effect rounded-xl p-6 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">Histórico de Áudios</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{audioHistory.length} {audioHistory.length === 1 ? 'item' : 'itens'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<TabsContent value="history" className="space-y-4">
|
||||
{/* 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={audioSearchQuery}
|
||||
@@ -287,59 +338,127 @@ export const GenerationView = () => {
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{filteredAudios.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<Mic className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
||||
<p>{audioSearchQuery ? 'Nenhum áudio encontrado' : 'Nenhum áudio no histórico'}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{filteredAudios.map((audio) => (
|
||||
<div key={audio.id} className="bg-muted/30 rounded-lg p-4 space-y-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="font-medium">Voz: {audio.voiceLabel}</h4>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{new Date(audio.timestamp).toLocaleDateString('pt-BR')} às{' '}
|
||||
{new Date(audio.timestamp).toLocaleTimeString('pt-BR')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleDownloadAudio(audio)}
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleDeleteAudio(audio.id)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground line-clamp-2">
|
||||
{audio.text}
|
||||
</p>
|
||||
<audio
|
||||
key={audio.id}
|
||||
controls
|
||||
className="w-full"
|
||||
preload="metadata"
|
||||
>
|
||||
<source src={audio.audioUrl} type="audio/mpeg" />
|
||||
</audio>
|
||||
</div>
|
||||
))}
|
||||
</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>
|
||||
|
||||
{/* Loading State */}
|
||||
{isLoadingAudios ? (
|
||||
<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 áudios...</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{filteredAudios.length === 0 ? (
|
||||
<div className="glass-effect rounded-xl p-12 text-center">
|
||||
<Mic className="w-12 h-12 mx-auto mb-4 text-muted-foreground opacity-50" />
|
||||
<p className="text-muted-foreground">
|
||||
{audioSearchQuery ? 'Nenhum áudio encontrado' : 'Nenhum áudio gerado ainda'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-3">
|
||||
{filteredAudios.map((audio) => (
|
||||
<div key={audio.id} className="glass-effect rounded-lg p-4 space-y-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="font-medium">
|
||||
Voz: {VOICE_OPTIONS[audio.voice]?.label || audio.voice}
|
||||
</h4>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{new Date(audio.created_at).toLocaleDateString('pt-BR')} às{' '}
|
||||
{new Date(audio.created_at).toLocaleTimeString('pt-BR')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleDownloadAudio(audio)}
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleDeleteAudio(audio.id)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground line-clamp-2">
|
||||
{audio.input_text}
|
||||
</p>
|
||||
<audio
|
||||
key={audio.id}
|
||||
controls
|
||||
className="w-full"
|
||||
preload="metadata"
|
||||
>
|
||||
<source src={audio.audio_url} type="audio/mpeg" />
|
||||
</audio>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{!audioSearchQuery && audioHistory.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={audioHistory.length < perPage}
|
||||
className="gap-1"
|
||||
>
|
||||
<span className="hidden md:inline">Próxima</span>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
@@ -2,37 +2,67 @@ import { useState, useEffect } from "react";
|
||||
import { ChatHeader } from "@/components/ChatHeader";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Upload, Download, Trash2, FileAudio, Copy, Search } from "lucide-react";
|
||||
import { Upload, Download, Trash2, FileAudio, Copy, Search, ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationItem,
|
||||
} from "@/components/ui/pagination";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { transcriptionService } from "@/services/transcription";
|
||||
import { transcriptionService, TranscriptionRecord } from "@/services/transcription";
|
||||
|
||||
const SUPPORTED_FORMATS = ['flac', 'm4a', 'mp3', 'mp4', 'mpeg', 'mpga', 'oga', 'ogg', 'wav', 'webm'];
|
||||
const MAX_FILE_SIZE = 25 * 1024 * 1024; // 25 MB
|
||||
|
||||
interface TranscriptionResult {
|
||||
id: string;
|
||||
fileName: string;
|
||||
text: string;
|
||||
timestamp: Date;
|
||||
audioUrl?: string;
|
||||
}
|
||||
|
||||
export const TranscriptionView = () => {
|
||||
const [isTranscribing, setIsTranscribing] = useState(false);
|
||||
const [transcriptionResult, setTranscriptionResult] = useState<TranscriptionResult | null>(null);
|
||||
const [lastTranscriptionResult, setLastTranscriptionResult] = useState<TranscriptionRecord | null>(null);
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [transcriptionHistory, setTranscriptionHistory] = useState<TranscriptionResult[]>([]);
|
||||
const [transcriptionHistory, setTranscriptionHistory] = useState<TranscriptionRecord[]>([]);
|
||||
const [isLoadingTranscriptions, setIsLoadingTranscriptions] = useState(false);
|
||||
const [transcriptionSearchQuery, setTranscriptionSearchQuery] = useState("");
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [perPage, setPerPage] = useState(10);
|
||||
const { toast } = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
const savedTranscriptions = localStorage.getItem('transcriptionHistory');
|
||||
if (savedTranscriptions) {
|
||||
setTranscriptionHistory(JSON.parse(savedTranscriptions));
|
||||
// Carrega transcrições do banco de dados
|
||||
const loadTranscriptions = async (page: number = currentPage, limit: number = perPage) => {
|
||||
setIsLoadingTranscriptions(true);
|
||||
try {
|
||||
const fetchedTranscriptions = await transcriptionService.getTranscriptions(undefined, page, limit);
|
||||
|
||||
// Garante que sempre seja um array
|
||||
if (Array.isArray(fetchedTranscriptions)) {
|
||||
setTranscriptionHistory(fetchedTranscriptions);
|
||||
} else {
|
||||
console.warn('Resposta da API não é um array:', fetchedTranscriptions);
|
||||
setTranscriptionHistory([]);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao carregar transcrições:', error);
|
||||
toast({
|
||||
title: "Erro ao carregar histórico",
|
||||
description: error.message || "Não foi possível carregar o histórico de transcrições.",
|
||||
variant: "destructive",
|
||||
});
|
||||
setTranscriptionHistory([]);
|
||||
} finally {
|
||||
setIsLoadingTranscriptions(false);
|
||||
}
|
||||
}, []);
|
||||
};
|
||||
|
||||
// Carrega transcrições ao montar e quando a paginação mudar
|
||||
useEffect(() => {
|
||||
loadTranscriptions();
|
||||
}, [currentPage, perPage]);
|
||||
|
||||
const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
@@ -64,24 +94,31 @@ export const TranscriptionView = () => {
|
||||
|
||||
// Verifica se a transcrição foi bem-sucedida
|
||||
if (response.success) {
|
||||
const result: TranscriptionResult = {
|
||||
// Cria objeto da transcrição recém-gerada para exibição imediata
|
||||
const newTranscription: TranscriptionRecord = {
|
||||
id: response.transcription_id,
|
||||
fileName: file.name,
|
||||
text: response.message,
|
||||
timestamp: new Date(),
|
||||
audioUrl: response.audio_url,
|
||||
user_email: '',
|
||||
estabelecimento_id: 0,
|
||||
audio_file_name: file.name,
|
||||
audio_duration_seconds: 0,
|
||||
transcription_text: response.message,
|
||||
model: 'whisper-1',
|
||||
audio_url: response.audio_url,
|
||||
cost_usd: '0',
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
setTranscriptionResult(result);
|
||||
|
||||
const newHistory = [result, ...transcriptionHistory].slice(0, 10);
|
||||
setTranscriptionHistory(newHistory);
|
||||
localStorage.setItem('transcriptionHistory', JSON.stringify(newHistory));
|
||||
// Salva a última transcrição para exibição
|
||||
setLastTranscriptionResult(newTranscription);
|
||||
|
||||
toast({
|
||||
title: "Transcrição concluída",
|
||||
description: "Seu áudio foi transcrito com sucesso!",
|
||||
});
|
||||
|
||||
// Recarrega a lista de transcrições (sem aguardar para não bloquear a UI)
|
||||
loadTranscriptions(1, perPage);
|
||||
setCurrentPage(1);
|
||||
} else {
|
||||
throw new Error(response.message || 'Erro ao transcrever áudio');
|
||||
}
|
||||
@@ -99,52 +136,80 @@ export const TranscriptionView = () => {
|
||||
};
|
||||
|
||||
const handleDeleteTranscription = () => {
|
||||
setTranscriptionResult(null);
|
||||
setLastTranscriptionResult(null);
|
||||
setSelectedFile(null);
|
||||
};
|
||||
|
||||
const handleDeleteTranscriptionFromHistory = (transcriptionId: string) => {
|
||||
if (transcriptionResult?.id === transcriptionId) {
|
||||
setTranscriptionResult(null);
|
||||
}
|
||||
const newHistory = transcriptionHistory.filter(t => t.id !== transcriptionId);
|
||||
setTranscriptionHistory(newHistory);
|
||||
localStorage.setItem('transcriptionHistory', JSON.stringify(newHistory));
|
||||
const handleDeleteTranscriptionFromHistory = async (transcriptionId: string) => {
|
||||
try {
|
||||
const result = await transcriptionService.deleteTranscription(transcriptionId);
|
||||
|
||||
toast({
|
||||
title: "Transcrição removida",
|
||||
description: "A transcrição foi removida do histórico.",
|
||||
});
|
||||
};
|
||||
if (result.success) {
|
||||
toast({
|
||||
title: "Transcrição removida",
|
||||
description: "A transcrição foi removida com sucesso.",
|
||||
});
|
||||
|
||||
const handleCopyTranscription = () => {
|
||||
if (transcriptionResult) {
|
||||
navigator.clipboard.writeText(transcriptionResult.text);
|
||||
// Se a transcrição deletada for a última gerada, limpa o preview
|
||||
if (lastTranscriptionResult && lastTranscriptionResult.id === transcriptionId) {
|
||||
setLastTranscriptionResult(null);
|
||||
}
|
||||
|
||||
// Recarrega a lista de transcrições
|
||||
await loadTranscriptions();
|
||||
} else {
|
||||
throw new Error(result.message || 'Erro ao deletar transcrição');
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao deletar transcrição:', error);
|
||||
toast({
|
||||
title: "Texto copiado",
|
||||
description: "A transcrição foi copiada para a área de transferência",
|
||||
title: "Erro ao remover",
|
||||
description: error.message || "Não foi possível remover a transcrição.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownloadTranscription = () => {
|
||||
if (transcriptionResult) {
|
||||
const blob = new Blob([transcriptionResult.text], { type: 'text/plain' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `transcricao_${transcriptionResult.fileName}.txt`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
const handleCopyTranscription = (text: string) => {
|
||||
navigator.clipboard.writeText(text);
|
||||
toast({
|
||||
title: "Texto copiado",
|
||||
description: "A transcrição foi copiada para a área de transferência",
|
||||
});
|
||||
};
|
||||
|
||||
const filteredTranscriptions = transcriptionHistory.filter(item =>
|
||||
item.fileName.toLowerCase().includes(transcriptionSearchQuery.toLowerCase()) ||
|
||||
item.text.toLowerCase().includes(transcriptionSearchQuery.toLowerCase())
|
||||
);
|
||||
const handleDownloadTranscription = (transcription: TranscriptionRecord) => {
|
||||
const blob = new Blob([transcription.transcription_text], { type: 'text/plain' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `transcricao_${transcription.audio_file_name}.txt`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
toast({
|
||||
title: "Download iniciado",
|
||||
description: "O arquivo de transcrição está sendo baixado.",
|
||||
});
|
||||
};
|
||||
|
||||
const handlePageChange = (page: number) => {
|
||||
setCurrentPage(page);
|
||||
};
|
||||
|
||||
const handlePerPageChange = (value: string) => {
|
||||
setPerPage(parseInt(value));
|
||||
setCurrentPage(1);
|
||||
};
|
||||
|
||||
const filteredTranscriptions = Array.isArray(transcriptionHistory)
|
||||
? transcriptionHistory.filter(item =>
|
||||
item.audio_file_name.toLowerCase().includes(transcriptionSearchQuery.toLowerCase()) ||
|
||||
item.transcription_text.toLowerCase().includes(transcriptionSearchQuery.toLowerCase())
|
||||
)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full pb-16 md:pb-0">
|
||||
@@ -222,13 +287,13 @@ export const TranscriptionView = () => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{transcriptionResult && (
|
||||
{lastTranscriptionResult && (
|
||||
<div className="glass-effect rounded-xl p-6 space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h4 className="font-semibold">{transcriptionResult.fileName}</h4>
|
||||
<h4 className="font-semibold">{lastTranscriptionResult.audio_file_name}</h4>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Transcrito {new Date(transcriptionResult.timestamp).toLocaleTimeString('pt-BR')}
|
||||
Transcrito {new Date(lastTranscriptionResult.created_at).toLocaleTimeString('pt-BR')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
@@ -236,7 +301,7 @@ export const TranscriptionView = () => {
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="gap-1"
|
||||
onClick={handleCopyTranscription}
|
||||
onClick={() => handleCopyTranscription(lastTranscriptionResult.transcription_text)}
|
||||
>
|
||||
<Copy className="w-3 h-3" />
|
||||
Copiar
|
||||
@@ -245,7 +310,7 @@ export const TranscriptionView = () => {
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="gap-1"
|
||||
onClick={handleDownloadTranscription}
|
||||
onClick={() => handleDownloadTranscription(lastTranscriptionResult)}
|
||||
>
|
||||
<Download className="w-3 h-3" />
|
||||
Baixar
|
||||
@@ -263,23 +328,17 @@ export const TranscriptionView = () => {
|
||||
</div>
|
||||
<div className="bg-muted/30 rounded-lg p-4">
|
||||
<p className="text-sm leading-relaxed whitespace-pre-wrap">
|
||||
{transcriptionResult.text}
|
||||
{lastTranscriptionResult.transcription_text}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="history" className="space-y-6">
|
||||
<div className="glass-effect rounded-xl p-6 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">Histórico de Transcrições</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{transcriptionHistory.length} {transcriptionHistory.length === 1 ? 'item' : 'itens'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<TabsContent value="history" className="space-y-4">
|
||||
{/* 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={transcriptionSearchQuery}
|
||||
@@ -288,40 +347,122 @@ export const TranscriptionView = () => {
|
||||
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>
|
||||
|
||||
{filteredTranscriptions.length === 0 ? (
|
||||
<div className="text-center py-12 text-muted-foreground">
|
||||
<FileAudio className="w-12 h-12 mx-auto mb-3 opacity-50" />
|
||||
<p>{transcriptionSearchQuery ? 'Nenhuma transcrição encontrada' : 'Nenhuma transcrição no histórico'}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{filteredTranscriptions.map((item) => (
|
||||
<div key={item.id} className="bg-muted/30 rounded-lg p-4 space-y-2">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h4 className="font-medium truncate">{item.fileName}</h4>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{new Date(item.timestamp).toLocaleDateString('pt-BR')} às{' '}
|
||||
{new Date(item.timestamp).toLocaleTimeString('pt-BR')}
|
||||
{/* Loading State */}
|
||||
{isLoadingTranscriptions ? (
|
||||
<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 transcrições...</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{filteredTranscriptions.length === 0 ? (
|
||||
<div className="glass-effect rounded-xl p-12 text-center">
|
||||
<FileAudio className="w-12 h-12 mx-auto mb-4 text-muted-foreground opacity-50" />
|
||||
<p className="text-muted-foreground">
|
||||
{transcriptionSearchQuery ? 'Nenhuma transcrição encontrada' : 'Nenhuma transcrição no histórico'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-3">
|
||||
{filteredTranscriptions.map((item) => (
|
||||
<div key={item.id} className="glass-effect rounded-lg p-4 space-y-2">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<h4 className="font-medium truncate">{item.audio_file_name}</h4>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{new Date(item.created_at).toLocaleDateString('pt-BR')} às{' '}
|
||||
{new Date(item.created_at).toLocaleTimeString('pt-BR')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleCopyTranscription(item.transcription_text)}
|
||||
>
|
||||
<Copy className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleDownloadTranscription(item)}
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleDeleteTranscriptionFromHistory(item.id)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground line-clamp-2">
|
||||
{item.transcription_text}
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleDeleteTranscriptionFromHistory(item.id)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground line-clamp-2">
|
||||
{item.text}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Pagination */}
|
||||
{!transcriptionSearchQuery && transcriptionHistory.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={transcriptionHistory.length < perPage}
|
||||
className="gap-1"
|
||||
>
|
||||
<span className="hidden md:inline">Próxima</span>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
+219
-261
@@ -4,7 +4,7 @@ import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { chatService, StoredChat, StoredFolder } from "@/services/chat";
|
||||
import { chatService, ChatRecord, FolderRecord } from "@/services/chat";
|
||||
import { formatDistanceToNow } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
import {
|
||||
@@ -38,7 +38,7 @@ interface ChatSidebarProps {
|
||||
isCollapsed: boolean;
|
||||
onToggleCollapse: () => void;
|
||||
onNewChat: () => void;
|
||||
onSelectChat?: (chat: StoredChat) => void;
|
||||
onSelectChat?: (chat: ChatRecord) => void;
|
||||
currentChatId?: string;
|
||||
}
|
||||
|
||||
@@ -46,20 +46,22 @@ export const ChatSidebar = ({ isCollapsed, onToggleCollapse, onNewChat, onSelect
|
||||
const { toast } = useToast();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [isCreateFolderOpen, setIsCreateFolderOpen] = useState(false);
|
||||
const [isEditFolderOpen, setIsEditFolderOpen] = useState(false);
|
||||
const [isDeleteFolderOpen, setIsDeleteFolderOpen] = useState(false);
|
||||
const [isDeleteChatOpen, setIsDeleteChatOpen] = useState(false);
|
||||
const [isRenameFolderOpen, setIsRenameFolderOpen] = useState(false);
|
||||
const [newFolderName, setNewFolderName] = useState("");
|
||||
const [editingFolder, setEditingFolder] = useState<StoredFolder | null>(null);
|
||||
const [deletingFolder, setDeletingFolder] = useState<StoredFolder | null>(null);
|
||||
const [deletingChat, setDeletingChat] = useState<StoredChat | null>(null);
|
||||
const [renamingFolder, setRenamingFolder] = useState<FolderRecord | null>(null);
|
||||
const [renamedFolderName, setRenamedFolderName] = useState("");
|
||||
const [deletingFolder, setDeletingFolder] = useState<FolderRecord | null>(null);
|
||||
const [deletingChat, setDeletingChat] = useState<ChatRecord | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
// Estado carregado do localStorage via chatService
|
||||
const [chats, setChats] = useState<StoredChat[]>([]);
|
||||
const [folders, setFolders] = useState<StoredFolder[]>([]);
|
||||
// Estado carregado do banco de dados via chatService
|
||||
const [chats, setChats] = useState<ChatRecord[]>([]);
|
||||
const [folders, setFolders] = useState<FolderRecord[]>([]);
|
||||
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
|
||||
|
||||
// Carrega chats e pastas do localStorage quando o componente monta
|
||||
// Carrega chats e pastas do banco de dados quando o componente monta
|
||||
useEffect(() => {
|
||||
loadChatsAndFolders();
|
||||
|
||||
@@ -76,28 +78,39 @@ export const ChatSidebar = ({ isCollapsed, onToggleCollapse, onNewChat, onSelect
|
||||
};
|
||||
}, []);
|
||||
|
||||
const loadChatsAndFolders = () => {
|
||||
const loadedChats = chatService.getAllChats();
|
||||
const loadedFolders = chatService.getAllFolders();
|
||||
const loadChatsAndFolders = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const data = await chatService.getChatsAndFolders();
|
||||
|
||||
setChats(loadedChats);
|
||||
setFolders(loadedFolders);
|
||||
console.log('Dados carregados:', data);
|
||||
|
||||
// Expande todas as pastas por padrão
|
||||
setExpandedFolders(new Set(loadedFolders.map(f => f.id)));
|
||||
setChats(data.chats);
|
||||
setFolders(data.folders);
|
||||
|
||||
// Expande todas as pastas por padrão
|
||||
setExpandedFolders(new Set(data.folders.map(f => f.id)));
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao carregar chats e pastas:', error);
|
||||
toast({
|
||||
title: "Erro ao carregar dados",
|
||||
description: error.message || "Não foi possível carregar chats e pastas.",
|
||||
variant: "destructive",
|
||||
});
|
||||
|
||||
// Define arrays vazios em caso de erro
|
||||
setChats([]);
|
||||
setFolders([]);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateFolder = () => {
|
||||
const handleCreateFolder = async () => {
|
||||
if (newFolderName.trim()) {
|
||||
try {
|
||||
const newFolder: StoredFolder = {
|
||||
id: chatService.generateChatId(), // Usa mesmo gerador de ID
|
||||
name: newFolderName,
|
||||
createdAt: new Date(),
|
||||
chatIds: [],
|
||||
};
|
||||
chatService.saveFolder(newFolder);
|
||||
loadChatsAndFolders();
|
||||
await chatService.createFolder(newFolderName);
|
||||
await loadChatsAndFolders();
|
||||
setNewFolderName("");
|
||||
setIsCreateFolderOpen(false);
|
||||
|
||||
@@ -105,86 +118,75 @@ export const ChatSidebar = ({ isCollapsed, onToggleCollapse, onNewChat, onSelect
|
||||
title: "Pasta criada",
|
||||
description: `Pasta "${newFolderName}" criada com sucesso.`,
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao criar pasta:', error);
|
||||
toast({
|
||||
title: "Erro ao criar pasta",
|
||||
description: "Não foi possível criar a pasta. Tente novamente.",
|
||||
description: error.message || "Não foi possível criar a pasta. Tente novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditFolder = () => {
|
||||
if (editingFolder && newFolderName.trim()) {
|
||||
try {
|
||||
const updatedFolder: StoredFolder = {
|
||||
...editingFolder,
|
||||
name: newFolderName,
|
||||
};
|
||||
chatService.saveFolder(updatedFolder);
|
||||
loadChatsAndFolders();
|
||||
setNewFolderName("");
|
||||
setEditingFolder(null);
|
||||
setIsEditFolderOpen(false);
|
||||
|
||||
toast({
|
||||
title: "Pasta renomeada",
|
||||
description: `Pasta renomeada para "${newFolderName}".`,
|
||||
});
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Erro ao renomear pasta",
|
||||
description: "Não foi possível renomear a pasta. Tente novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteFolder = () => {
|
||||
const handleDeleteFolder = async () => {
|
||||
if (deletingFolder) {
|
||||
try {
|
||||
// Remove chats da pasta (volta para "Sem Pasta")
|
||||
const updatedChats = chats.map(chat => {
|
||||
if (chat.folderId === deletingFolder.id) {
|
||||
const updated = { ...chat, folderId: undefined };
|
||||
chatService.saveChat(updated);
|
||||
return updated;
|
||||
}
|
||||
return chat;
|
||||
});
|
||||
|
||||
chatService.deleteFolder(deletingFolder.id);
|
||||
loadChatsAndFolders();
|
||||
await chatService.deleteFolder(deletingFolder.id);
|
||||
await loadChatsAndFolders();
|
||||
setDeletingFolder(null);
|
||||
setIsDeleteFolderOpen(false);
|
||||
|
||||
toast({
|
||||
title: "Pasta excluída",
|
||||
description: "As conversas foram movidas para 'Sem Pasta'.",
|
||||
description: "A pasta foi excluída com sucesso.",
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao excluir pasta:', error);
|
||||
toast({
|
||||
title: "Erro ao excluir pasta",
|
||||
description: "Não foi possível excluir a pasta. Tente novamente.",
|
||||
description: error.message || "Não foi possível excluir a pasta. Tente novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const openEditFolder = (folder: StoredFolder) => {
|
||||
setEditingFolder(folder);
|
||||
setNewFolderName(folder.name);
|
||||
setIsEditFolderOpen(true);
|
||||
};
|
||||
|
||||
const openDeleteFolder = (folder: StoredFolder) => {
|
||||
const openDeleteFolder = (folder: FolderRecord) => {
|
||||
setDeletingFolder(folder);
|
||||
setIsDeleteFolderOpen(true);
|
||||
};
|
||||
|
||||
const openRenameFolder = (folder: FolderRecord) => {
|
||||
setRenamingFolder(folder);
|
||||
setRenamedFolderName(folder.name);
|
||||
setIsRenameFolderOpen(true);
|
||||
};
|
||||
|
||||
const handleRenameFolder = async () => {
|
||||
if (renamingFolder && renamedFolderName.trim()) {
|
||||
try {
|
||||
await chatService.renameFolder(renamingFolder.id, renamedFolderName);
|
||||
await loadChatsAndFolders();
|
||||
setRenamingFolder(null);
|
||||
setRenamedFolderName("");
|
||||
setIsRenameFolderOpen(false);
|
||||
|
||||
toast({
|
||||
title: "Pasta renomeada",
|
||||
description: `Pasta renomeada para "${renamedFolderName}" com sucesso.`,
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao renomear pasta:', error);
|
||||
toast({
|
||||
title: "Erro ao renomear pasta",
|
||||
description: error.message || "Não foi possível renomear a pasta. Tente novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const toggleFolder = (folderId: string) => {
|
||||
const newExpanded = new Set(expandedFolders);
|
||||
if (newExpanded.has(folderId)) {
|
||||
@@ -195,62 +197,31 @@ export const ChatSidebar = ({ isCollapsed, onToggleCollapse, onNewChat, onSelect
|
||||
setExpandedFolders(newExpanded);
|
||||
};
|
||||
|
||||
const moveToFolder = (chatId: string, folderId: string) => {
|
||||
const moveToFolder = async (chatId: string, folderId: string) => {
|
||||
try {
|
||||
const chat = chats.find(c => c.id === chatId);
|
||||
if (chat) {
|
||||
const updatedChat: StoredChat = {
|
||||
...chat,
|
||||
folderId: folderId,
|
||||
};
|
||||
chatService.saveChat(updatedChat);
|
||||
loadChatsAndFolders();
|
||||
await chatService.moveChatToFolder(chatId, folderId);
|
||||
await loadChatsAndFolders();
|
||||
|
||||
const folder = folders.find(f => f.id === folderId);
|
||||
toast({
|
||||
title: "Chat movido",
|
||||
description: `Movido para a pasta "${folder?.name}".`,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
const folder = folders.find(f => f.id === folderId);
|
||||
toast({
|
||||
title: "Chat movido",
|
||||
description: `Movido para a pasta "${folder?.name}".`,
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao mover chat:', error);
|
||||
toast({
|
||||
title: "Erro ao mover chat",
|
||||
description: "Não foi possível mover o chat. Tente novamente.",
|
||||
description: error.message || "Não foi possível mover o chat. Tente novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const removeFromFolder = (chatId: string) => {
|
||||
try {
|
||||
const chat = chats.find(c => c.id === chatId);
|
||||
if (chat) {
|
||||
const updatedChat: StoredChat = {
|
||||
...chat,
|
||||
folderId: undefined,
|
||||
};
|
||||
chatService.saveChat(updatedChat);
|
||||
loadChatsAndFolders();
|
||||
|
||||
toast({
|
||||
title: "Chat removido da pasta",
|
||||
description: "Chat movido para 'Sem Pasta'.",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Erro ao remover chat",
|
||||
description: "Não foi possível remover o chat da pasta.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteChat = () => {
|
||||
const handleDeleteChat = async () => {
|
||||
if (deletingChat) {
|
||||
try {
|
||||
chatService.deleteChat(deletingChat.id);
|
||||
loadChatsAndFolders();
|
||||
await chatService.deleteChat(deletingChat.id);
|
||||
await loadChatsAndFolders();
|
||||
setDeletingChat(null);
|
||||
setIsDeleteChatOpen(false);
|
||||
|
||||
@@ -258,22 +229,23 @@ export const ChatSidebar = ({ isCollapsed, onToggleCollapse, onNewChat, onSelect
|
||||
title: "Chat excluído",
|
||||
description: "A conversa foi excluída com sucesso.",
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao excluir chat:', error);
|
||||
toast({
|
||||
title: "Erro ao excluir chat",
|
||||
description: "Não foi possível excluir o chat. Tente novamente.",
|
||||
description: error.message || "Não foi possível excluir o chat. Tente novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const openDeleteChat = (chat: StoredChat) => {
|
||||
const openDeleteChat = (chat: ChatRecord) => {
|
||||
setDeletingChat(chat);
|
||||
setIsDeleteChatOpen(true);
|
||||
};
|
||||
|
||||
const handleSelectChat = (chat: StoredChat) => {
|
||||
const handleSelectChat = (chat: ChatRecord) => {
|
||||
if (onSelectChat) {
|
||||
onSelectChat(chat);
|
||||
}
|
||||
@@ -283,20 +255,17 @@ export const ChatSidebar = ({ isCollapsed, onToggleCollapse, onNewChat, onSelect
|
||||
const filteredChats = chats.filter((chat) => {
|
||||
const searchLower = searchQuery.toLowerCase();
|
||||
const titleMatch = chat.title.toLowerCase().includes(searchLower);
|
||||
const contentMatch = chat.messages.some(msg =>
|
||||
msg.content.toLowerCase().includes(searchLower)
|
||||
);
|
||||
return titleMatch || contentMatch;
|
||||
return titleMatch;
|
||||
});
|
||||
|
||||
// Separar chats sem pasta
|
||||
const chatsWithoutFolder = filteredChats.filter((c) => !c.folderId);
|
||||
// Separar chats sem pasta (folder_id é null)
|
||||
const chatsWithoutFolder = filteredChats.filter((c) => c.folder_id === null);
|
||||
|
||||
// Agrupar chats por pasta
|
||||
// Agrupar chats por pasta (quando folder_id === folder.id)
|
||||
const chatsByFolder = folders.reduce((acc, folder) => {
|
||||
acc[folder.id] = filteredChats.filter((c) => c.folderId === folder.id);
|
||||
acc[folder.id] = filteredChats.filter((c) => c.folder_id === folder.id);
|
||||
return acc;
|
||||
}, {} as Record<string, StoredChat[]>);
|
||||
}, {} as Record<string, ChatRecord[]>);
|
||||
|
||||
if (isCollapsed) {
|
||||
return (
|
||||
@@ -382,33 +351,34 @@ export const ChatSidebar = ({ isCollapsed, onToggleCollapse, onNewChat, onSelect
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Edit Folder Dialog */}
|
||||
<Dialog open={isEditFolderOpen} onOpenChange={setIsEditFolderOpen}>
|
||||
{/* Rename Folder Dialog */}
|
||||
<Dialog open={isRenameFolderOpen} onOpenChange={setIsRenameFolderOpen}>
|
||||
<DialogContent className="glass-effect bg-card border-border z-50">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Editar Pasta</DialogTitle>
|
||||
<DialogTitle>Renomear Pasta</DialogTitle>
|
||||
<DialogDescription>
|
||||
Renomeie sua pasta de conversas.
|
||||
Digite o novo nome para a pasta "{renamingFolder?.name}".
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-folder-name">Nome da Pasta</Label>
|
||||
<Label htmlFor="rename-folder-name">Novo Nome</Label>
|
||||
<Input
|
||||
id="edit-folder-name"
|
||||
value={newFolderName}
|
||||
onChange={(e) => setNewFolderName(e.target.value)}
|
||||
placeholder="Digite o novo nome..."
|
||||
onKeyDown={(e) => e.key === "Enter" && handleEditFolder()}
|
||||
id="rename-folder-name"
|
||||
value={renamedFolderName}
|
||||
onChange={(e) => setRenamedFolderName(e.target.value)}
|
||||
placeholder="Ex: Projetos, Estudos..."
|
||||
onKeyDown={(e) => e.key === "Enter" && handleRenameFolder()}
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setIsEditFolderOpen(false)}>
|
||||
<Button variant="outline" onClick={() => setIsRenameFolderOpen(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={handleEditFolder} disabled={!newFolderName.trim()}>
|
||||
Salvar
|
||||
<Button onClick={handleRenameFolder} disabled={!renamedFolderName.trim()}>
|
||||
Renomear
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
@@ -420,7 +390,7 @@ export const ChatSidebar = ({ isCollapsed, onToggleCollapse, onNewChat, onSelect
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Excluir Pasta?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Esta ação não pode ser desfeita. As conversas dentro da pasta serão movidas para "Sem Pasta".
|
||||
Esta ação não pode ser desfeita. A pasta "{deletingFolder?.name}" será excluída.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
@@ -436,57 +406,85 @@ export const ChatSidebar = ({ isCollapsed, onToggleCollapse, onNewChat, onSelect
|
||||
{/* Conversations List */}
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="p-2 space-y-1">
|
||||
{/* Folders */}
|
||||
{folders.map((folder) => (
|
||||
<div key={folder.id} className="space-y-1">
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => toggleFolder(folder.id)}
|
||||
className="flex-1 flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-muted/50 transition-colors group"
|
||||
>
|
||||
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-primary to-secondary flex items-center justify-center flex-shrink-0">
|
||||
<Folder className="w-4 h-4 text-white" />
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<div className="w-8 h-8 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Folders */}
|
||||
{folders.map((folder) => (
|
||||
<div key={folder.id} className="space-y-1">
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => toggleFolder(folder.id)}
|
||||
className="flex-1 flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-muted/50 transition-colors group"
|
||||
>
|
||||
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-primary to-secondary flex items-center justify-center flex-shrink-0">
|
||||
<Folder className="w-4 h-4 text-white" />
|
||||
</div>
|
||||
<span className="font-medium text-sm flex-1 text-left">
|
||||
{folder.name}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{chatsByFolder[folder.id]?.length || 0}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<MoreVertical className="w-3 h-3" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="glass-effect bg-popover border-border z-50">
|
||||
<DropdownMenuItem
|
||||
className="gap-2"
|
||||
onClick={() => openRenameFolder(folder)}
|
||||
>
|
||||
<Edit className="w-3 h-3" />
|
||||
Renomear Pasta
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="gap-2 text-destructive"
|
||||
onClick={() => openDeleteFolder(folder)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
Excluir Pasta
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<span className="font-medium text-sm flex-1 text-left">
|
||||
{folder.name}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{chatsByFolder[folder.id]?.length || 0}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<MoreVertical className="w-3 h-3" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="glass-effect bg-popover border-border z-50">
|
||||
<DropdownMenuItem
|
||||
className="gap-2"
|
||||
onClick={() => openEditFolder(folder)}
|
||||
>
|
||||
<Edit className="w-3 h-3" />
|
||||
Editar Nome
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="gap-2 text-destructive"
|
||||
onClick={() => openDeleteFolder(folder)}
|
||||
>
|
||||
<Trash2 className="w-3 h-3" />
|
||||
Excluir Pasta
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
{expandedFolders.has(folder.id) && chatsByFolder[folder.id]?.length > 0 && (
|
||||
<div className="ml-6 space-y-1">
|
||||
{chatsByFolder[folder.id].map((chat) => (
|
||||
<ChatItem
|
||||
key={chat.id}
|
||||
chat={chat}
|
||||
isSelected={currentChatId === chat.id}
|
||||
onSelect={() => handleSelectChat(chat)}
|
||||
folders={folders}
|
||||
onMoveToFolder={moveToFolder}
|
||||
onDelete={() => openDeleteChat(chat)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{expandedFolders.has(folder.id) && chatsByFolder[folder.id]?.length > 0 && (
|
||||
<div className="ml-6 space-y-1">
|
||||
{chatsByFolder[folder.id].map((chat) => (
|
||||
{/* Chats without folder */}
|
||||
{chatsWithoutFolder.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<div className="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
|
||||
Sem Pasta
|
||||
</div>
|
||||
{chatsWithoutFolder.map((chat) => (
|
||||
<ChatItem
|
||||
key={chat.id}
|
||||
chat={chat}
|
||||
@@ -494,34 +492,25 @@ export const ChatSidebar = ({ isCollapsed, onToggleCollapse, onNewChat, onSelect
|
||||
onSelect={() => handleSelectChat(chat)}
|
||||
folders={folders}
|
||||
onMoveToFolder={moveToFolder}
|
||||
onRemoveFromFolder={removeFromFolder}
|
||||
onDelete={() => openDeleteChat(chat)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Chats without folder */}
|
||||
{chatsWithoutFolder.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<div className="px-3 py-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
|
||||
Sem Pasta
|
||||
</div>
|
||||
{chatsWithoutFolder.map((chat) => (
|
||||
<ChatItem
|
||||
key={chat.id}
|
||||
chat={chat}
|
||||
isSelected={currentChatId === chat.id}
|
||||
onSelect={() => handleSelectChat(chat)}
|
||||
folders={folders}
|
||||
onMoveToFolder={moveToFolder}
|
||||
onRemoveFromFolder={removeFromFolder}
|
||||
onDelete={() => openDeleteChat(chat)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{/* Empty state */}
|
||||
{!isLoading && chats.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center p-8 text-center">
|
||||
<MessageSquare className="w-12 h-12 text-muted-foreground opacity-50 mb-3" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Nenhuma conversa ainda
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Clique em "Novo Chat" para começar
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
@@ -548,12 +537,11 @@ export const ChatSidebar = ({ isCollapsed, onToggleCollapse, onNewChat, onSelect
|
||||
};
|
||||
|
||||
interface ChatItemProps {
|
||||
chat: StoredChat;
|
||||
chat: ChatRecord;
|
||||
isSelected: boolean;
|
||||
onSelect: () => void;
|
||||
folders: StoredFolder[];
|
||||
folders: FolderRecord[];
|
||||
onMoveToFolder: (chatId: string, folderId: string) => void;
|
||||
onRemoveFromFolder: (chatId: string) => void;
|
||||
onDelete: () => void;
|
||||
}
|
||||
|
||||
@@ -563,50 +551,29 @@ const ChatItem = ({
|
||||
onSelect,
|
||||
folders,
|
||||
onMoveToFolder,
|
||||
onRemoveFromFolder,
|
||||
onDelete,
|
||||
}: ChatItemProps) => {
|
||||
// Pega a última mensagem do usuário
|
||||
const lastUserMessage = chat.messages
|
||||
.filter(m => m.role === 'user')
|
||||
.slice(-1)[0];
|
||||
|
||||
// Formata timestamp relativo
|
||||
const timeAgo = formatDistanceToNow(new Date(chat.updatedAt), {
|
||||
const timeAgo = formatDistanceToNow(new Date(chat.updated_at), {
|
||||
addSuffix: true,
|
||||
locale: ptBR,
|
||||
});
|
||||
|
||||
// Limita o título a 40 caracteres
|
||||
const truncatedTitle = chat.title.length > 40
|
||||
? chat.title.substring(0, 40) + '...'
|
||||
: chat.title;
|
||||
|
||||
// Limita a mensagem a 50 caracteres
|
||||
const truncatedMessage = lastUserMessage?.content.length > 50
|
||||
? lastUserMessage.content.substring(0, 50) + '...'
|
||||
: lastUserMessage?.content;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`group flex items-start gap-2 px-3 py-2 rounded-lg cursor-pointer transition-all ${
|
||||
className={`group flex items-center gap-2 px-3 py-2 rounded-lg cursor-pointer transition-all w-full ${
|
||||
isSelected
|
||||
? "bg-sidebar-accent cyber-border"
|
||||
: "hover:bg-muted/50"
|
||||
}`}
|
||||
onClick={onSelect}
|
||||
>
|
||||
<MessageSquare className="w-4 h-4 mt-0.5 text-primary flex-shrink-0" />
|
||||
<div className="flex-1 min-w-0 overflow-hidden">
|
||||
<MessageSquare className="w-4 h-4 text-primary flex-shrink-0" />
|
||||
<div className="flex-1 min-w-0 max-w-[180px]">
|
||||
<p className="text-sm font-medium truncate" title={chat.title}>
|
||||
{truncatedTitle}
|
||||
{chat.title}
|
||||
</p>
|
||||
{lastUserMessage && (
|
||||
<p className="text-xs text-muted-foreground truncate" title={lastUserMessage.content}>
|
||||
{truncatedMessage}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
<p className="text-xs text-muted-foreground truncate" title={timeAgo}>
|
||||
{timeAgo}
|
||||
</p>
|
||||
</div>
|
||||
@@ -622,17 +589,8 @@ const ChatItem = ({
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="glass-effect bg-popover border-border z-50">
|
||||
{chat.folderId && (
|
||||
<DropdownMenuItem
|
||||
className="gap-2"
|
||||
onClick={() => onRemoveFromFolder(chat.id)}
|
||||
>
|
||||
<FolderInput className="w-3 h-3" />
|
||||
Remover da Pasta
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
|
||||
{folders.map((folder) => (
|
||||
{/* Opções para mover para pastas */}
|
||||
{folders.filter(f => f.id !== chat.folder_id).map((folder) => (
|
||||
<DropdownMenuItem
|
||||
key={folder.id}
|
||||
className="gap-2"
|
||||
|
||||
@@ -4,10 +4,13 @@ import { ChatMessage } from "./ChatMessage";
|
||||
import { ChatInput } from "./ChatInput";
|
||||
import { ChatSidebar } from "./ChatSidebar";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { chatService, StoredChat } from "@/services/chat";
|
||||
import { chatService, ChatRecord, MessageRecord } from "@/services/chat";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { getModelId } from "@/config/models";
|
||||
|
||||
// Texto padrão da personalidade (usado para novos chats)
|
||||
const DEFAULT_SYSTEM_PROMPT = "Você é um assistente útil e prestativo.";
|
||||
|
||||
interface Message {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
@@ -26,7 +29,8 @@ export const ChatView = () => {
|
||||
const [selectedModel, setSelectedModel] = useState("GPT-4o");
|
||||
// Inicia com "0" - será atualizado com o chat_id real após primeira resposta da API
|
||||
const [currentChatId, setCurrentChatId] = useState("0");
|
||||
const [systemPrompt, setSystemPrompt] = useState("Você é um assistente útil e prestativo.");
|
||||
// Inicia com texto padrão - será atualizado ao carregar chat existente
|
||||
const [systemPrompt, setSystemPrompt] = useState(DEFAULT_SYSTEM_PROMPT);
|
||||
const [messages, setMessages] = useState<Message[]>([
|
||||
{
|
||||
id: "1",
|
||||
@@ -38,44 +42,46 @@ export const ChatView = () => {
|
||||
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
// Salva o chat no localStorage sempre que as mensagens mudam
|
||||
useEffect(() => {
|
||||
if (messages.length > 1) { // Salva apenas se houver mensagens além da inicial
|
||||
saveCurrentChat();
|
||||
// Dispara evento customizado para a sidebar recarregar
|
||||
window.dispatchEvent(new Event('chatUpdated'));
|
||||
}
|
||||
}, [messages]);
|
||||
// NOTA: Salvamento automático desabilitado - mensagens já são salvas na API
|
||||
// quando enviadas via handleSendMessage
|
||||
// useEffect(() => {
|
||||
// if (messages.length > 1) {
|
||||
// saveCurrentChat();
|
||||
// window.dispatchEvent(new Event('chatUpdated'));
|
||||
// }
|
||||
// }, [messages]);
|
||||
|
||||
// Função para salvar o chat atual
|
||||
const saveCurrentChat = () => {
|
||||
try {
|
||||
const chatTitle = chatService.generateChatTitle(
|
||||
messages.find(m => m.role === 'user')?.content || 'Nova Conversa'
|
||||
);
|
||||
|
||||
const storedChat: StoredChat = {
|
||||
id: currentChatId,
|
||||
title: chatTitle,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
model: selectedModel,
|
||||
systemPrompt: systemPrompt,
|
||||
messages: messages.map(msg => ({
|
||||
...msg,
|
||||
timestamp: new Date(),
|
||||
})),
|
||||
};
|
||||
|
||||
chatService.saveChat(storedChat);
|
||||
} catch (error) {
|
||||
console.error('Erro ao salvar chat:', error);
|
||||
}
|
||||
};
|
||||
// NOTA: Função de salvamento localStorage desabilitada - migrado para banco de dados
|
||||
// const saveCurrentChat = () => {
|
||||
// try {
|
||||
// const chatTitle = chatService.generateChatTitle(
|
||||
// messages.find(m => m.role === 'user')?.content || 'Nova Conversa'
|
||||
// );
|
||||
// const storedChat: StoredChat = {
|
||||
// id: currentChatId,
|
||||
// title: chatTitle,
|
||||
// createdAt: new Date(),
|
||||
// updatedAt: new Date(),
|
||||
// model: selectedModel,
|
||||
// systemPrompt: systemPrompt,
|
||||
// messages: messages.map(msg => ({
|
||||
// ...msg,
|
||||
// timestamp: new Date(),
|
||||
// })),
|
||||
// };
|
||||
// chatService.saveChat(storedChat);
|
||||
// } catch (error) {
|
||||
// console.error('Erro ao salvar chat:', error);
|
||||
// }
|
||||
// };
|
||||
|
||||
const handleNewChat = () => {
|
||||
// Reseta para "0" - novo chat sempre começa com chat_id "0"
|
||||
setCurrentChatId("0");
|
||||
|
||||
// Reseta a personalidade para o texto padrão
|
||||
setSystemPrompt(DEFAULT_SYSTEM_PROMPT);
|
||||
|
||||
setMessages([
|
||||
{
|
||||
id: "1",
|
||||
@@ -89,22 +95,58 @@ export const ChatView = () => {
|
||||
window.dispatchEvent(new Event('chatUpdated'));
|
||||
};
|
||||
|
||||
const handleLoadChat = (chat: StoredChat) => {
|
||||
// Carrega um chat existente do histórico
|
||||
const handleLoadChat = async (chat: ChatRecord) => {
|
||||
// Carrega um chat existente do banco de dados
|
||||
setCurrentChatId(chat.id);
|
||||
setSelectedModel(chat.model);
|
||||
setSystemPrompt(chat.systemPrompt);
|
||||
|
||||
// Converte mensagens do StoredChat para Message
|
||||
const loadedMessages: Message[] = chat.messages.map(msg => ({
|
||||
id: msg.id,
|
||||
role: msg.role,
|
||||
content: msg.content,
|
||||
model: msg.model,
|
||||
attachments: msg.attachments,
|
||||
}));
|
||||
// Atualiza a personalidade com o valor do banco de dados
|
||||
// Se não tiver personalidade salva, usa o texto padrão
|
||||
setSystemPrompt(chat.personalidade || DEFAULT_SYSTEM_PROMPT);
|
||||
|
||||
setMessages(loadedMessages);
|
||||
// Limpa mensagens enquanto carrega
|
||||
setMessages([]);
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Busca mensagens do chat na API
|
||||
const messagesFromAPI = await chatService.getChatMessages(chat.id);
|
||||
|
||||
// Converte MessageRecord para Message
|
||||
const loadedMessages: Message[] = messagesFromAPI.map((msg: MessageRecord) => ({
|
||||
id: msg.id,
|
||||
role: msg.role,
|
||||
content: msg.content,
|
||||
model: msg.model_name, // Nome do modelo retornado pela API
|
||||
attachments: msg.has_attachments ? [] : undefined, // Não temos detalhes dos anexos no GET
|
||||
}));
|
||||
|
||||
setMessages(loadedMessages);
|
||||
|
||||
toast({
|
||||
title: "Chat carregado",
|
||||
description: `${loadedMessages.length} mensagens carregadas.`,
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao carregar mensagens:', error);
|
||||
|
||||
toast({
|
||||
title: "Erro ao carregar chat",
|
||||
description: error.message || "Não foi possível carregar as mensagens.",
|
||||
variant: "destructive",
|
||||
});
|
||||
|
||||
// Inicia com mensagem padrão em caso de erro
|
||||
setMessages([
|
||||
{
|
||||
id: "1",
|
||||
role: "assistant",
|
||||
content: "Olá! Sou o assistente HGTX Codex. Como posso ajudá-lo hoje?",
|
||||
model: selectedModel,
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSendMessage = async (content: string, files?: File[]) => {
|
||||
@@ -142,7 +184,18 @@ export const ChatView = () => {
|
||||
// Isso mantém o contexto da conversa para as próximas mensagens
|
||||
if (response.chat_id && response.chat_id !== currentChatId) {
|
||||
console.log(`Chat ID atualizado: ${currentChatId} → ${response.chat_id}`);
|
||||
|
||||
// Se estava com chat_id "0", significa que é a primeira mensagem
|
||||
// e o chat acabou de ser criado no backend
|
||||
const isFirstMessage = currentChatId === "0";
|
||||
|
||||
setCurrentChatId(response.chat_id);
|
||||
|
||||
// Dispara evento para ChatSidebar recarregar e mostrar o novo chat
|
||||
if (isFirstMessage) {
|
||||
console.log('Primeira mensagem - novo chat criado, atualizando sidebar');
|
||||
window.dispatchEvent(new Event('chatUpdated'));
|
||||
}
|
||||
}
|
||||
|
||||
const aiResponse: Message = {
|
||||
|
||||
@@ -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
|
||||
@@ -72,38 +92,54 @@ 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));
|
||||
|
||||
if (response.success && response.image_url && response.image_generation_id) {
|
||||
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');
|
||||
// Se success for false ou faltarem dados, trata como erro
|
||||
throw {
|
||||
message: response.message || 'Erro ao gerar imagem',
|
||||
code: response.code,
|
||||
};
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Erro na geração de imagem:', error);
|
||||
|
||||
// Exibe a mensagem de erro exata retornada pela API
|
||||
const errorMessage = error.message || "Não foi possível gerar a imagem. Tente novamente.";
|
||||
const errorCode = error.code ? ` (${error.code})` : '';
|
||||
|
||||
toast({
|
||||
title: "Erro na geração",
|
||||
description: error.message || "Não foi possível gerar a imagem. Tente novamente.",
|
||||
description: errorMessage + errorCode,
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
@@ -111,22 +147,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 +197,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 +293,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 +307,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 +414,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 +424,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 +439,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 +465,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 +473,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 +482,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 +493,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
|
||||
|
||||
+42
-16
@@ -9,6 +9,21 @@ export interface ModelConfig {
|
||||
description?: string; // Descrição opcional do modelo
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para modelo retornado pela API do banco de dados
|
||||
*/
|
||||
export interface ModelIA {
|
||||
id: number;
|
||||
provider_id: number;
|
||||
name: string;
|
||||
model_identifier: string;
|
||||
cost_input_per_million: string;
|
||||
cost_output_per_million: string;
|
||||
is_active: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lista de modelos disponíveis
|
||||
* NOTA: Estes dados correspondem à tabela de modelos do banco de dados.
|
||||
@@ -112,21 +127,32 @@ export function getModelNames(): string[] {
|
||||
}
|
||||
|
||||
/**
|
||||
* FUTURA INTEGRAÇÃO COM BANCO DE DADOS
|
||||
* Busca modelos de IA disponíveis no banco de dados
|
||||
*
|
||||
* Quando a API estiver pronta, substituir AVAILABLE_MODELS por chamada à API:
|
||||
*
|
||||
* export async function fetchModelsFromDatabase(): Promise<ModelConfig[]> {
|
||||
* const response = await apiService.get('/api/models');
|
||||
* return response.data.map((model: any) => ({
|
||||
* name: model.name,
|
||||
* id: model.id.toString(),
|
||||
* description: model.description || '',
|
||||
* }));
|
||||
* }
|
||||
*
|
||||
* Nos componentes, usar:
|
||||
* - useEffect para carregar modelos na montagem
|
||||
* - useState para armazenar lista de modelos
|
||||
* - Loading state durante o fetch
|
||||
* @returns Promise com array de modelos ativos
|
||||
*/
|
||||
export async function fetchModelsFromDatabase(): Promise<ModelConfig[]> {
|
||||
try {
|
||||
// Importa dinamicamente para evitar circular dependency
|
||||
const { apiService } = await import('@/services/api');
|
||||
|
||||
const response = await apiService.get<ModelIA[]>('/webhook/codex/get_models_ia');
|
||||
|
||||
console.log('Modelos carregados da API:', response.data);
|
||||
|
||||
// Filtra apenas modelos ativos e converte para ModelConfig
|
||||
return response.data
|
||||
.filter(model => model.is_active === 1)
|
||||
.map((model: ModelIA) => ({
|
||||
name: model.name,
|
||||
id: model.id.toString(),
|
||||
description: `${model.model_identifier}`,
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error('Erro ao buscar modelos da API:', error);
|
||||
|
||||
// Fallback para modelos hardcoded em caso de erro
|
||||
console.warn('Usando modelos hardcoded como fallback');
|
||||
return AVAILABLE_MODELS;
|
||||
}
|
||||
}
|
||||
|
||||
+72
-1
@@ -31,6 +31,12 @@
|
||||
--destructive: 0 84% 60%;
|
||||
--destructive-foreground: 0 0% 100%;
|
||||
|
||||
--success: 142 71% 45%;
|
||||
--success-foreground: 0 0% 100%;
|
||||
|
||||
--warning: 38 92% 50%;
|
||||
--warning-foreground: 222 47% 11%;
|
||||
|
||||
--border: 214 32% 91%;
|
||||
--input: 214 32% 91%;
|
||||
--ring: 190 100% 45%;
|
||||
@@ -84,6 +90,12 @@
|
||||
--destructive: 0 84% 60%;
|
||||
--destructive-foreground: 200 100% 95%;
|
||||
|
||||
--success: 142 71% 45%;
|
||||
--success-foreground: 222 47% 5%;
|
||||
|
||||
--warning: 38 92% 50%;
|
||||
--warning-foreground: 222 47% 5%;
|
||||
|
||||
--border: 222 30% 18%;
|
||||
--input: 222 30% 18%;
|
||||
--ring: 190 100% 50%;
|
||||
@@ -137,7 +149,7 @@
|
||||
|
||||
@layer components {
|
||||
.glass-effect {
|
||||
@apply bg-card/40 backdrop-blur-xl border border-border/50;
|
||||
@apply bg-card/80 backdrop-blur-xl border border-border/50;
|
||||
}
|
||||
|
||||
.cyber-glow {
|
||||
@@ -152,4 +164,63 @@
|
||||
.gradient-text {
|
||||
@apply bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent;
|
||||
}
|
||||
|
||||
.metric-card {
|
||||
@apply bg-card rounded-xl p-5 border border-border shadow-sm transition-all duration-300 hover:shadow-md hover:border-primary/30;
|
||||
}
|
||||
|
||||
.nav-item {
|
||||
@apply flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 w-full;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.nav-item svg,
|
||||
.nav-item .w-5 {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.nav-item span {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.nav-item-inactive {
|
||||
@apply text-muted-foreground hover:text-foreground hover:bg-sidebar-accent;
|
||||
}
|
||||
|
||||
.nav-item-active {
|
||||
@apply text-primary bg-sidebar-accent font-medium;
|
||||
}
|
||||
|
||||
.status-dot {
|
||||
@apply w-2 h-2 rounded-full;
|
||||
}
|
||||
|
||||
.status-connected {
|
||||
@apply bg-success;
|
||||
box-shadow: 0 0 8px hsl(var(--success) / 0.6);
|
||||
animation: pulse 2s infinite;
|
||||
}
|
||||
|
||||
.status-error {
|
||||
@apply bg-destructive;
|
||||
box-shadow: 0 0 8px hsl(var(--destructive) / 0.6);
|
||||
animation: pulse 2s infinite;
|
||||
}
|
||||
|
||||
.status-warning {
|
||||
@apply bg-warning;
|
||||
box-shadow: 0 0 8px hsl(var(--warning) / 0.6);
|
||||
animation: pulse 2s infinite;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Routes, Route } from "react-router-dom";
|
||||
import { MainLayout } from "@/modules/intelligence-ia/components/layout/MainLayout";
|
||||
import Index from "./pages/Index";
|
||||
import Integrations from "./pages/Integrations";
|
||||
import Financas from "./pages/Financas";
|
||||
import MeuPerfil from "./pages/MeuPerfil";
|
||||
import NotFound from "./pages/NotFound";
|
||||
|
||||
// App do módulo Intelligence IA - funciona como subpath
|
||||
// Não precisa de BrowserRouter, QueryClientProvider, TooltipProvider, Toaster ou Sonner
|
||||
// pois já são fornecidos pelo App principal
|
||||
const IntelligenceIAApp = () => {
|
||||
return (
|
||||
<MainLayout>
|
||||
<Routes>
|
||||
<Route index element={<Index />} />
|
||||
<Route path="integracoes" element={<Integrations />} />
|
||||
<Route path="financas" element={<Financas />} />
|
||||
<Route path="meu-perfil" element={<MeuPerfil />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</MainLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export default IntelligenceIAApp;
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 831 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 71 KiB |
@@ -0,0 +1,28 @@
|
||||
import { NavLink as RouterNavLink, NavLinkProps } from "react-router-dom";
|
||||
import { forwardRef } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface NavLinkCompatProps extends Omit<NavLinkProps, "className"> {
|
||||
className?: string;
|
||||
activeClassName?: string;
|
||||
pendingClassName?: string;
|
||||
}
|
||||
|
||||
const NavLink = forwardRef<HTMLAnchorElement, NavLinkCompatProps>(
|
||||
({ className, activeClassName, pendingClassName, to, ...props }, ref) => {
|
||||
return (
|
||||
<RouterNavLink
|
||||
ref={ref}
|
||||
to={to}
|
||||
className={({ isActive, isPending }) =>
|
||||
cn(className, isActive && activeClassName, isPending && pendingClassName)
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
NavLink.displayName = "NavLink";
|
||||
|
||||
export { NavLink };
|
||||
@@ -0,0 +1,44 @@
|
||||
import { ReactNode } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface MetricCardProps {
|
||||
title: string;
|
||||
value: string | number;
|
||||
subtitle?: string;
|
||||
icon: ReactNode;
|
||||
status?: "success" | "warning" | "error";
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function MetricCard({
|
||||
title,
|
||||
value,
|
||||
subtitle,
|
||||
icon,
|
||||
status,
|
||||
className,
|
||||
}: MetricCardProps) {
|
||||
return (
|
||||
<div className={cn("metric-card animate-fade-in", className)}>
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="p-2.5 rounded-lg bg-primary/10 text-primary">
|
||||
{icon}
|
||||
</div>
|
||||
{status && (
|
||||
<span
|
||||
className={cn("status-dot", {
|
||||
"status-connected": status === "success",
|
||||
"status-warning": status === "warning",
|
||||
"status-error": status === "error",
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm mb-1">{title}</p>
|
||||
<p className="text-2xl font-semibold text-foreground">{value}</p>
|
||||
{subtitle && (
|
||||
<p className="text-muted-foreground text-xs mt-1">{subtitle}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface StatusBadgeProps {
|
||||
status: "connected" | "error" | "disconnected" | "pending";
|
||||
label?: string;
|
||||
}
|
||||
|
||||
const statusConfig = {
|
||||
connected: {
|
||||
label: "Conectado",
|
||||
className: "bg-success/10 text-success border-success/20",
|
||||
},
|
||||
error: {
|
||||
label: "Erro",
|
||||
className: "bg-destructive/10 text-destructive border-destructive/20",
|
||||
},
|
||||
disconnected: {
|
||||
label: "Desconectado",
|
||||
className: "bg-muted text-muted-foreground border-border",
|
||||
},
|
||||
pending: {
|
||||
label: "Pendente",
|
||||
className: "bg-warning/10 text-warning border-warning/20",
|
||||
},
|
||||
};
|
||||
|
||||
export function StatusBadge({ status, label }: StatusBadgeProps) {
|
||||
const config = statusConfig[status];
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium border",
|
||||
config.className
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn("w-1.5 h-1.5 rounded-full", {
|
||||
"bg-success": status === "connected",
|
||||
"bg-destructive": status === "error",
|
||||
"bg-muted-foreground": status === "disconnected",
|
||||
"bg-warning": status === "pending",
|
||||
})}
|
||||
/>
|
||||
{label || config.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Eye, EyeOff, Loader2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import asanaLogo from "@/modules/intelligence-ia/assets/asana-logo.png";
|
||||
|
||||
interface Workspace {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface AsanaCardProps {
|
||||
apiKey?: string;
|
||||
workspaces?: Workspace[];
|
||||
users?: User[];
|
||||
selectedWorkspaceId?: string;
|
||||
selectedUserId?: string;
|
||||
loadingWorkspaces?: boolean;
|
||||
loadingUsers?: boolean;
|
||||
loadingIntegration?: boolean;
|
||||
hasIntegration?: boolean;
|
||||
saving?: boolean;
|
||||
onSave?: (apiKey: string, workspaceId: string, userId: string) => void | Promise<void>;
|
||||
onConfirmApiKey?: (apiKey: string) => void | Promise<void>;
|
||||
onWorkspaceChange?: (workspaceId: string) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export function AsanaCard({
|
||||
apiKey = "",
|
||||
workspaces = [],
|
||||
users = [],
|
||||
selectedWorkspaceId = "",
|
||||
selectedUserId = "",
|
||||
loadingWorkspaces = false,
|
||||
loadingUsers = false,
|
||||
loadingIntegration = false,
|
||||
hasIntegration = false,
|
||||
saving = false,
|
||||
onSave,
|
||||
onConfirmApiKey,
|
||||
onWorkspaceChange,
|
||||
}: AsanaCardProps) {
|
||||
const [showKey, setShowKey] = useState(false);
|
||||
const [key, setKey] = useState(apiKey);
|
||||
const [selectedWorkspace, setSelectedWorkspace] = useState(selectedWorkspaceId);
|
||||
const [selectedUser, setSelectedUser] = useState(selectedUserId);
|
||||
const [isApiKeyConfirmed, setIsApiKeyConfirmed] = useState(!!apiKey);
|
||||
|
||||
// Atualiza os valores quando as props mudam (carregamento inicial)
|
||||
useEffect(() => {
|
||||
if (apiKey) {
|
||||
setKey(apiKey);
|
||||
setIsApiKeyConfirmed(true);
|
||||
}
|
||||
}, [apiKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedWorkspaceId) {
|
||||
setSelectedWorkspace(selectedWorkspaceId);
|
||||
}
|
||||
}, [selectedWorkspaceId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedUserId) {
|
||||
setSelectedUser(selectedUserId);
|
||||
}
|
||||
}, [selectedUserId]);
|
||||
|
||||
const handleKeyChange = (value: string) => {
|
||||
setKey(value);
|
||||
setSelectedWorkspace("");
|
||||
setSelectedUser("");
|
||||
setIsApiKeyConfirmed(false);
|
||||
};
|
||||
|
||||
const handleConfirmApiKey = async () => {
|
||||
if (key.length >= 5) {
|
||||
setIsApiKeyConfirmed(true);
|
||||
// Chama a função assíncrona para buscar workspaces
|
||||
await onConfirmApiKey?.(key);
|
||||
}
|
||||
};
|
||||
|
||||
const handleWorkspaceChange = async (value: string) => {
|
||||
setSelectedWorkspace(value);
|
||||
setSelectedUser("");
|
||||
// Chama a função assíncrona para buscar usuários
|
||||
await onWorkspaceChange?.(value);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
await onSave?.(key, selectedWorkspace, selectedUser);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="metric-card space-y-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-12 h-12 rounded-xl bg-muted flex items-center justify-center">
|
||||
<img src={asanaLogo} alt="Asana" className="w-6 h-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-foreground font-medium">Asana</h3>
|
||||
<p className="text-muted-foreground text-sm">Gerencie tarefas e projetos</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label className="text-sm text-muted-foreground mb-1.5 block">
|
||||
API Key / Token
|
||||
</label>
|
||||
<div className="relative">
|
||||
{loadingIntegration ? (
|
||||
<div className="relative">
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Input
|
||||
type={showKey ? "text" : "password"}
|
||||
value={key}
|
||||
onChange={(e) => handleKeyChange(e.target.value)}
|
||||
placeholder="Insira sua chave de API"
|
||||
className="pr-10 bg-card border-border"
|
||||
disabled={loadingWorkspaces}
|
||||
/>
|
||||
<button
|
||||
onClick={() => setShowKey(!showKey)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||
disabled={loadingWorkspaces}
|
||||
>
|
||||
{showKey ? (
|
||||
<EyeOff className="w-4 h-4" />
|
||||
) : (
|
||||
<Eye className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleConfirmApiKey}
|
||||
disabled={key.length < 5 || isApiKeyConfirmed || loadingWorkspaces}
|
||||
className="shrink-0"
|
||||
>
|
||||
{loadingWorkspaces ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Carregando...
|
||||
</>
|
||||
) : isApiKeyConfirmed ? (
|
||||
"Confirmado"
|
||||
) : (
|
||||
"Confirmar"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm text-muted-foreground mb-1.5 block">
|
||||
Workspace
|
||||
</label>
|
||||
{loadingIntegration ? (
|
||||
<div className="relative">
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<div className="absolute inset-0 flex items-center justify-center gap-2">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
<span className="text-sm text-muted-foreground">Carregando integração...</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="relative">
|
||||
<Select
|
||||
value={selectedWorkspace}
|
||||
onValueChange={handleWorkspaceChange}
|
||||
disabled={loadingWorkspaces || loadingIntegration}
|
||||
>
|
||||
<SelectTrigger className="bg-card border-border">
|
||||
<SelectValue
|
||||
placeholder={
|
||||
loadingWorkspaces
|
||||
? "Carregando workspaces..."
|
||||
: workspaces.length === 0
|
||||
? "Insira o token e clique em Confirmar"
|
||||
: "Selecione um workspace"
|
||||
}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent className="bg-card border-border">
|
||||
{workspaces.map((ws) => (
|
||||
<SelectItem key={ws.id} value={ws.id}>
|
||||
{ws.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{loadingWorkspaces && (
|
||||
<div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm text-muted-foreground mb-1.5 block">
|
||||
Usuário
|
||||
</label>
|
||||
{loadingUsers ? (
|
||||
<div className="relative">
|
||||
<Skeleton className="h-10 w-full" />
|
||||
<div className="absolute inset-0 flex items-center justify-center gap-2">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
<span className="text-sm text-muted-foreground">Carregando usuários...</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="relative">
|
||||
<Select
|
||||
value={selectedUser}
|
||||
onValueChange={setSelectedUser}
|
||||
disabled={loadingUsers || !selectedWorkspace}
|
||||
>
|
||||
<SelectTrigger className="bg-card border-border">
|
||||
<SelectValue
|
||||
placeholder={
|
||||
!selectedWorkspace
|
||||
? "Selecione um workspace primeiro"
|
||||
: users.length === 0
|
||||
? "Nenhum usuário encontrado"
|
||||
: "Selecione um usuário"
|
||||
}
|
||||
/>
|
||||
</SelectTrigger>
|
||||
<SelectContent className="bg-card border-border">
|
||||
{users.map((user) => (
|
||||
<SelectItem key={user.id} value={user.id}>
|
||||
{user.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 pt-2">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSave}
|
||||
disabled={!selectedWorkspace || !selectedUser || saving}
|
||||
className="bg-primary text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
{hasIntegration ? "Salvando..." : "Criando..."}
|
||||
</>
|
||||
) : hasIntegration ? (
|
||||
"Salvar"
|
||||
) : (
|
||||
"Criar Integração"
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import googleCalendarLogo from "@/modules/intelligence-ia/assets/google-calendar-logo.png";
|
||||
|
||||
export function GoogleCalendarCard() {
|
||||
return (
|
||||
<div className="metric-card space-y-4 opacity-60">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-12 h-12 rounded-xl bg-muted flex items-center justify-center">
|
||||
<img src={googleCalendarLogo} alt="Google Calendar" className="w-6 h-6 grayscale" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-foreground font-medium">Google Calendar</h3>
|
||||
<span className="text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded-full">
|
||||
Em breve
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm">Sincronize reuniões e eventos</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 pointer-events-none">
|
||||
<div>
|
||||
<label className="text-sm text-muted-foreground mb-1.5 block">
|
||||
Client ID
|
||||
</label>
|
||||
<Input
|
||||
type="text"
|
||||
disabled
|
||||
placeholder="Insira o Client ID"
|
||||
className="bg-card border-border"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm text-muted-foreground mb-1.5 block">
|
||||
Client Secret
|
||||
</label>
|
||||
<Input
|
||||
type="password"
|
||||
disabled
|
||||
placeholder="Insira o Client Secret"
|
||||
className="bg-card border-border"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm text-muted-foreground mb-1.5 block">
|
||||
Nome da Agenda
|
||||
</label>
|
||||
<Input
|
||||
type="text"
|
||||
disabled
|
||||
placeholder="Ex: Reuniões de Trabalho"
|
||||
className="bg-card border-border"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 pt-2">
|
||||
<Button
|
||||
size="sm"
|
||||
disabled
|
||||
className="bg-primary text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
Salvar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { FileSpreadsheet } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
export function GoogleSheetsCard() {
|
||||
return (
|
||||
<div className="metric-card space-y-4 opacity-60">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-12 h-12 rounded-xl bg-muted flex items-center justify-center">
|
||||
<FileSpreadsheet className="w-6 h-6 text-muted-foreground" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="text-foreground font-medium">Google Sheets</h3>
|
||||
<span className="text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded-full">
|
||||
Em breve
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-sm">Gerencie planilhas e dados</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 pointer-events-none">
|
||||
<div>
|
||||
<label className="text-sm text-muted-foreground mb-1.5 block">
|
||||
Client ID
|
||||
</label>
|
||||
<Input
|
||||
type="text"
|
||||
disabled
|
||||
placeholder="Insira o Client ID"
|
||||
className="bg-card border-border"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm text-muted-foreground mb-1.5 block">
|
||||
Client Secret
|
||||
</label>
|
||||
<Input
|
||||
type="password"
|
||||
disabled
|
||||
placeholder="Insira o Client Secret"
|
||||
className="bg-card border-border"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm text-muted-foreground mb-1.5 block">
|
||||
Link da Planilha
|
||||
</label>
|
||||
<Input
|
||||
type="text"
|
||||
disabled
|
||||
placeholder="Cole o link da planilha aqui"
|
||||
className="bg-card border-border"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 pt-2">
|
||||
<Button
|
||||
size="sm"
|
||||
disabled
|
||||
className="bg-primary text-primary-foreground hover:bg-primary/90"
|
||||
>
|
||||
Salvar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useState } from "react";
|
||||
import { NavLink } from "react-router-dom";
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Plug,
|
||||
Bot,
|
||||
ChevronLeft,
|
||||
Menu,
|
||||
X,
|
||||
DollarSign,
|
||||
UserCircle,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const navItems = [
|
||||
{ title: "Home", path: "", icon: LayoutDashboard },
|
||||
{ title: "Finanças", path: "financas", icon: DollarSign },
|
||||
{ title: "Integrações", path: "integracoes", icon: Plug },
|
||||
{ title: "Meu Perfil", path: "meu-perfil", icon: UserCircle },
|
||||
];
|
||||
|
||||
export function AppSidebar() {
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const [mobileOpen, setMobileOpen] = useState(false);
|
||||
|
||||
const SidebarContent = () => (
|
||||
<>
|
||||
{/* Logo */}
|
||||
<div className="flex items-center gap-3 px-4 py-6 border-b border-sidebar-border">
|
||||
<div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center cyber-glow">
|
||||
<Bot className="w-5 h-5 text-primary" />
|
||||
</div>
|
||||
{!collapsed && (
|
||||
<div className="animate-fade-in">
|
||||
<h1 className="text-sidebar-foreground font-semibold text-lg">AI Agent</h1>
|
||||
<p className="text-muted-foreground text-xs">Painel Admin</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="flex-1 px-3 py-4 space-y-1">
|
||||
{navItems.map((item) => (
|
||||
<NavLink
|
||||
key={item.path}
|
||||
to={item.path}
|
||||
end={item.path === ""} // Apenas a Home precisa de match exato
|
||||
onClick={() => setMobileOpen(false)}
|
||||
className={({ isActive }) =>
|
||||
cn(
|
||||
"nav-item flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 w-full",
|
||||
isActive
|
||||
? "text-primary bg-sidebar-accent font-medium"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-sidebar-accent"
|
||||
)
|
||||
}
|
||||
>
|
||||
<item.icon className="w-5 h-5 flex-shrink-0" />
|
||||
{!collapsed && <span className="animate-fade-in">{item.title}</span>}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{/* Collapse button - desktop only */}
|
||||
<div className="hidden lg:block px-3 py-4 border-t border-sidebar-border">
|
||||
<button
|
||||
onClick={() => setCollapsed(!collapsed)}
|
||||
className="nav-item flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 w-full justify-center lg:justify-start text-muted-foreground hover:text-foreground hover:bg-sidebar-accent"
|
||||
>
|
||||
<ChevronLeft
|
||||
className={cn(
|
||||
"w-5 h-5 transition-transform duration-300 flex-shrink-0",
|
||||
collapsed && "rotate-180"
|
||||
)}
|
||||
/>
|
||||
{!collapsed && <span>Recolher</span>}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Mobile menu button */}
|
||||
<button
|
||||
onClick={() => setMobileOpen(true)}
|
||||
className="lg:hidden fixed top-4 left-4 z-50 p-2 rounded-lg bg-card border border-border shadow-sm"
|
||||
>
|
||||
<Menu className="w-5 h-5" />
|
||||
</button>
|
||||
|
||||
{/* Mobile overlay */}
|
||||
{mobileOpen && (
|
||||
<div
|
||||
className="lg:hidden fixed inset-0 bg-background/80 backdrop-blur-sm z-40"
|
||||
onClick={() => setMobileOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Mobile sidebar */}
|
||||
<aside
|
||||
className={cn(
|
||||
"lg:hidden fixed left-0 top-0 h-full w-64 bg-sidebar z-50 flex flex-col border-r border-sidebar-border transition-transform duration-300",
|
||||
mobileOpen ? "translate-x-0" : "-translate-x-full"
|
||||
)}
|
||||
>
|
||||
<button
|
||||
onClick={() => setMobileOpen(false)}
|
||||
className="absolute top-4 right-4 p-2 rounded-lg hover:bg-sidebar-accent"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
<SidebarContent />
|
||||
</aside>
|
||||
|
||||
{/* Desktop sidebar */}
|
||||
<aside
|
||||
className={cn(
|
||||
"hidden lg:flex flex-col h-screen bg-sidebar border-r border-sidebar-border transition-all duration-300 sticky top-0",
|
||||
collapsed ? "w-[72px]" : "w-64"
|
||||
)}
|
||||
>
|
||||
<SidebarContent />
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { ReactNode } from "react";
|
||||
import { AppSidebar } from "./AppSidebar";
|
||||
|
||||
interface MainLayoutProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function MainLayout({ children }: MainLayoutProps) {
|
||||
return (
|
||||
<div className="flex min-h-screen w-full bg-background">
|
||||
<AppSidebar />
|
||||
<main className="flex-1 overflow-auto">
|
||||
<div className="p-4 lg:p-8 pt-16 lg:pt-8">
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { useEffect } from "react";
|
||||
import { format } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
import { Bot, Sparkles, Zap, Brain, MessageCircle } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { GlobalFunctions } from "@/GlobalFunctions";
|
||||
export default function Dashboard() {
|
||||
const today = new Date();
|
||||
const formattedDate = format(today, "EEEE, d 'de' MMMM 'de' yyyy", { locale: ptBR });
|
||||
const hour = today.getHours();
|
||||
|
||||
const getGreeting = () => {
|
||||
if (hour < 12) return "Bom dia";
|
||||
if (hour < 18) return "Boa tarde";
|
||||
return "Boa noite";
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-[70vh] text-center px-4">
|
||||
{/* Floating particles background effect */}
|
||||
<div className="absolute inset-0 overflow-hidden pointer-events-none">
|
||||
<div className="absolute top-1/4 left-1/4 w-2 h-2 bg-primary/30 rounded-full animate-pulse" />
|
||||
<div className="absolute top-1/3 right-1/3 w-1 h-1 bg-primary/40 rounded-full animate-pulse delay-300" />
|
||||
<div className="absolute bottom-1/3 left-1/3 w-1.5 h-1.5 bg-primary/20 rounded-full animate-pulse delay-500" />
|
||||
<div className="absolute top-1/2 right-1/4 w-1 h-1 bg-primary/30 rounded-full animate-pulse delay-700" />
|
||||
</div>
|
||||
|
||||
{/* AI Agent Avatar */}
|
||||
<div className="relative mb-8 animate-fade-in">
|
||||
{/* Outer glow ring */}
|
||||
<div className="absolute inset-0 w-32 h-32 rounded-full bg-gradient-to-r from-primary/20 via-primary/10 to-primary/20 blur-xl animate-pulse" />
|
||||
|
||||
{/* Middle ring */}
|
||||
<div className="relative w-32 h-32 rounded-full bg-gradient-to-br from-primary/20 to-primary/5 p-1 cyber-glow">
|
||||
<div className="w-full h-full rounded-full bg-card border border-primary/30 flex items-center justify-center relative overflow-hidden">
|
||||
{/* Inner gradient effect */}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-primary/10 to-transparent" />
|
||||
|
||||
{/* Bot icon */}
|
||||
<Bot className="w-14 h-14 text-primary relative z-10" />
|
||||
|
||||
{/* Scanning line effect */}
|
||||
<div className="absolute inset-0 bg-gradient-to-b from-transparent via-primary/20 to-transparent h-8 animate-[slide-scan_2s_ease-in-out_infinite]" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Orbiting icons */}
|
||||
<div className="absolute -top-2 -right-2 w-10 h-10 rounded-full bg-card border border-border flex items-center justify-center shadow-lg animate-bounce">
|
||||
<Sparkles className="w-5 h-5 text-yellow-500" />
|
||||
</div>
|
||||
<div className="absolute -bottom-1 -left-1 w-8 h-8 rounded-full bg-card border border-border flex items-center justify-center shadow-lg animate-pulse">
|
||||
<Zap className="w-4 h-4 text-primary" />
|
||||
</div>
|
||||
<div className="absolute top-1/2 -right-4 w-8 h-8 rounded-full bg-card border border-border flex items-center justify-center shadow-lg animate-pulse delay-300">
|
||||
<Brain className="w-4 h-4 text-primary" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Greeting */}
|
||||
<div className="space-y-3 animate-fade-in" style={{ animationDelay: "0.2s" }}>
|
||||
<h1 className="text-4xl md:text-5xl font-bold text-foreground">
|
||||
{getGreeting()}! 👋
|
||||
</h1>
|
||||
<p className="text-xl text-muted-foreground">
|
||||
Seu agente de IA está pronto para ajudar
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Date card */}
|
||||
<div
|
||||
className="mt-8 px-6 py-3 rounded-full bg-card/50 border border-border backdrop-blur-sm animate-fade-in"
|
||||
style={{ animationDelay: "0.4s" }}
|
||||
>
|
||||
<p className="text-muted-foreground capitalize">
|
||||
📅 {formattedDate}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Status indicator */}
|
||||
<div
|
||||
className="mt-6 flex items-center gap-2 text-sm animate-fade-in"
|
||||
style={{ animationDelay: "0.6s" }}
|
||||
>
|
||||
<span className="relative flex h-3 w-3">
|
||||
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
|
||||
<span className="relative inline-flex rounded-full h-3 w-3 bg-green-500"></span>
|
||||
</span>
|
||||
<span className="text-muted-foreground">Sistema operacional</span>
|
||||
</div>
|
||||
|
||||
{/* WhatsApp Button */}
|
||||
<Button
|
||||
asChild
|
||||
size="lg"
|
||||
variant="outline"
|
||||
className="mt-8 gap-2 border-[#25D366] text-[#25D366] hover:bg-[#25D366] hover:text-white hover:border-[#25D366] animate-fade-in"
|
||||
style={{ animationDelay: "0.8s" }}
|
||||
>
|
||||
<a href="https://wa.me/5511914382960" target="_blank" rel="noopener noreferrer">
|
||||
<MessageCircle className="w-5 h-5" />
|
||||
Conversar com o Agente
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,778 @@
|
||||
import { useState, useMemo, useEffect, useCallback } from "react";
|
||||
import { format } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
import {
|
||||
DollarSign,
|
||||
TrendingUp,
|
||||
TrendingDown,
|
||||
Building2,
|
||||
User,
|
||||
Receipt,
|
||||
Filter,
|
||||
Calendar,
|
||||
Search,
|
||||
CalendarIcon,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Calendar as CalendarComponent } from "@/components/ui/calendar";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationItem,
|
||||
PaginationLink,
|
||||
PaginationNext,
|
||||
PaginationPrevious,
|
||||
} from "@/components/ui/pagination";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { userProfileService, FinancialIndicators, ExpenseItem, ExpensesResponse, ExpensesFilters, ExpenseCategory } from "@/services/userProfile";
|
||||
import { GlobalFunctions, TransferAreaProperties } from "@/GlobalFunctions";
|
||||
import { toast } from "@/hooks/use-toast";
|
||||
|
||||
// Mapeamento de categoria_id para cores (cores padrão caso não tenha categoria)
|
||||
const categoryColorMap: Record<number, string> = {
|
||||
1: "bg-orange-500/10 text-orange-600 border-orange-500/20", // Alimentação
|
||||
2: "bg-yellow-500/10 text-yellow-600 border-yellow-500/20", // Combustível
|
||||
3: "bg-purple-500/10 text-purple-600 border-purple-500/20", // Hospedagem
|
||||
4: "bg-blue-500/10 text-blue-600 border-blue-500/20", // Estacionamento
|
||||
5: "bg-indigo-500/10 text-indigo-600 border-indigo-500/20", // Pedágio
|
||||
6: "bg-cyan-500/10 text-cyan-600 border-cyan-500/20", // Transporte
|
||||
};
|
||||
|
||||
// Função auxiliar para obter informações da categoria
|
||||
const getCategoryInfo = (categoriaId: number | undefined | null, categories: ExpenseCategory[]) => {
|
||||
// Se não tem categoria_id válido, retorna padrão
|
||||
if (categoriaId === undefined || categoriaId === null || categoriaId === 0) {
|
||||
return {
|
||||
label: "Outros",
|
||||
color: "bg-gray-500/10 text-gray-600 border-gray-500/20",
|
||||
};
|
||||
}
|
||||
|
||||
// Converte para número caso venha como string
|
||||
const id = typeof categoriaId === 'string' ? parseInt(categoriaId, 10) : categoriaId;
|
||||
|
||||
// Busca a categoria na lista carregada
|
||||
const category = categories.find(cat => cat.id === id);
|
||||
|
||||
// Se encontrou a categoria, usa o nome dela
|
||||
if (category) {
|
||||
const color = categoryColorMap[id] || "bg-gray-500/10 text-gray-600 border-gray-500/20";
|
||||
return {
|
||||
label: category.nome,
|
||||
color: color,
|
||||
};
|
||||
}
|
||||
|
||||
// Se não encontrou mas tem ID válido, usa o ID com cor padrão
|
||||
const color = categoryColorMap[id] || "bg-gray-500/10 text-gray-600 border-gray-500/20";
|
||||
return {
|
||||
label: `Categoria ${id}`,
|
||||
color: color,
|
||||
};
|
||||
};
|
||||
|
||||
function formatCurrency(value: number) {
|
||||
return new Intl.NumberFormat("pt-BR", {
|
||||
style: "currency",
|
||||
currency: "BRL",
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
function formatDateTime(dateTimeString: string) {
|
||||
// Formata "2026-01-14 10:38:57" para Date
|
||||
const date = new Date(dateTimeString.replace(" ", "T"));
|
||||
return {
|
||||
date: date.toLocaleDateString("pt-BR"),
|
||||
time: date.toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" }),
|
||||
};
|
||||
}
|
||||
|
||||
export default function Financas() {
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [typeFilter, setTypeFilter] = useState<string>("all");
|
||||
const [categoryFilter, setCategoryFilter] = useState<string>("all"); // Agora será o ID da categoria ou "all"
|
||||
const [startDate, setStartDate] = useState<Date | undefined>(undefined);
|
||||
const [endDate, setEndDate] = useState<Date | undefined>(undefined);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const itemsPerPage = 10;
|
||||
|
||||
// Estados para os indicadores financeiros da API
|
||||
const [loadingIndicators, setLoadingIndicators] = useState(true);
|
||||
const [indicators, setIndicators] = useState<FinancialIndicators | null>(null);
|
||||
|
||||
// Estados para as despesas da API
|
||||
const [loadingExpenses, setLoadingExpenses] = useState(true);
|
||||
const [expensesData, setExpensesData] = useState<ExpensesResponse | null>(null);
|
||||
const [userEmail, setUserEmail] = useState<string>("");
|
||||
|
||||
// Estados para as categorias da API
|
||||
const [loadingCategories, setLoadingCategories] = useState(true);
|
||||
const [categories, setCategories] = useState<ExpenseCategory[]>([]);
|
||||
|
||||
// Carrega os indicadores financeiros da API
|
||||
useEffect(() => {
|
||||
const loadFinancialIndicators = async () => {
|
||||
try {
|
||||
setLoadingIndicators(true);
|
||||
|
||||
// Obtém o email do usuário logado
|
||||
let userEmail = GlobalFunctions.getUsuarioLogado().email;
|
||||
|
||||
// Se não tem email, tenta obter do Transfer Area como fallback
|
||||
if (!userEmail) {
|
||||
const transferEmail = GlobalFunctions.getTransferProperty(
|
||||
TransferAreaProperties.UsuarioEmail
|
||||
);
|
||||
if (transferEmail) {
|
||||
userEmail = transferEmail as string;
|
||||
}
|
||||
}
|
||||
|
||||
// Se ainda não tem email, tenta obter do token novamente após refresh
|
||||
if (!userEmail) {
|
||||
try {
|
||||
await GlobalFunctions.getToken();
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
userEmail = GlobalFunctions.getUsuarioLogado().email;
|
||||
} catch (error) {
|
||||
console.error("Erro ao fazer refresh do token:", error);
|
||||
}
|
||||
}
|
||||
|
||||
if (!userEmail) {
|
||||
console.error("Financas: Não foi possível obter email do usuário");
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Email do usuário não encontrado. Por favor, faça login novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
setLoadingIndicators(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Busca os indicadores financeiros da API
|
||||
const response = await userProfileService.getFinancialIndicators(userEmail);
|
||||
|
||||
if (response.success) {
|
||||
setIndicators(response);
|
||||
} else {
|
||||
throw new Error(response.message || "Erro ao carregar indicadores financeiros");
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error("Erro ao carregar indicadores financeiros:", error);
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: errorMessage || "Erro ao carregar indicadores financeiros.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setLoadingIndicators(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadFinancialIndicators();
|
||||
}, []);
|
||||
|
||||
// Função auxiliar para obter o email do usuário
|
||||
const getUserEmail = async (): Promise<string | null> => {
|
||||
let email = GlobalFunctions.getUsuarioLogado().email;
|
||||
|
||||
if (!email) {
|
||||
const transferEmail = GlobalFunctions.getTransferProperty(
|
||||
TransferAreaProperties.UsuarioEmail
|
||||
);
|
||||
if (transferEmail) {
|
||||
email = transferEmail as string;
|
||||
}
|
||||
}
|
||||
|
||||
if (!email) {
|
||||
try {
|
||||
await GlobalFunctions.getToken();
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
email = GlobalFunctions.getUsuarioLogado().email;
|
||||
} catch (error) {
|
||||
console.error("Erro ao fazer refresh do token:", error);
|
||||
}
|
||||
}
|
||||
|
||||
return email || null;
|
||||
};
|
||||
|
||||
// Carrega as despesas da API
|
||||
const loadExpenses = useCallback(async (page: number = 1) => {
|
||||
const emailToUse = userEmail || await getUserEmail();
|
||||
if (!emailToUse) {
|
||||
setLoadingExpenses(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!userEmail && emailToUse) {
|
||||
setUserEmail(emailToUse);
|
||||
}
|
||||
|
||||
try {
|
||||
setLoadingExpenses(true);
|
||||
|
||||
// Prepara filtros para a API
|
||||
const filters: ExpensesFilters = {
|
||||
page,
|
||||
per_page: itemsPerPage,
|
||||
};
|
||||
|
||||
if (searchTerm.trim()) {
|
||||
filters.descricao = searchTerm.trim();
|
||||
}
|
||||
|
||||
if (categoryFilter !== "all") {
|
||||
// Usa o ID da categoria diretamente
|
||||
const categoriaId = parseInt(categoryFilter, 10);
|
||||
if (!isNaN(categoriaId)) {
|
||||
filters.categoria_id = categoriaId;
|
||||
}
|
||||
}
|
||||
|
||||
if (startDate) {
|
||||
filters.data_inicial = format(startDate, "yyyy-MM-dd");
|
||||
}
|
||||
|
||||
if (endDate) {
|
||||
filters.data_final = format(endDate, "yyyy-MM-dd");
|
||||
}
|
||||
|
||||
const response = await userProfileService.getExpenses(emailToUse, filters);
|
||||
|
||||
if (response.success) {
|
||||
// Garante que a resposta tenha estrutura válida mesmo quando não há dados
|
||||
const safeResponse: ExpensesResponse = {
|
||||
success: response.success,
|
||||
total_registros: response.total_registros || 0,
|
||||
total_paginas: response.total_paginas || 0,
|
||||
per_page: response.per_page || itemsPerPage,
|
||||
pagina_atual: response.pagina_atual || page,
|
||||
data: Array.isArray(response.data)
|
||||
? response.data.filter((item) => item && item.id && Object.keys(item).length > 0)
|
||||
: [],
|
||||
};
|
||||
setExpensesData(safeResponse);
|
||||
} else {
|
||||
throw new Error("Erro ao carregar despesas");
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error("Erro ao carregar despesas:", error);
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: errorMessage || "Erro ao carregar despesas.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setLoadingExpenses(false);
|
||||
}
|
||||
}, [userEmail, searchTerm, categoryFilter, startDate, endDate, itemsPerPage]);
|
||||
|
||||
// Carrega o email do usuário e as categorias na montagem do componente
|
||||
useEffect(() => {
|
||||
const initData = async () => {
|
||||
// Carrega email do usuário
|
||||
const email = await getUserEmail();
|
||||
if (email) {
|
||||
setUserEmail(email);
|
||||
}
|
||||
|
||||
// Carrega categorias
|
||||
try {
|
||||
setLoadingCategories(true);
|
||||
const categoriesData = await userProfileService.getCategories();
|
||||
console.log("Categorias carregadas:", categoriesData);
|
||||
setCategories(categoriesData);
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar categorias:", error);
|
||||
toast({
|
||||
title: "Aviso",
|
||||
description: "Não foi possível carregar as categorias. Usando categorias padrão.",
|
||||
variant: "default",
|
||||
});
|
||||
} finally {
|
||||
setLoadingCategories(false);
|
||||
}
|
||||
};
|
||||
initData();
|
||||
}, []);
|
||||
|
||||
// Debounce para busca de descrição
|
||||
useEffect(() => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
if (userEmail) {
|
||||
setCurrentPage(1); // Reseta para página 1 ao buscar
|
||||
loadExpenses(1);
|
||||
}
|
||||
}, 500); // Aguarda 500ms após parar de digitar
|
||||
|
||||
return () => clearTimeout(timeoutId);
|
||||
}, [searchTerm, userEmail, loadExpenses]);
|
||||
|
||||
// Carrega despesas quando os filtros ou página mudam (exceto searchTerm que tem debounce)
|
||||
useEffect(() => {
|
||||
if (userEmail) {
|
||||
loadExpenses(currentPage);
|
||||
}
|
||||
}, [currentPage, typeFilter, categoryFilter, startDate, endDate, userEmail, loadExpenses]);
|
||||
|
||||
// Calculate totals - usa dados da API se disponível
|
||||
const totals = useMemo(() => {
|
||||
if (indicators && indicators.success) {
|
||||
return {
|
||||
total: parseFloat(indicators.total_despesas) || 0,
|
||||
corporate: parseFloat(indicators.total_corporativo) || 0,
|
||||
personal: parseFloat(indicators.total_pessoal) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
return { total: 0, personal: 0, corporate: 0 };
|
||||
}, [indicators]);
|
||||
|
||||
// Filtra despesas por tipo (se necessário, já que a API pode não filtrar por tipo)
|
||||
const filteredExpenses = useMemo(() => {
|
||||
if (!expensesData || !expensesData.data || !Array.isArray(expensesData.data)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Filtra objetos vazios ou inválidos
|
||||
let expenses = expensesData.data.filter((expense) => {
|
||||
// Verifica se o expense é válido e tem propriedades necessárias
|
||||
// categoria_id pode ser opcional, então não validamos ele aqui
|
||||
return expense &&
|
||||
typeof expense === 'object' &&
|
||||
expense.id &&
|
||||
expense.descricao &&
|
||||
expense.data_hora &&
|
||||
expense.valor;
|
||||
});
|
||||
|
||||
// Filtra por tipo se necessário (a API pode não ter esse filtro)
|
||||
if (typeFilter !== "all") {
|
||||
expenses = expenses.filter((expense) => expense.tipo === typeFilter);
|
||||
}
|
||||
|
||||
return expenses;
|
||||
}, [expensesData, typeFilter]);
|
||||
|
||||
const clearFilters = () => {
|
||||
setSearchTerm("");
|
||||
setTypeFilter("all");
|
||||
setCategoryFilter("all");
|
||||
setStartDate(undefined);
|
||||
setEndDate(undefined);
|
||||
setCurrentPage(1);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-fade-in">
|
||||
{/* Header */}
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold gradient-text">Finanças</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Análise de despesas pessoais e corporativas identificadas pelo agente
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Indicators */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<Card className="metric-card">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Total de Despesas</p>
|
||||
{loadingIndicators ? (
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
<span className="text-sm text-muted-foreground">Carregando...</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-2xl font-bold mt-1">{formatCurrency(totals.total)}</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center">
|
||||
<DollarSign className="w-6 h-6 text-primary" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="metric-card">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Despesas Corporativas</p>
|
||||
{loadingIndicators ? (
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
<span className="text-sm text-muted-foreground">Carregando...</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-2xl font-bold mt-1">{formatCurrency(totals.corporate)}</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-12 h-12 rounded-xl bg-secondary/10 flex items-center justify-center">
|
||||
<Building2 className="w-6 h-6 text-secondary" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="metric-card">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Despesas Pessoais</p>
|
||||
{loadingIndicators ? (
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
<span className="text-sm text-muted-foreground">Carregando...</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-2xl font-bold mt-1">{formatCurrency(totals.personal)}</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="w-12 h-12 rounded-xl bg-warning/10 flex items-center justify-center">
|
||||
<User className="w-6 h-6 text-warning" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Filter className="w-4 h-4" />
|
||||
Filtros
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col gap-3">
|
||||
{/* First row: Search + Date filters */}
|
||||
<div className="flex flex-col md:flex-row gap-3">
|
||||
<div className="flex-1">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Buscar por descrição..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => {
|
||||
setSearchTerm(e.target.value);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className={cn(
|
||||
"w-full md:w-[160px] justify-start text-left font-normal",
|
||||
!startDate && "text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{startDate ? format(startDate, "dd/MM/yyyy") : "Data inicial"}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<CalendarComponent
|
||||
mode="single"
|
||||
selected={startDate}
|
||||
onSelect={(date) => {
|
||||
setStartDate(date);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
locale={ptBR}
|
||||
initialFocus
|
||||
className={cn("p-3 pointer-events-auto")}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className={cn(
|
||||
"w-full md:w-[160px] justify-start text-left font-normal",
|
||||
!endDate && "text-muted-foreground"
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-4 w-4" />
|
||||
{endDate ? format(endDate, "dd/MM/yyyy") : "Data final"}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<CalendarComponent
|
||||
mode="single"
|
||||
selected={endDate}
|
||||
onSelect={(date) => {
|
||||
setEndDate(date);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
locale={ptBR}
|
||||
disabled={(date) => startDate ? date < startDate : false}
|
||||
initialFocus
|
||||
className={cn("p-3 pointer-events-auto")}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
|
||||
{/* Second row: Type + Category + Clear */}
|
||||
<div className="flex flex-col md:flex-row gap-3">
|
||||
<Select
|
||||
value={typeFilter}
|
||||
onValueChange={(value) => {
|
||||
setTypeFilter(value);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full md:w-[180px]">
|
||||
<SelectValue placeholder="Tipo" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todos os tipos</SelectItem>
|
||||
<SelectItem value="pessoal">Pessoal</SelectItem>
|
||||
<SelectItem value="corporativo">Corporativo</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select
|
||||
value={categoryFilter}
|
||||
onValueChange={(value) => {
|
||||
setCategoryFilter(value);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
disabled={loadingCategories}
|
||||
>
|
||||
<SelectTrigger className="w-full md:w-[180px]">
|
||||
<SelectValue placeholder={loadingCategories ? "Carregando..." : "Categoria"} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Todas categorias</SelectItem>
|
||||
{categories.map((category) => (
|
||||
<SelectItem key={category.id} value={category.id.toString()}>
|
||||
{category.nome}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button variant="outline" onClick={clearFilters}>
|
||||
Limpar filtros
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Table */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Receipt className="w-4 h-4" />
|
||||
Registro de Despesas
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[140px]">
|
||||
<div className="flex items-center gap-1">
|
||||
<Calendar className="w-3.5 h-3.5" />
|
||||
Data/Hora
|
||||
</div>
|
||||
</TableHead>
|
||||
<TableHead>Descrição</TableHead>
|
||||
<TableHead className="w-[120px]">Tipo</TableHead>
|
||||
<TableHead className="w-[130px]">Categoria</TableHead>
|
||||
<TableHead className="w-[120px] text-right">Valor</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loadingExpenses ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center py-8">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Carregando despesas...</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : filteredExpenses.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
|
||||
{expensesData && expensesData.total_registros === 0
|
||||
? "Nenhuma despesa encontrada."
|
||||
: "Nenhuma despesa encontrada com os filtros aplicados."}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
filteredExpenses.map((expense) => {
|
||||
// Validação adicional para garantir que o expense é válido
|
||||
if (!expense || !expense.id || !expense.data_hora || !expense.descricao || !expense.valor) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const { date, time } = formatDateTime(expense.data_hora);
|
||||
// Usa categoria_id diretamente (pode ser number, undefined ou null)
|
||||
const categoriaId = expense.categoria_id;
|
||||
const categoryInfo = getCategoryInfo(categoriaId, categories);
|
||||
const valor = parseFloat(expense.valor) || 0;
|
||||
|
||||
return (
|
||||
<TableRow key={expense.id}>
|
||||
<TableCell>
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{date}</span>
|
||||
<span className="text-xs text-muted-foreground">{time}</span>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<span className="font-medium">{expense.descricao || "Sem descrição"}</span>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={
|
||||
expense.tipo === "corporativo"
|
||||
? "bg-secondary/10 text-secondary border-secondary/20"
|
||||
: "bg-warning/10 text-warning border-warning/20"
|
||||
}
|
||||
>
|
||||
{expense.tipo === "corporativo" ? (
|
||||
<Building2 className="w-3 h-3 mr-1" />
|
||||
) : (
|
||||
<User className="w-3 h-3 mr-1" />
|
||||
)}
|
||||
{expense.tipo === "corporativo" ? "Corp." : "Pessoal"}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{categoryInfo ? (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={categoryInfo.color}
|
||||
>
|
||||
{categoryInfo.label}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-gray-500/10 text-gray-600 border-gray-500/20"
|
||||
>
|
||||
Sem categoria
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right font-semibold">
|
||||
{formatCurrency(valor)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Erro ao renderizar despesa:", error, expense);
|
||||
return null;
|
||||
}
|
||||
}).filter(Boolean) // Remove nulls do array
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
{/* Pagination */}
|
||||
{expensesData && expensesData.total_paginas > 0 && expensesData.total_paginas > 1 && (
|
||||
<div className="mt-4 flex items-center justify-between">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Mostrando {(currentPage - 1) * itemsPerPage + 1} a{" "}
|
||||
{Math.min(currentPage * itemsPerPage, expensesData.total_registros)} de{" "}
|
||||
{expensesData.total_registros} registros
|
||||
</p>
|
||||
<Pagination>
|
||||
<PaginationContent>
|
||||
<PaginationItem>
|
||||
<PaginationPrevious
|
||||
onClick={() => {
|
||||
if (currentPage > 1) {
|
||||
setCurrentPage(currentPage - 1);
|
||||
}
|
||||
}}
|
||||
className={
|
||||
currentPage === 1
|
||||
? "pointer-events-none opacity-50"
|
||||
: "cursor-pointer"
|
||||
}
|
||||
/>
|
||||
</PaginationItem>
|
||||
{Array.from({ length: expensesData.total_paginas }, (_, i) => i + 1).map((page) => (
|
||||
<PaginationItem key={page}>
|
||||
<PaginationLink
|
||||
onClick={() => setCurrentPage(page)}
|
||||
isActive={currentPage === page}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
{page}
|
||||
</PaginationLink>
|
||||
</PaginationItem>
|
||||
))}
|
||||
<PaginationItem>
|
||||
<PaginationNext
|
||||
onClick={() => {
|
||||
if (currentPage < expensesData.total_paginas) {
|
||||
setCurrentPage(currentPage + 1);
|
||||
}
|
||||
}}
|
||||
className={
|
||||
currentPage === expensesData.total_paginas
|
||||
? "pointer-events-none opacity-50"
|
||||
: "cursor-pointer"
|
||||
}
|
||||
/>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import Dashboard from "./Dashboard";
|
||||
|
||||
const Index = () => {
|
||||
return <Dashboard />;
|
||||
};
|
||||
|
||||
export default Index;
|
||||
@@ -0,0 +1,312 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { GoogleCalendarCard } from "@/modules/intelligence-ia/components/integrations/GoogleCalendarCard";
|
||||
import { GoogleSheetsCard } from "@/modules/intelligence-ia/components/integrations/GoogleSheetsCard";
|
||||
import { AsanaCard } from "@/modules/intelligence-ia/components/integrations/AsanaCard";
|
||||
import { asanaService } from "@/services/asana";
|
||||
import { userProfileService } from "@/services/userProfile";
|
||||
import { GlobalFunctions, TransferAreaProperties } from "@/GlobalFunctions";
|
||||
|
||||
interface Workspace {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
|
||||
export default function Integrations() {
|
||||
const [asanaWorkspaces, setAsanaWorkspaces] = useState<Workspace[]>([]);
|
||||
const [asanaUsers, setAsanaUsers] = useState<User[]>([]);
|
||||
const [loadingAsanaWorkspaces, setLoadingAsanaWorkspaces] = useState(false);
|
||||
const [loadingAsanaUsers, setLoadingAsanaUsers] = useState(false);
|
||||
const [asanaToken, setAsanaToken] = useState<string>("");
|
||||
const [asanaApiKey, setAsanaApiKey] = useState<string>("");
|
||||
const [selectedWorkspaceId, setSelectedWorkspaceId] = useState<string>("");
|
||||
const [selectedUserId, setSelectedUserId] = useState<string>("");
|
||||
const [loadingIntegration, setLoadingIntegration] = useState(true);
|
||||
const [hasIntegration, setHasIntegration] = useState(false);
|
||||
const [integrationId, setIntegrationId] = useState<string>("");
|
||||
const [userId, setUserId] = useState<string>("");
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const handleAsanaSave = async (apiKey: string, workspaceId: string, usuarioAsanaId: string) => {
|
||||
if (!apiKey || !workspaceId || !usuarioAsanaId) {
|
||||
toast.error("Preencha todos os campos obrigatórios");
|
||||
return;
|
||||
}
|
||||
|
||||
// Encontra o nome do workspace e do usuário selecionado
|
||||
const workspace = asanaWorkspaces.find(w => w.id === workspaceId);
|
||||
const user = asanaUsers.find(u => u.id === usuarioAsanaId);
|
||||
|
||||
if (!workspace || !user) {
|
||||
toast.error("Workspace ou usuário não encontrado");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setSaving(true);
|
||||
|
||||
if (hasIntegration && integrationId) {
|
||||
// Atualiza integração existente
|
||||
await asanaService.updateIntegration(integrationId, {
|
||||
api_key: apiKey,
|
||||
workspace_gid: workspaceId,
|
||||
workspace_nome: workspace.name,
|
||||
usuario_asana_gid: usuarioAsanaId,
|
||||
usuario_asana_nome: user.name,
|
||||
});
|
||||
toast.success("Integração do Asana atualizada com sucesso!");
|
||||
} else {
|
||||
// Cria nova integração
|
||||
if (!userId) {
|
||||
toast.error("ID do usuário não encontrado");
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await asanaService.createIntegration({
|
||||
user_id: userId,
|
||||
api_key: apiKey,
|
||||
workspace_gid: workspaceId,
|
||||
workspace_nome: workspace.name,
|
||||
usuario_asana_gid: usuarioAsanaId,
|
||||
usuario_asana_nome: user.name,
|
||||
});
|
||||
|
||||
if (response.success && response.integracao_id) {
|
||||
setIntegrationId(response.integracao_id);
|
||||
setHasIntegration(true);
|
||||
}
|
||||
toast.success("Integração do Asana criada com sucesso!");
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error("Erro ao salvar integração do Asana:", error);
|
||||
const errorMessage = error && typeof error === 'object' && 'message' in error
|
||||
? (error as { message: string }).message
|
||||
: "Erro ao salvar integração do Asana";
|
||||
toast.error(errorMessage);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAsanaApiKeyConfirm = async (apiKey: string) => {
|
||||
if (!apiKey || apiKey.trim().length === 0) {
|
||||
toast.error("Insira um token válido do Asana");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoadingAsanaWorkspaces(true);
|
||||
|
||||
// Busca workspaces da API do Asana
|
||||
const workspaces = await asanaService.getWorkspaces(apiKey);
|
||||
|
||||
if (workspaces && workspaces.length > 0) {
|
||||
setAsanaWorkspaces(workspaces);
|
||||
setAsanaUsers([]);
|
||||
setAsanaToken(apiKey); // Armazena o token para usar na busca de usuários
|
||||
toast.success(`${workspaces.length} workspace(s) encontrado(s)`);
|
||||
} else {
|
||||
setAsanaWorkspaces([]);
|
||||
setAsanaUsers([]);
|
||||
setAsanaToken("");
|
||||
toast.warning("Nenhum workspace encontrado para este token");
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error("Erro ao buscar workspaces do Asana:", error);
|
||||
const errorMessage = error && typeof error === 'object' && 'message' in error
|
||||
? (error as { message: string }).message
|
||||
: "Erro ao buscar workspaces do Asana. Verifique se o token está correto.";
|
||||
|
||||
toast.error(errorMessage);
|
||||
setAsanaWorkspaces([]);
|
||||
setAsanaUsers([]);
|
||||
setAsanaToken(""); // Limpa o token em caso de erro
|
||||
} finally {
|
||||
setLoadingAsanaWorkspaces(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAsanaWorkspaceChange = async (workspaceId: string) => {
|
||||
setSelectedWorkspaceId(workspaceId);
|
||||
|
||||
if (!workspaceId || !asanaToken) {
|
||||
setAsanaUsers([]);
|
||||
setSelectedUserId("");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoadingAsanaUsers(true);
|
||||
|
||||
// Busca usuários do workspace da API do Asana
|
||||
const users = await asanaService.getUsers(asanaToken, workspaceId);
|
||||
|
||||
if (users && users.length > 0) {
|
||||
setAsanaUsers(users);
|
||||
// Não mostra toast ao selecionar workspace (só quando confirmar token)
|
||||
} else {
|
||||
setAsanaUsers([]);
|
||||
setSelectedUserId("");
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error("Erro ao buscar usuários do Asana:", error);
|
||||
const errorMessage = error && typeof error === 'object' && 'message' in error
|
||||
? (error as { message: string }).message
|
||||
: "Erro ao buscar usuários do Asana. Verifique se o token está correto.";
|
||||
|
||||
toast.error(errorMessage);
|
||||
setAsanaUsers([]);
|
||||
setSelectedUserId("");
|
||||
} finally {
|
||||
setLoadingAsanaUsers(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Carrega a integração do Asana ao montar o componente
|
||||
useEffect(() => {
|
||||
const loadAsanaIntegration = async () => {
|
||||
try {
|
||||
setLoadingIntegration(true);
|
||||
|
||||
// Obtém o ID do usuário do perfil
|
||||
let userEmail = GlobalFunctions.getUsuarioLogado().email;
|
||||
|
||||
// Se não tem email, tenta obter do Transfer Area como fallback
|
||||
if (!userEmail) {
|
||||
const transferEmail = GlobalFunctions.getTransferProperty(
|
||||
TransferAreaProperties.UsuarioEmail
|
||||
);
|
||||
if (transferEmail) {
|
||||
userEmail = transferEmail as string;
|
||||
}
|
||||
}
|
||||
|
||||
// Se ainda não tem email, tenta obter do token novamente após refresh
|
||||
if (!userEmail) {
|
||||
try {
|
||||
await GlobalFunctions.getToken();
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
userEmail = GlobalFunctions.getUsuarioLogado().email;
|
||||
} catch (error) {
|
||||
console.error("Erro ao fazer refresh do token:", error);
|
||||
}
|
||||
}
|
||||
|
||||
if (!userEmail) {
|
||||
console.log("Integrations: Não foi possível obter email do usuário");
|
||||
setLoadingIntegration(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Busca o perfil do usuário para obter o ID
|
||||
const userProfile = await userProfileService.getUserProfile(userEmail);
|
||||
|
||||
if (!userProfile.success || !userProfile.id) {
|
||||
console.log("Integrations: Usuário não encontrado ou sem ID");
|
||||
setLoadingIntegration(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Armazena o ID do usuário para usar ao criar integração
|
||||
setUserId(userProfile.id);
|
||||
|
||||
// Busca a integração do Asana
|
||||
const integration = await asanaService.getIntegration(userProfile.id);
|
||||
|
||||
if (integration && integration.success) {
|
||||
// Marca que há integração existente
|
||||
setHasIntegration(true);
|
||||
|
||||
// Armazena o ID da integração (pode vir como integracao_id ou id)
|
||||
if (integration.integracao_id) {
|
||||
setIntegrationId(integration.integracao_id);
|
||||
} else if (integration.id) {
|
||||
setIntegrationId(integration.id);
|
||||
}
|
||||
|
||||
// Preenche os dados da integração
|
||||
if (integration.api_key) {
|
||||
setAsanaApiKey(integration.api_key);
|
||||
setAsanaToken(integration.api_key);
|
||||
|
||||
// Busca workspaces com o token
|
||||
try {
|
||||
const workspaces = await asanaService.getWorkspaces(integration.api_key);
|
||||
setAsanaWorkspaces(workspaces);
|
||||
|
||||
// Se tem workspace_gid, seleciona e busca usuários
|
||||
if (integration.workspace_gid) {
|
||||
setSelectedWorkspaceId(integration.workspace_gid);
|
||||
|
||||
// Busca usuários do workspace
|
||||
const users = await asanaService.getUsers(integration.api_key, integration.workspace_gid);
|
||||
setAsanaUsers(users);
|
||||
|
||||
// Se tem usuario_asana_gid, seleciona
|
||||
if (integration.usuario_asana_gid) {
|
||||
setSelectedUserId(integration.usuario_asana_gid);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar workspaces/usuários:", error);
|
||||
// Continua mesmo se não conseguir carregar workspaces
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Não há integração, marca como false
|
||||
setHasIntegration(false);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error("Erro ao carregar integração do Asana:", error);
|
||||
// Não mostra erro para o usuário, apenas deixa os campos vazios
|
||||
} finally {
|
||||
setLoadingIntegration(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadAsanaIntegration();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{/* Header */}
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-foreground mb-1">
|
||||
Integrações
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Configure as conexões do seu agente com serviços externos
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Integrations Grid */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
|
||||
<GoogleCalendarCard />
|
||||
|
||||
<GoogleSheetsCard />
|
||||
|
||||
<AsanaCard
|
||||
apiKey={asanaApiKey}
|
||||
workspaces={asanaWorkspaces}
|
||||
users={asanaUsers}
|
||||
selectedWorkspaceId={selectedWorkspaceId}
|
||||
selectedUserId={selectedUserId}
|
||||
onSave={handleAsanaSave}
|
||||
onConfirmApiKey={handleAsanaApiKeyConfirm}
|
||||
onWorkspaceChange={handleAsanaWorkspaceChange}
|
||||
loadingWorkspaces={loadingAsanaWorkspaces}
|
||||
loadingUsers={loadingAsanaUsers}
|
||||
loadingIntegration={loadingIntegration}
|
||||
hasIntegration={hasIntegration}
|
||||
saving={saving}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { User, Mail, Phone, Save, Bell, Loader2, Plus } from "lucide-react";
|
||||
import { toast } from "@/hooks/use-toast";
|
||||
import { userProfileService, UserProfile } from "@/services/userProfile";
|
||||
import { GlobalFunctions, TransferAreaProperties } from "@/GlobalFunctions";
|
||||
|
||||
const formatPhoneNumber = (value: string) => {
|
||||
const numbers = value.replace(/\D/g, "");
|
||||
|
||||
if (numbers.length <= 2) {
|
||||
return numbers;
|
||||
} else if (numbers.length <= 7) {
|
||||
return `(${numbers.slice(0, 2)}) ${numbers.slice(2)}`;
|
||||
} else if (numbers.length <= 11) {
|
||||
return `(${numbers.slice(0, 2)}) ${numbers.slice(2, 7)}-${numbers.slice(7)}`;
|
||||
}
|
||||
return `(${numbers.slice(0, 2)}) ${numbers.slice(2, 7)}-${numbers.slice(7, 11)}`;
|
||||
};
|
||||
|
||||
const MeuPerfil = () => {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [userExists, setUserExists] = useState(false);
|
||||
const [showCreateModal, setShowCreateModal] = useState(false);
|
||||
const [userId, setUserId] = useState<string>("");
|
||||
|
||||
const [nomeCompleto, setNomeCompleto] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [whatsapp, setWhatsapp] = useState("");
|
||||
const [receberLembretes, setReceberLembretes] = useState(true);
|
||||
|
||||
// Estados para o modal de criação
|
||||
const [createNome, setCreateNome] = useState("");
|
||||
const [createWhatsapp, setCreateWhatsapp] = useState("");
|
||||
const [createFollowup, setCreateFollowup] = useState(true);
|
||||
const [creating, setCreating] = useState(false);
|
||||
|
||||
// Verifica se o usuário está logado e carrega os dados
|
||||
useEffect(() => {
|
||||
const checkAuthAndLoad = async () => {
|
||||
// Verifica se há token no sessionStorage primeiro
|
||||
const jsonUsuario = sessionStorage.getItem('usuarioLogado');
|
||||
if (!jsonUsuario) {
|
||||
console.log("MeuPerfil: Não há token no sessionStorage");
|
||||
window.location.replace(import.meta.env.VITE_BASE_URL_HGTX_CORE || 'https://core.hgtx.com.br');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("MeuPerfil: Token encontrado no sessionStorage");
|
||||
|
||||
// Tenta obter o email do usuário logado
|
||||
let userEmail = GlobalFunctions.getUsuarioLogado().email;
|
||||
console.log("MeuPerfil: Email obtido:", userEmail);
|
||||
|
||||
// Se não tem email, tenta fazer refresh do token
|
||||
if (!userEmail) {
|
||||
console.log("MeuPerfil: Email vazio, tentando fazer refresh do token");
|
||||
try {
|
||||
await GlobalFunctions.getToken();
|
||||
// Aguarda um pouco para o refresh ser processado (se necessário)
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
// Verifica novamente após refresh
|
||||
userEmail = GlobalFunctions.getUsuarioLogado().email;
|
||||
console.log("MeuPerfil: Email após refresh:", userEmail);
|
||||
} catch (error) {
|
||||
console.error("MeuPerfil: Erro ao obter token:", error);
|
||||
}
|
||||
}
|
||||
|
||||
// Se ainda não tem email após tentar refresh, verifica se o token existe
|
||||
// Se o token existe mas não tem email, pode ser problema na decodificação
|
||||
if (!userEmail) {
|
||||
const usuarioData = GlobalFunctions.getUsuarioLogado();
|
||||
console.log("MeuPerfil: Dados do usuário após tentativas:", usuarioData);
|
||||
|
||||
// Se não tem email mas tem token no sessionStorage, tenta carregar mesmo assim
|
||||
// O loadUserProfile vai tratar o erro adequadamente se o email for necessário
|
||||
// Só redireciona se o token estiver completamente inválido (sem UID e sem EID)
|
||||
if (!usuarioData.email && usuarioData.UID === "0" && usuarioData.EID === "0") {
|
||||
console.log("MeuPerfil: Token completamente inválido (sem UID/EID), redirecionando");
|
||||
window.location.replace(import.meta.env.VITE_BASE_URL_HGTX_CORE || 'https://core.hgtx.com.br');
|
||||
return;
|
||||
}
|
||||
|
||||
// Se tem token mas não tem email, pode ser que o email esteja em outro campo
|
||||
// ou o token precisa ser renovado. Tenta carregar o perfil mesmo assim.
|
||||
console.log("MeuPerfil: Token existe mas email vazio, tentando carregar perfil mesmo assim");
|
||||
}
|
||||
|
||||
// Se passou na verificação (ou tem token válido), carrega o perfil
|
||||
console.log("MeuPerfil: Carregando perfil do usuário");
|
||||
loadUserProfile();
|
||||
};
|
||||
|
||||
checkAuthAndLoad();
|
||||
}, []);
|
||||
|
||||
const loadUserProfile = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
let userEmail = GlobalFunctions.getUsuarioLogado().email;
|
||||
|
||||
// Se não tem email, tenta obter do Transfer Area como fallback
|
||||
if (!userEmail) {
|
||||
console.log("MeuPerfil: Email não encontrado no token, tentando Transfer Area");
|
||||
const transferEmail = GlobalFunctions.getTransferProperty(
|
||||
TransferAreaProperties.UsuarioEmail
|
||||
);
|
||||
if (transferEmail) {
|
||||
userEmail = transferEmail as string;
|
||||
console.log("MeuPerfil: Email do Transfer Area:", userEmail);
|
||||
}
|
||||
}
|
||||
|
||||
// Se ainda não tem email, tenta obter do token novamente após refresh
|
||||
if (!userEmail) {
|
||||
try {
|
||||
await GlobalFunctions.getToken();
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
userEmail = GlobalFunctions.getUsuarioLogado().email;
|
||||
console.log("MeuPerfil: Email após refresh no loadUserProfile:", userEmail);
|
||||
} catch (error) {
|
||||
console.error("MeuPerfil: Erro ao fazer refresh no loadUserProfile:", error);
|
||||
}
|
||||
}
|
||||
|
||||
if (!userEmail) {
|
||||
console.error("MeuPerfil: Não foi possível obter email do usuário");
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Email do usuário não encontrado. Por favor, faça login novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
setLoading(false);
|
||||
// Não redireciona aqui, deixa o usuário ver o erro
|
||||
return;
|
||||
}
|
||||
|
||||
setEmail(userEmail);
|
||||
const response = await userProfileService.getUserProfile(userEmail);
|
||||
|
||||
if (response.success && response.id) {
|
||||
// Usuário existe
|
||||
setUserExists(true);
|
||||
setUserId(response.id);
|
||||
setNomeCompleto(response.nome);
|
||||
setWhatsapp(formatPhoneNumber(response.whatsapp));
|
||||
setReceberLembretes(response.followup);
|
||||
} else {
|
||||
// Usuário não existe
|
||||
setUserExists(false);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error("Erro ao carregar perfil:", error);
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
if (errorMessage.includes("não está cadastrado")) {
|
||||
setUserExists(false);
|
||||
} else {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: errorMessage || "Erro ao carregar perfil do usuário.",
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleWhatsappChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const formatted = formatPhoneNumber(e.target.value);
|
||||
setWhatsapp(formatted);
|
||||
};
|
||||
|
||||
const handleCreateWhatsappChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const formatted = formatPhoneNumber(e.target.value);
|
||||
setCreateWhatsapp(formatted);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!userExists || !userId) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Usuário não encontrado. Por favor, crie uma conta primeiro.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setSaving(true);
|
||||
const response = await userProfileService.updateUser(userId, {
|
||||
nome: nomeCompleto,
|
||||
whatsapp: whatsapp,
|
||||
followup: receberLembretes,
|
||||
});
|
||||
|
||||
if (response.success) {
|
||||
toast({
|
||||
title: "Perfil atualizado",
|
||||
description: "Suas informações foram salvas com sucesso.",
|
||||
});
|
||||
// Atualiza os dados locais
|
||||
setNomeCompleto(response.nome);
|
||||
setWhatsapp(formatPhoneNumber(response.whatsapp));
|
||||
setReceberLembretes(response.followup);
|
||||
} else {
|
||||
throw new Error(response.message || "Erro ao atualizar perfil");
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error("Erro ao salvar:", error);
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
toast({
|
||||
title: "Erro ao salvar",
|
||||
description: errorMessage || "Erro ao atualizar perfil. Tente novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateUser = async () => {
|
||||
if (!createNome.trim()) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "Nome é obrigatório.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!createWhatsapp.trim()) {
|
||||
toast({
|
||||
title: "Erro",
|
||||
description: "WhatsApp é obrigatório.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setCreating(true);
|
||||
const response = await userProfileService.createUser({
|
||||
nome: createNome.trim(),
|
||||
email: email,
|
||||
whatsapp: createWhatsapp,
|
||||
followup: createFollowup,
|
||||
});
|
||||
|
||||
if (response.success && response.id) {
|
||||
toast({
|
||||
title: "Conta criada",
|
||||
description: "Sua conta foi criada com sucesso!",
|
||||
});
|
||||
setUserExists(true);
|
||||
setUserId(response.id);
|
||||
setNomeCompleto(response.nome);
|
||||
setWhatsapp(formatPhoneNumber(response.whatsapp));
|
||||
setReceberLembretes(response.followup);
|
||||
setShowCreateModal(false);
|
||||
// Limpa os campos do modal
|
||||
setCreateNome("");
|
||||
setCreateWhatsapp("");
|
||||
setCreateFollowup(true);
|
||||
} else {
|
||||
throw new Error(response.message || "Erro ao criar conta");
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error("Erro ao criar usuário:", error);
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
toast({
|
||||
title: "Erro ao criar conta",
|
||||
description: errorMessage || "Erro ao criar conta. Tente novamente.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[400px]">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||
<p className="text-muted-foreground">Carregando perfil...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-foreground">Meu Perfil</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Gerencie suas informações pessoais
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{!userExists ? (
|
||||
<Card className="max-w-2xl">
|
||||
<CardContent className="py-12 text-center">
|
||||
<div className="space-y-4">
|
||||
<User className="w-16 h-16 mx-auto text-muted-foreground" />
|
||||
<div>
|
||||
<h3 className="text-xl font-semibold mb-2">
|
||||
Você ainda não possui uma conta
|
||||
</h3>
|
||||
<p className="text-muted-foreground mb-6">
|
||||
Crie sua conta para começar a usar o agente pessoal de IA
|
||||
</p>
|
||||
</div>
|
||||
<Button onClick={() => setShowCreateModal(true)} size="lg">
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Criar Conta
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card className="max-w-2xl">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<User className="w-5 h-5" />
|
||||
Informações Pessoais
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nomeCompleto" className="flex items-center gap-2">
|
||||
<User className="w-4 h-4" />
|
||||
Nome Completo
|
||||
</Label>
|
||||
<Input
|
||||
id="nomeCompleto"
|
||||
value={nomeCompleto}
|
||||
onChange={(e) => setNomeCompleto(e.target.value)}
|
||||
placeholder="Digite seu nome completo"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email" className="flex items-center gap-2">
|
||||
<Mail className="w-4 h-4" />
|
||||
E-mail
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={email}
|
||||
readOnly
|
||||
className="bg-muted cursor-not-allowed"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
O e-mail não pode ser alterado
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="whatsapp" className="flex items-center gap-2">
|
||||
<Phone className="w-4 h-4" />
|
||||
WhatsApp
|
||||
</Label>
|
||||
<Input
|
||||
id="whatsapp"
|
||||
value={whatsapp}
|
||||
onChange={handleWhatsappChange}
|
||||
placeholder="(00) 00000-0000"
|
||||
maxLength={15}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="receberLembretes" className="flex items-center gap-2 cursor-pointer">
|
||||
<Bell className="w-4 h-4" />
|
||||
Receber Follow up e lembretes
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Receba notificações sobre eventos e tarefas
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="receberLembretes"
|
||||
checked={receberLembretes}
|
||||
onCheckedChange={setReceberLembretes}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
className="w-full sm:w-auto"
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Salvando...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="w-4 h-4 mr-2" />
|
||||
Salvar Alterações
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Modal de Criação de Conta */}
|
||||
<Dialog open={showCreateModal} onOpenChange={setShowCreateModal}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Criar Conta</DialogTitle>
|
||||
<DialogDescription>
|
||||
Preencha os dados abaixo para criar sua conta no agente pessoal de IA
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="createNome">Nome Completo</Label>
|
||||
<Input
|
||||
id="createNome"
|
||||
value={createNome}
|
||||
onChange={(e) => setCreateNome(e.target.value)}
|
||||
placeholder="Digite seu nome completo"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="createEmail">E-mail</Label>
|
||||
<Input
|
||||
id="createEmail"
|
||||
type="email"
|
||||
value={email}
|
||||
readOnly
|
||||
className="bg-muted cursor-not-allowed"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
O e-mail é baseado na sua conta logada
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="createWhatsapp">WhatsApp</Label>
|
||||
<Input
|
||||
id="createWhatsapp"
|
||||
value={createWhatsapp}
|
||||
onChange={handleCreateWhatsappChange}
|
||||
placeholder="(00) 00000-0000"
|
||||
maxLength={15}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="createFollowup" className="cursor-pointer">
|
||||
Receber Follow up e lembretes
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Receba notificações sobre eventos e tarefas
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="createFollowup"
|
||||
checked={createFollowup}
|
||||
onCheckedChange={setCreateFollowup}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowCreateModal(false)}
|
||||
disabled={creating}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={handleCreateUser} disabled={creating}>
|
||||
{creating ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
Criando...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
Criar Conta
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MeuPerfil;
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { useEffect } from "react";
|
||||
|
||||
const NotFound = () => {
|
||||
const location = useLocation();
|
||||
|
||||
useEffect(() => {
|
||||
console.error("404 Error: User attempted to access non-existent route:", location.pathname);
|
||||
}, [location.pathname]);
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-muted">
|
||||
<div className="text-center">
|
||||
<h1 className="mb-4 text-4xl font-bold">404</h1>
|
||||
<p className="mb-4 text-xl text-muted-foreground">Oops! Page not found</p>
|
||||
<a href="/" className="text-primary underline hover:text-primary/90">
|
||||
Return to Home
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotFound;
|
||||
@@ -8,6 +8,8 @@ import { BotView } from "@/components/bots/BotView";
|
||||
import { BotChat } from "@/components/bots/BotChat";
|
||||
import { AgentView } from "@/components/agent/AgentView";
|
||||
import { Navigate, Route, Routes } from "react-router-dom";
|
||||
import React from "react";
|
||||
import { GlobalFunctions } from "@/GlobalFunctions";
|
||||
|
||||
interface Bot {
|
||||
id: string;
|
||||
@@ -28,6 +30,10 @@ const Index = () => {
|
||||
setActiveBotChat(null);
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
if(!GlobalFunctions.isUsuarioLogado())window.location.replace(import.meta.env.VITE_BASE_URL_HGTX_CORE);
|
||||
},[]);
|
||||
|
||||
return (<Routes>
|
||||
<Route path="" element={<Navigate to={`/404`} replace />} />
|
||||
<Route path="codex">
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
import { GlobalFunctions, TransferAreaProperties } from '@/GlobalFunctions';
|
||||
import { apiService } from './api';
|
||||
|
||||
/**
|
||||
* Interface para resposta do POST de parecer técnico
|
||||
*/
|
||||
export interface CreateOpinionResponse {
|
||||
success: boolean;
|
||||
id?: string;
|
||||
file_url?: string;
|
||||
file_url_melhoria?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para requisição de criação de parecer
|
||||
*/
|
||||
export interface CreateOpinionRequest {
|
||||
titulo: string;
|
||||
categoria: string;
|
||||
instrucoes: string;
|
||||
userEmail?: string;
|
||||
estabelecimentoId?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Status do parecer
|
||||
*/
|
||||
export type OpinionStatus = 'processando' | 'concluido' | 'erro';
|
||||
|
||||
/**
|
||||
* Interface para um parecer retornado pela API
|
||||
*/
|
||||
export interface OpinionRecord {
|
||||
id: string;
|
||||
estabelecimento_id: number;
|
||||
user_email: string;
|
||||
titulo: string;
|
||||
categoria: string;
|
||||
instrucoes: string;
|
||||
file_url: string;
|
||||
created_at: string;
|
||||
file_url_melhoria: string;
|
||||
status?: OpinionStatus; // Status do processamento do parecer (pode vir da API ou ser local)
|
||||
isLocalPending?: boolean; // Flag para indicar se é um registro local temporário
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para parâmetros de paginação e busca
|
||||
*/
|
||||
export interface GetOpinionsParams {
|
||||
page?: number;
|
||||
per_page?: number;
|
||||
search?: string;
|
||||
userEmail?: string;
|
||||
estabelecimentoId?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para resposta do GET de pareceres
|
||||
*/
|
||||
export interface GetOpinionsResponse {
|
||||
data: OpinionRecord[];
|
||||
total: number;
|
||||
page: number;
|
||||
per_page: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serviço para gerenciamento de pareceres jurídicos
|
||||
*/
|
||||
class AgentService {
|
||||
private readonly CREATE_OPINION_ENDPOINT = '/webhook/codex/gepam/parecer-tecnico';
|
||||
private readonly GET_OPINIONS_ENDPOINT = '/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/get_parecer';
|
||||
|
||||
/**
|
||||
* Cria um novo parecer técnico
|
||||
*
|
||||
* @param request - Dados do parecer
|
||||
* @returns Promise com a resposta da API
|
||||
*/
|
||||
async createOpinion(request: CreateOpinionRequest): Promise<CreateOpinionResponse> {
|
||||
const {
|
||||
titulo,
|
||||
categoria,
|
||||
instrucoes,
|
||||
userEmail,
|
||||
estabelecimentoId
|
||||
} = request;
|
||||
|
||||
// Usa valores do GlobalFunctions se não forem fornecidos
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
const estabId = estabelecimentoId || GlobalFunctions.getTransferProperty(TransferAreaProperties.EstabelecimentoCodigo);
|
||||
|
||||
// Validações
|
||||
if (!titulo || titulo.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Título do parecer é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
if (!instrucoes || instrucoes.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Instruções são obrigatórias',
|
||||
};
|
||||
}
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
if (!estabId) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID do estabelecimento não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
// Log para debug
|
||||
console.log('Criando parecer:', {
|
||||
titulo,
|
||||
categoria,
|
||||
instrucoesLength: instrucoes.length,
|
||||
userEmail: email,
|
||||
estabelecimentoId: estabId,
|
||||
});
|
||||
|
||||
try {
|
||||
// Faz a requisição usando o serviço de API com timeout de 5 minutos
|
||||
const response = await apiService.post<CreateOpinionResponse>(
|
||||
this.CREATE_OPINION_ENDPOINT,
|
||||
{
|
||||
user_email: email,
|
||||
estabelecimento_id: estabId,
|
||||
titulo: titulo.trim(),
|
||||
categoria: categoria.trim(),
|
||||
instrucoes: instrucoes.trim(),
|
||||
},
|
||||
{
|
||||
timeout: 600000, // 5 minutos para geração de parecer (processo demorado)
|
||||
}
|
||||
);
|
||||
|
||||
console.log('Resposta da API (criar parecer):', response.data);
|
||||
|
||||
return response.data;
|
||||
} catch (error: any) {
|
||||
// Trata erros específicos
|
||||
console.error('Erro ao criar parecer:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao criar parecer',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Busca todos os pareceres do usuário com paginação e busca
|
||||
*
|
||||
* @param params - Parâmetros de paginação e busca
|
||||
* @returns Promise com array de pareceres
|
||||
*/
|
||||
async getOpinions(params?: GetOpinionsParams): Promise<OpinionRecord[]> {
|
||||
const {
|
||||
page = 1,
|
||||
per_page = 10,
|
||||
search = '',
|
||||
userEmail,
|
||||
estabelecimentoId
|
||||
} = params || {};
|
||||
|
||||
// Usa valores do GlobalFunctions se não forem fornecidos
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
const estabId = estabelecimentoId || GlobalFunctions.getTransferProperty(TransferAreaProperties.EstabelecimentoCodigo);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
if (!estabId) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID do estabelecimento não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Buscando pareceres:', {
|
||||
userEmail: email,
|
||||
estabelecimentoId: estabId,
|
||||
page,
|
||||
per_page,
|
||||
search,
|
||||
});
|
||||
|
||||
try {
|
||||
// Constrói a URL com parâmetros de query
|
||||
const url = `${this.GET_OPINIONS_ENDPOINT}/${email}/${estabId}`;
|
||||
|
||||
const response = await apiService.get<OpinionRecord[]>(url, {
|
||||
params: {
|
||||
page,
|
||||
per_page,
|
||||
search,
|
||||
},
|
||||
});
|
||||
|
||||
console.log('Resposta da API (buscar pareceres):', response.data);
|
||||
|
||||
// A API retorna diretamente o array de pareceres
|
||||
// Garante que sempre retorna um array
|
||||
if (Array.isArray(response.data)) {
|
||||
return response.data;
|
||||
} else if (response.data && typeof response.data === 'object') {
|
||||
// Se a resposta for um objeto, tenta encontrar o array dentro dele
|
||||
console.warn('API retornou objeto em vez de array:', response.data);
|
||||
|
||||
if (Array.isArray((response.data as any).data)) {
|
||||
return (response.data as any).data;
|
||||
} else if (Array.isArray((response.data as any).opinions)) {
|
||||
return (response.data as any).opinions;
|
||||
}
|
||||
}
|
||||
|
||||
// Se não conseguir extrair array, retorna vazio
|
||||
console.warn('Não foi possível extrair array de pareceres da resposta');
|
||||
return [];
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao buscar pareceres:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao buscar pareceres',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Faz download de um arquivo de parecer
|
||||
*
|
||||
* @param fileUrl - URL do arquivo a ser baixado
|
||||
* @param fileName - Nome do arquivo para download
|
||||
*/
|
||||
async downloadOpinion(fileUrl: string, fileName: string): Promise<void> {
|
||||
if (!fileUrl) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'URL do arquivo não fornecida',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('Iniciando download:', { fileUrl, fileName });
|
||||
|
||||
// Tenta primeiro fazer o download via fetch (funciona se CORS estiver configurado)
|
||||
try {
|
||||
const response = await fetch(fileUrl, {
|
||||
method: 'GET',
|
||||
mode: 'cors',
|
||||
cache: 'no-cache',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Erro HTTP: ${response.status}`);
|
||||
}
|
||||
|
||||
// Converte a resposta em blob
|
||||
const blob = await response.blob();
|
||||
|
||||
// Cria uma URL temporária para o blob
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
|
||||
// Cria um elemento <a> temporário para forçar o download
|
||||
const link = document.createElement('a');
|
||||
link.href = blobUrl;
|
||||
link.download = fileName;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
|
||||
// Remove o elemento e libera a URL temporária
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
|
||||
console.log('Download via fetch concluído:', { fileUrl, fileName });
|
||||
return;
|
||||
} catch (fetchError: any) {
|
||||
console.warn('Erro no download via fetch, tentando método alternativo:', fetchError.message);
|
||||
|
||||
// Se falhar (erro de CORS), usa o método alternativo de abrir em nova aba
|
||||
// Isso permite que o navegador force o download mesmo com restrições de CORS
|
||||
const link = document.createElement('a');
|
||||
link.href = fileUrl;
|
||||
link.download = fileName;
|
||||
link.target = '_blank';
|
||||
link.rel = 'noopener noreferrer';
|
||||
|
||||
// Para S3, podemos tentar adicionar parâmetros que forçam o download
|
||||
const url = new URL(fileUrl);
|
||||
url.searchParams.set('response-content-disposition', `attachment; filename="${encodeURIComponent(fileName)}"`);
|
||||
link.href = url.toString();
|
||||
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
|
||||
console.log('Download via link direto iniciado:', { fileUrl, fileName });
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao fazer download:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao fazer download do arquivo. Verifique se a URL está acessível.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exclui um parecer técnico
|
||||
*
|
||||
* @param opinionId - ID do parecer a ser excluído
|
||||
* @param userEmail - Email do usuário (opcional, usa GlobalFunctions se não fornecido)
|
||||
* @returns Promise com a resposta da API
|
||||
*/
|
||||
async deleteOpinion(opinionId: string, userEmail?: string): Promise<{ success: boolean }> {
|
||||
// Usa valores do GlobalFunctions se não forem fornecidos
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!opinionId) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID do parecer não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Excluindo parecer:', {
|
||||
opinionId,
|
||||
userEmail: email,
|
||||
});
|
||||
|
||||
try {
|
||||
// Constrói a URL com o user_email e id
|
||||
const url = `/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/delete_parecer/${email}/${opinionId}`;
|
||||
|
||||
const response = await apiService.delete<{ success: boolean }[]>(url);
|
||||
|
||||
console.log('Resposta da API (excluir parecer):', response.data);
|
||||
|
||||
// A API retorna um array com { success: true }
|
||||
if (Array.isArray(response.data) && response.data.length > 0) {
|
||||
return response.data[0];
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao excluir parecer:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao excluir parecer',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exporta instância única (Singleton)
|
||||
export const agentService = new AgentService();
|
||||
@@ -0,0 +1,435 @@
|
||||
/**
|
||||
* Serviço para integração com API do Asana
|
||||
*/
|
||||
|
||||
/**
|
||||
* Interface para workspace do Asana (resposta da API)
|
||||
*/
|
||||
export interface AsanaWorkspaceResponse {
|
||||
gid: string;
|
||||
resource_type: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para resposta da API de workspaces
|
||||
*/
|
||||
export interface AsanaWorkspacesResponse {
|
||||
data: AsanaWorkspaceResponse[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para workspace formatado (usado no componente)
|
||||
*/
|
||||
export interface AsanaWorkspace {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para usuário do Asana (resposta da API)
|
||||
*/
|
||||
export interface AsanaUserResponse {
|
||||
gid: string;
|
||||
name: string;
|
||||
resource_type: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para resposta da API de usuários
|
||||
*/
|
||||
export interface AsanaUsersResponse {
|
||||
data: AsanaUserResponse[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para usuário formatado (usado no componente)
|
||||
*/
|
||||
export interface AsanaUser {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para resposta da API de integração do Asana
|
||||
*/
|
||||
export interface AsanaIntegrationResponse {
|
||||
success: boolean;
|
||||
integracao_id?: string;
|
||||
id?: string;
|
||||
api_key?: string;
|
||||
workspace_gid?: string;
|
||||
workspace_nome?: string;
|
||||
usuario_asana_gid?: string;
|
||||
usuario_asana_nome?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para request de criação/atualização de integração
|
||||
*/
|
||||
export interface AsanaIntegrationRequest {
|
||||
user_id?: string;
|
||||
api_key: string;
|
||||
workspace_gid: string;
|
||||
workspace_nome: string;
|
||||
usuario_asana_gid: string;
|
||||
usuario_asana_nome: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serviço para integração com Asana
|
||||
*/
|
||||
class AsanaService {
|
||||
private readonly BASE_URL = 'https://app.asana.com/api/1.0';
|
||||
private readonly INTEGRATION_BASE_URL = 'https://prod-hgtx-intelligence-n8n.hgtx.com.br';
|
||||
private readonly INTEGRATION_WEBHOOK_ID = 'c898beff-84cb-44df-a69c-6eff27ccd7aa';
|
||||
|
||||
/**
|
||||
* Lista os workspaces do Asana usando o token fornecido
|
||||
*
|
||||
* @param token - Token de acesso do Asana
|
||||
* @returns Promise com a lista de workspaces formatados
|
||||
*/
|
||||
async getWorkspaces(token: string): Promise<AsanaWorkspace[]> {
|
||||
if (!token || token.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Token do Asana é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'accept': 'application/json',
|
||||
'authorization': `Bearer ${token.trim()}`,
|
||||
};
|
||||
|
||||
const response = await axios.get<AsanaWorkspacesResponse>(
|
||||
`${this.BASE_URL}/workspaces`,
|
||||
{ headers }
|
||||
);
|
||||
|
||||
// Converte a resposta da API para o formato esperado pelo componente
|
||||
// A API retorna gid, mas o componente espera id
|
||||
return response.data.data.map((workspace) => ({
|
||||
id: workspace.gid,
|
||||
name: workspace.name,
|
||||
}));
|
||||
} catch (error: unknown) {
|
||||
console.error('Erro ao buscar workspaces do Asana:', error);
|
||||
|
||||
// Retorna o erro da API se existir
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const axiosError = error as { response?: { data?: any; status?: number } };
|
||||
|
||||
if (axiosError.response?.status === 401) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Token inválido ou expirado. Verifique sua chave de API.',
|
||||
};
|
||||
}
|
||||
|
||||
if (axiosError.response?.data) {
|
||||
throw {
|
||||
success: false,
|
||||
message: axiosError.response.data.message || 'Erro ao buscar workspaces do Asana',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Erro ao buscar workspaces do Asana',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lista os usuários de um workspace do Asana
|
||||
*
|
||||
* @param token - Token de acesso do Asana
|
||||
* @param workspaceId - ID do workspace (gid)
|
||||
* @returns Promise com a lista de usuários formatados
|
||||
*/
|
||||
async getUsers(token: string, workspaceId: string): Promise<AsanaUser[]> {
|
||||
if (!token || token.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Token do Asana é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
if (!workspaceId || workspaceId.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID do workspace é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'accept': 'application/json',
|
||||
'authorization': `Bearer ${token.trim()}`,
|
||||
};
|
||||
|
||||
const response = await axios.get<AsanaUsersResponse>(
|
||||
`${this.BASE_URL}/users?workspace=${workspaceId}`,
|
||||
{ headers }
|
||||
);
|
||||
|
||||
// Converte a resposta da API para o formato esperado pelo componente
|
||||
// A API retorna gid, mas o componente espera id
|
||||
return response.data.data.map((user) => ({
|
||||
id: user.gid,
|
||||
name: user.name,
|
||||
}));
|
||||
} catch (error: unknown) {
|
||||
console.error('Erro ao buscar usuários do Asana:', error);
|
||||
|
||||
// Retorna o erro da API se existir
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const axiosError = error as { response?: { data?: any; status?: number } };
|
||||
|
||||
if (axiosError.response?.status === 401) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Token inválido ou expirado. Verifique sua chave de API.',
|
||||
};
|
||||
}
|
||||
|
||||
if (axiosError.response?.data) {
|
||||
throw {
|
||||
success: false,
|
||||
message: axiosError.response.data.message || 'Erro ao buscar usuários do Asana',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Erro ao buscar usuários do Asana',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtém os detalhes da integração do Asana do usuário
|
||||
*
|
||||
* @param userId - ID do usuário
|
||||
* @returns Promise com os detalhes da integração ou null se não houver
|
||||
*/
|
||||
async getIntegration(userId: string): Promise<AsanaIntegrationResponse | null> {
|
||||
if (!userId || userId.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID do usuário é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
const { GlobalFunctions } = await import('@/GlobalFunctions');
|
||||
|
||||
// Obtém o token JWT para autenticação
|
||||
const token = await GlobalFunctions.getToken();
|
||||
const apiKey = import.meta.env.VITE_API_KEY || '';
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'accept': 'application/json',
|
||||
};
|
||||
|
||||
// Adiciona API key (obrigatória)
|
||||
if (apiKey) {
|
||||
headers['apikey'] = apiKey;
|
||||
}
|
||||
|
||||
// Adiciona token JWT se disponível
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// Em desenvolvimento, usa proxy do Vite para evitar CORS
|
||||
const baseUrl = import.meta.env.DEV
|
||||
? '/api/intelligence'
|
||||
: this.INTEGRATION_BASE_URL;
|
||||
|
||||
const response = await axios.get<AsanaIntegrationResponse>(
|
||||
`${baseUrl}/webhook/${this.INTEGRATION_WEBHOOK_ID}/codex/agente-pessoal/integracoes/asana/${userId}`,
|
||||
{ headers }
|
||||
);
|
||||
|
||||
// Se success é false, retorna null (não tem integração)
|
||||
if (!response.data.success) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return response.data;
|
||||
} catch (error: unknown) {
|
||||
console.error('Erro ao buscar integração do Asana:', error);
|
||||
|
||||
// Se o erro for 404 ou similar, significa que não tem integração cadastrada
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const axiosError = error as { response?: { status?: number } };
|
||||
if (axiosError.response?.status === 404) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Para outros erros, retorna null silenciosamente (não quebra a aplicação)
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cria uma nova integração do Asana
|
||||
*
|
||||
* @param request - Dados da integração a ser criada
|
||||
* @returns Promise com a resposta da criação
|
||||
*/
|
||||
async createIntegration(request: AsanaIntegrationRequest): Promise<AsanaIntegrationResponse> {
|
||||
if (!request.user_id || !request.api_key || !request.workspace_gid || !request.usuario_asana_gid) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Dados incompletos para criar integração',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
const { GlobalFunctions } = await import('@/GlobalFunctions');
|
||||
|
||||
// Obtém o token JWT para autenticação
|
||||
const token = await GlobalFunctions.getToken();
|
||||
const apiKey = import.meta.env.VITE_API_KEY || '';
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'accept': 'application/json',
|
||||
};
|
||||
|
||||
// Adiciona API key (obrigatória)
|
||||
if (apiKey) {
|
||||
headers['apikey'] = apiKey;
|
||||
}
|
||||
|
||||
// Adiciona token JWT se disponível
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// Em desenvolvimento, usa proxy do Vite para evitar CORS
|
||||
const baseUrl = import.meta.env.DEV
|
||||
? '/api/intelligence'
|
||||
: this.INTEGRATION_BASE_URL;
|
||||
|
||||
const response = await axios.post<AsanaIntegrationResponse>(
|
||||
`${baseUrl}/webhook/codex/agente-pessoal/integracoes/asana`,
|
||||
request,
|
||||
{ headers }
|
||||
);
|
||||
|
||||
return response.data;
|
||||
} catch (error: unknown) {
|
||||
console.error('Erro ao criar integração do Asana:', error);
|
||||
|
||||
// Retorna o erro da API se existir
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const axiosError = error as { response?: { data?: any; status?: number } };
|
||||
|
||||
if (axiosError.response?.data) {
|
||||
const errorData = axiosError.response.data;
|
||||
throw {
|
||||
success: false,
|
||||
message: errorData.message || 'Erro ao criar integração do Asana',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Erro ao criar integração do Asana',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atualiza uma integração existente do Asana
|
||||
*
|
||||
* @param integracaoId - ID da integração a ser atualizada
|
||||
* @param request - Dados da integração a ser atualizada
|
||||
* @returns Promise com a resposta da atualização
|
||||
*/
|
||||
async updateIntegration(integracaoId: string, request: Omit<AsanaIntegrationRequest, 'user_id'>): Promise<AsanaIntegrationResponse> {
|
||||
if (!integracaoId || !request.api_key || !request.workspace_gid || !request.usuario_asana_gid) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Dados incompletos para atualizar integração',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
const { GlobalFunctions } = await import('@/GlobalFunctions');
|
||||
|
||||
// Obtém o token JWT para autenticação
|
||||
const token = await GlobalFunctions.getToken();
|
||||
const apiKey = import.meta.env.VITE_API_KEY || '';
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'accept': 'application/json',
|
||||
};
|
||||
|
||||
// Adiciona API key (obrigatória)
|
||||
if (apiKey) {
|
||||
headers['apikey'] = apiKey;
|
||||
}
|
||||
|
||||
// Adiciona token JWT se disponível
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// Em desenvolvimento, usa proxy do Vite para evitar CORS
|
||||
const baseUrl = import.meta.env.DEV
|
||||
? '/api/intelligence'
|
||||
: this.INTEGRATION_BASE_URL;
|
||||
|
||||
const response = await axios.put<AsanaIntegrationResponse>(
|
||||
`${baseUrl}/webhook/${this.INTEGRATION_WEBHOOK_ID}/codex/agente-pessoal/integracoes/asana/${integracaoId}`,
|
||||
request,
|
||||
{ headers }
|
||||
);
|
||||
|
||||
return response.data;
|
||||
} catch (error: unknown) {
|
||||
console.error('Erro ao atualizar integração do Asana:', error);
|
||||
|
||||
// Retorna o erro da API se existir
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const axiosError = error as { response?: { data?: any; status?: number } };
|
||||
|
||||
if (axiosError.response?.data) {
|
||||
const errorData = axiosError.response.data;
|
||||
throw {
|
||||
success: false,
|
||||
message: errorData.message || 'Erro ao atualizar integração do Asana',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Erro ao atualizar integração do Asana',
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exporta instância única (Singleton)
|
||||
export const asanaService = new AsanaService();
|
||||
@@ -16,6 +16,23 @@ export interface AudioGenerationResponse {
|
||||
message: string; // Texto que foi convertido em áudio
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para um áudio armazenado no banco de dados
|
||||
*/
|
||||
export interface AudioRecord {
|
||||
id: string;
|
||||
user_email: string;
|
||||
estabelecimento_id: number;
|
||||
input_text: string;
|
||||
model: string;
|
||||
voice: VoiceType;
|
||||
audio_url: string;
|
||||
duration_seconds: number | null;
|
||||
file_size: number;
|
||||
cost_usd: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para os dados necessários para geração de áudio
|
||||
*/
|
||||
@@ -73,6 +90,8 @@ export const VOICE_OPTIONS = {
|
||||
*/
|
||||
class AudioGenerationService {
|
||||
private readonly AUDIO_GENERATION_ENDPOINT = '/webhook/codex/gerar_audio';
|
||||
private readonly GET_AUDIOS_ENDPOINT = '/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/get_gerar_audios';
|
||||
private readonly DELETE_AUDIO_ENDPOINT = '/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/delete_gerar_audio';
|
||||
|
||||
/**
|
||||
* Gera um arquivo de áudio a partir de texto
|
||||
@@ -192,6 +211,149 @@ class AudioGenerationService {
|
||||
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Lista áudios do banco de dados com paginação
|
||||
*
|
||||
* @param userEmail - Email do usuário
|
||||
* @param page - Número da página (padrão: 1)
|
||||
* @param perPage - Quantidade de itens por página (padrão: 10)
|
||||
* @returns Promise com o array de áudios
|
||||
*/
|
||||
async getAudios(
|
||||
userEmail?: string,
|
||||
page: number = 1,
|
||||
perPage: number = 10
|
||||
): Promise<AudioRecord[]> {
|
||||
// Usa valores do GlobalFunctions se não forem fornecidos
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Buscando áudios:', {
|
||||
userEmail: email,
|
||||
page,
|
||||
perPage,
|
||||
});
|
||||
|
||||
try {
|
||||
// Faz a requisição GET com parâmetros na URL e query
|
||||
const response = await apiService.get<AudioRecord[]>(
|
||||
`${this.GET_AUDIOS_ENDPOINT}/${email}`,
|
||||
{
|
||||
params: {
|
||||
page: page.toString(),
|
||||
per_page: perPage.toString(),
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
console.log('Resposta completa da API:', response);
|
||||
console.log('response.data:', response.data);
|
||||
console.log('É array?:', Array.isArray(response.data));
|
||||
|
||||
// A API retorna diretamente o array de áudios
|
||||
// Garante que sempre retorna um array
|
||||
if (Array.isArray(response.data)) {
|
||||
return response.data;
|
||||
} else if (response.data && typeof response.data === 'object') {
|
||||
// Se a resposta for um objeto com uma propriedade 'audios' ou similar
|
||||
console.warn('API retornou objeto em vez de array:', response.data);
|
||||
|
||||
// Tenta encontrar o array dentro do objeto
|
||||
if (Array.isArray((response.data as any).audios)) {
|
||||
return (response.data as any).audios;
|
||||
} else if (Array.isArray((response.data as any).data)) {
|
||||
return (response.data as any).data;
|
||||
}
|
||||
}
|
||||
|
||||
// Se não conseguir extrair array, retorna vazio
|
||||
console.warn('Não foi possível extrair array de áudios da resposta');
|
||||
return [];
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao buscar áudios:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao buscar áudios',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleta um áudio do banco de dados
|
||||
*
|
||||
* @param audioId - ID do áudio a ser deletado
|
||||
* @param userEmail - Email do usuário (opcional)
|
||||
* @returns Promise com sucesso ou erro
|
||||
*/
|
||||
async deleteAudio(audioId: string, userEmail?: string): Promise<{ success: boolean; message?: string }> {
|
||||
// Usa valores do GlobalFunctions se não forem fornecidos
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
if (!audioId) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID do áudio não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Deletando áudio:', {
|
||||
audioId,
|
||||
userEmail: email,
|
||||
});
|
||||
|
||||
try {
|
||||
// Faz a requisição DELETE com parâmetros na URL
|
||||
const response = await apiService.delete<{ success: boolean; message?: string } | Array<{ success: boolean; message?: string }>>(
|
||||
`${this.DELETE_AUDIO_ENDPOINT}/${email}/${audioId}`
|
||||
);
|
||||
|
||||
console.log('Resposta completa do DELETE:', response);
|
||||
console.log('response.data:', response.data);
|
||||
|
||||
// A API retorna um array com um objeto: [{"success":true}]
|
||||
let result: { success: boolean; message?: string };
|
||||
|
||||
if (Array.isArray(response.data)) {
|
||||
// Se for array, pega o primeiro elemento
|
||||
result = response.data[0];
|
||||
console.log('API retornou array, usando primeiro elemento:', result);
|
||||
} else {
|
||||
// Se for objeto direto
|
||||
result = response.data;
|
||||
console.log('API retornou objeto direto:', result);
|
||||
}
|
||||
|
||||
// Garante que tem a estrutura mínima
|
||||
return {
|
||||
success: result.success ?? true,
|
||||
message: result.message || 'Áudio deletado com sucesso',
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao deletar áudio:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao deletar áudio',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exporta instância única (Singleton)
|
||||
|
||||
+510
-4
@@ -59,6 +59,56 @@ export interface StoredFolder {
|
||||
chatIds: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para Folder no banco de dados
|
||||
*/
|
||||
export interface FolderRecord {
|
||||
id: string;
|
||||
name: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para Chat no banco de dados
|
||||
*/
|
||||
export interface ChatRecord {
|
||||
id: string;
|
||||
title: string;
|
||||
model_id: number;
|
||||
folder_id: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
personalidade: string; // Personalidade/prompt do sistema salvo no banco
|
||||
estabelecimento_id: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para resposta do GET de chats e folders
|
||||
*/
|
||||
export interface GetChatsAndFoldersResponse {
|
||||
chats: ChatRecord[];
|
||||
folders: FolderRecord[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para Message no banco de dados
|
||||
*/
|
||||
export interface MessageRecord {
|
||||
id: string;
|
||||
chat_id: string;
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
model_id: number;
|
||||
model_name?: string; // Nome do modelo retornado pela API
|
||||
has_attachments: number;
|
||||
input_tokens: number;
|
||||
output_tokens: number;
|
||||
total_tokens: number;
|
||||
cost_usd: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serviço de chat com IA
|
||||
*/
|
||||
@@ -67,6 +117,14 @@ class ChatService {
|
||||
private readonly STORAGE_KEY_CHATS = 'hgtx_chats';
|
||||
private readonly STORAGE_KEY_FOLDERS = 'hgtx_folders';
|
||||
|
||||
// Endpoints para folders e chats
|
||||
private readonly POST_FOLDER_ENDPOINT = '/webhook/codex/post_folders';
|
||||
private readonly GET_CHATS_FOLDERS_ENDPOINT = '/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/get_chat_folders';
|
||||
private readonly PUT_CHAT_IN_FOLDER_ENDPOINT = '/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/insert_chat_in_folder';
|
||||
private readonly DELETE_FOLDER_ENDPOINT = '/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/delete_chat_folder';
|
||||
private readonly DELETE_CHAT_ENDPOINT = '/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/delete_chat_messages';
|
||||
private readonly GET_CHAT_MESSAGES_ENDPOINT = '/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/get_chat_messages';
|
||||
|
||||
// Formatos de arquivo permitidos (atualmente)
|
||||
private readonly ALLOWED_FILE_TYPES = {
|
||||
// Formatos ativos
|
||||
@@ -280,11 +338,11 @@ class ChatService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleta um chat
|
||||
* Deleta um chat do localStorage
|
||||
*
|
||||
* @param chatId - ID do chat a ser deletado
|
||||
*/
|
||||
deleteChat(chatId: string): void {
|
||||
deleteChatLocal(chatId: string): void {
|
||||
try {
|
||||
const chats = this.getAllChats();
|
||||
const filteredChats = chats.filter(c => c.id !== chatId);
|
||||
@@ -342,11 +400,11 @@ class ChatService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleta uma pasta
|
||||
* Deleta uma pasta do localStorage
|
||||
*
|
||||
* @param folderId - ID da pasta a ser deletada
|
||||
*/
|
||||
deleteFolder(folderId: string): void {
|
||||
deleteFolderLocal(folderId: string): void {
|
||||
try {
|
||||
const folders = this.getAllFolders();
|
||||
const filteredFolders = folders.filter(f => f.id !== folderId);
|
||||
@@ -476,6 +534,454 @@ class ChatService {
|
||||
getMaxAttachments(): number {
|
||||
return this.MAX_ATTACHMENTS;
|
||||
}
|
||||
|
||||
// ===== MÉTODOS DE INTEGRAÇÃO COM BANCO DE DADOS =====
|
||||
|
||||
/**
|
||||
* Cria uma nova pasta no banco de dados
|
||||
*
|
||||
* @param name - Nome da pasta
|
||||
* @param userEmail - Email do usuário (opcional)
|
||||
* @returns Promise com sucesso ou erro
|
||||
*/
|
||||
async createFolder(name: string, userEmail?: string): Promise<{ success: boolean; folder?: FolderRecord }> {
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
if (!name || name.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Nome da pasta não pode estar vazio',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Criando pasta:', {
|
||||
name,
|
||||
userEmail: email,
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await apiService.post<Array<{ success: boolean; user_email?: string; name?: string }>>(
|
||||
this.POST_FOLDER_ENDPOINT,
|
||||
{
|
||||
user_email: email,
|
||||
name: name.trim(),
|
||||
}
|
||||
);
|
||||
|
||||
console.log('Resposta completa do POST:', response);
|
||||
console.log('response.data:', response.data);
|
||||
|
||||
// A API retorna um array com um objeto: [{"success":true, ...}]
|
||||
let result: { success: boolean; user_email?: string; name?: string };
|
||||
|
||||
if (Array.isArray(response.data)) {
|
||||
result = response.data[0];
|
||||
console.log('API retornou array, usando primeiro elemento:', result);
|
||||
} else {
|
||||
result = response.data as any;
|
||||
console.log('API retornou objeto direto:', result);
|
||||
}
|
||||
|
||||
return {
|
||||
success: result.success ?? true,
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao criar pasta:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao criar pasta',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renomeia uma pasta existente
|
||||
*
|
||||
* @param folderId - ID da pasta a ser renomeada
|
||||
* @param newName - Novo nome da pasta
|
||||
* @param userEmail - Email do usuário (opcional)
|
||||
* @returns Promise com o resultado da operação
|
||||
*/
|
||||
async renameFolder(folderId: string, newName: string, userEmail?: string): Promise<{ success: boolean; folder?: FolderRecord }> {
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
if (!folderId || folderId.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID da pasta não pode estar vazio',
|
||||
};
|
||||
}
|
||||
|
||||
if (!newName || newName.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Nome da pasta não pode estar vazio',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Renomeando pasta:', {
|
||||
folderId,
|
||||
newName,
|
||||
userEmail: email,
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await apiService.put<Array<{ success: boolean; user_email?: string; name?: string; id?: string }>>(
|
||||
this.POST_FOLDER_ENDPOINT,
|
||||
{
|
||||
id: folderId,
|
||||
user_email: email,
|
||||
name: newName.trim(),
|
||||
}
|
||||
);
|
||||
|
||||
console.log('Resposta completa do PUT (renomear pasta):', response);
|
||||
console.log('response.data:', response.data);
|
||||
|
||||
// A API retorna um array com um objeto: [{"success":true, "user_email": "...", "name": "...", "id": "..."}]
|
||||
let result: { success: boolean; user_email?: string; name?: string; id?: string };
|
||||
|
||||
if (Array.isArray(response.data)) {
|
||||
result = response.data[0];
|
||||
console.log('API retornou array, usando primeiro elemento:', result);
|
||||
} else {
|
||||
result = response.data as any;
|
||||
console.log('API retornou objeto direto:', result);
|
||||
}
|
||||
|
||||
return {
|
||||
success: result.success ?? true,
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao renomear pasta:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao renomear pasta',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Busca todos os chats e pastas do usuário
|
||||
*
|
||||
* @param userEmail - Email do usuário (opcional)
|
||||
* @returns Promise com chats e folders
|
||||
*/
|
||||
async getChatsAndFolders(userEmail?: string): Promise<GetChatsAndFoldersResponse> {
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Buscando chats e pastas:', {
|
||||
userEmail: email,
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await apiService.get<Array<{ result: GetChatsAndFoldersResponse }>>(
|
||||
`${this.GET_CHATS_FOLDERS_ENDPOINT}/${email}`
|
||||
);
|
||||
|
||||
console.log('Resposta completa da API:', response);
|
||||
console.log('response.data:', response.data);
|
||||
|
||||
// A API retorna um array com um objeto "result": [{"result": {"chats": [...], "folders": [...]}}]
|
||||
let result: GetChatsAndFoldersResponse;
|
||||
|
||||
if (Array.isArray(response.data) && response.data.length > 0) {
|
||||
result = response.data[0].result;
|
||||
console.log('API retornou array com result:', result);
|
||||
} else if ((response.data as any).result) {
|
||||
result = (response.data as any).result;
|
||||
console.log('API retornou objeto com result:', result);
|
||||
} else {
|
||||
// Fallback: retorna vazio
|
||||
console.warn('Estrutura inesperada da resposta');
|
||||
result = { chats: [], folders: [] };
|
||||
}
|
||||
|
||||
// Garante que chats e folders são arrays
|
||||
return {
|
||||
chats: Array.isArray(result.chats) ? result.chats : [],
|
||||
folders: Array.isArray(result.folders) ? result.folders : [],
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao buscar chats e pastas:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao buscar chats e pastas',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Move um chat para dentro de uma pasta
|
||||
*
|
||||
* @param chatId - ID do chat
|
||||
* @param folderId - ID da pasta
|
||||
* @returns Promise com sucesso ou erro
|
||||
*/
|
||||
async moveChatToFolder(chatId: string, folderId: string): Promise<{ success: boolean }> {
|
||||
if (!chatId || !folderId) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Chat ID e Folder ID são obrigatórios',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Movendo chat para pasta:', {
|
||||
chatId,
|
||||
folderId,
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await apiService.put<Array<{ success: boolean }>>(
|
||||
`${this.PUT_CHAT_IN_FOLDER_ENDPOINT}/${folderId}/${chatId}`
|
||||
);
|
||||
|
||||
console.log('Resposta completa do PUT:', response);
|
||||
console.log('response.data:', response.data);
|
||||
|
||||
// A API retorna um array com um objeto: [{"success":true}]
|
||||
let result: { success: boolean };
|
||||
|
||||
if (Array.isArray(response.data)) {
|
||||
result = response.data[0];
|
||||
console.log('API retornou array, usando primeiro elemento:', result);
|
||||
} else {
|
||||
result = response.data;
|
||||
console.log('API retornou objeto direto:', result);
|
||||
}
|
||||
|
||||
return {
|
||||
success: result.success ?? true,
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao mover chat para pasta:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao mover chat para pasta',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleta uma pasta do banco de dados
|
||||
*
|
||||
* @param folderId - ID da pasta
|
||||
* @param userEmail - Email do usuário (opcional)
|
||||
* @returns Promise com sucesso ou erro
|
||||
*/
|
||||
async deleteFolder(folderId: string, userEmail?: string): Promise<{ success: boolean }> {
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
if (!folderId) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID da pasta não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Deletando pasta:', {
|
||||
folderId,
|
||||
userEmail: email,
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await apiService.delete<Array<{ success: boolean }>>(
|
||||
`${this.DELETE_FOLDER_ENDPOINT}/${email}/${folderId}`
|
||||
);
|
||||
|
||||
console.log('Resposta completa do DELETE:', response);
|
||||
console.log('response.data:', response.data);
|
||||
|
||||
// A API retorna um array com um objeto: [{"success":true}]
|
||||
let result: { success: boolean };
|
||||
|
||||
if (Array.isArray(response.data)) {
|
||||
result = response.data[0];
|
||||
console.log('API retornou array, usando primeiro elemento:', result);
|
||||
} else {
|
||||
result = response.data;
|
||||
console.log('API retornou objeto direto:', result);
|
||||
}
|
||||
|
||||
return {
|
||||
success: result.success ?? true,
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao deletar pasta:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao deletar pasta',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleta um chat do banco de dados
|
||||
*
|
||||
* @param chatId - ID do chat
|
||||
* @param userEmail - Email do usuário (opcional)
|
||||
* @returns Promise com sucesso ou erro
|
||||
*/
|
||||
async deleteChat(chatId: string, userEmail?: string): Promise<{ success: boolean }> {
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
if (!chatId) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID do chat não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Deletando chat:', {
|
||||
chatId,
|
||||
userEmail: email,
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await apiService.delete<Array<{ success: boolean }>>(
|
||||
`${this.DELETE_CHAT_ENDPOINT}/${email}/${chatId}`
|
||||
);
|
||||
|
||||
console.log('Resposta completa do DELETE:', response);
|
||||
console.log('response.data:', response.data);
|
||||
|
||||
// A API retorna um array com um objeto: [{"success":true}]
|
||||
let result: { success: boolean };
|
||||
|
||||
if (Array.isArray(response.data)) {
|
||||
result = response.data[0];
|
||||
console.log('API retornou array, usando primeiro elemento:', result);
|
||||
} else {
|
||||
result = response.data;
|
||||
console.log('API retornou objeto direto:', result);
|
||||
}
|
||||
|
||||
return {
|
||||
success: result.success ?? true,
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao deletar chat:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao deletar chat',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Busca todas as mensagens de um chat específico
|
||||
*
|
||||
* @param chatId - ID do chat
|
||||
* @param userEmail - Email do usuário (opcional)
|
||||
* @returns Promise com array de mensagens
|
||||
*/
|
||||
async getChatMessages(chatId: string, userEmail?: string): Promise<MessageRecord[]> {
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
if (!chatId) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID do chat não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Buscando mensagens do chat:', {
|
||||
chatId,
|
||||
userEmail: email,
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await apiService.get<MessageRecord[]>(
|
||||
`${this.GET_CHAT_MESSAGES_ENDPOINT}/${email}/${chatId}`
|
||||
);
|
||||
|
||||
console.log('Resposta completa da API:', response);
|
||||
console.log('response.data:', response.data);
|
||||
console.log('É array?:', Array.isArray(response.data));
|
||||
|
||||
// A API retorna diretamente o array de mensagens
|
||||
// Garante que sempre retorna um array
|
||||
if (Array.isArray(response.data)) {
|
||||
return response.data;
|
||||
} else if (response.data && typeof response.data === 'object') {
|
||||
// Se a resposta for um objeto com uma propriedade 'messages' ou similar
|
||||
console.warn('API retornou objeto em vez de array:', response.data);
|
||||
|
||||
// Tenta encontrar o array dentro do objeto
|
||||
if (Array.isArray((response.data as any).messages)) {
|
||||
return (response.data as any).messages;
|
||||
} else if (Array.isArray((response.data as any).data)) {
|
||||
return (response.data as any).data;
|
||||
}
|
||||
}
|
||||
|
||||
// Se não conseguir extrair array, retorna vazio
|
||||
console.warn('Não foi possível extrair array de mensagens da resposta');
|
||||
return [];
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao buscar mensagens:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao buscar mensagens',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exporta instância única (Singleton)
|
||||
|
||||
@@ -11,9 +11,39 @@ export type ImageSize = '1024x1024' | '1024x1792' | '1792x1024';
|
||||
*/
|
||||
export interface ImageGenerationResponse {
|
||||
success: boolean;
|
||||
image_url: string; // URL da imagem gerada
|
||||
image_generation_id: string;
|
||||
message: string; // Descrição original
|
||||
image_url?: string; // URL da imagem gerada (opcional quando há erro)
|
||||
image_generation_id?: string; // ID da geração (opcional quando há erro)
|
||||
message: string; // Descrição original ou mensagem de erro
|
||||
code?: string; // Código de erro (ex: "server_error", "invalid_request")
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para uma imagem armazenada no banco de dados
|
||||
*/
|
||||
export interface ImageRecord {
|
||||
id: string;
|
||||
user_email: string;
|
||||
estabelecimento_id: number;
|
||||
description: string;
|
||||
model: string;
|
||||
image_url: string;
|
||||
size: ImageSize;
|
||||
cost_usd: string;
|
||||
total_tokens: number;
|
||||
input_tokens: number;
|
||||
output_tokens: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para resposta paginada de imagens
|
||||
*/
|
||||
export interface GetImagesResponse {
|
||||
images: ImageRecord[];
|
||||
total: number;
|
||||
page: number;
|
||||
per_page: number;
|
||||
total_pages: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,6 +85,8 @@ export const IMAGE_SIZE_OPTIONS = {
|
||||
*/
|
||||
class ImageGenerationService {
|
||||
private readonly IMAGE_GENERATION_ENDPOINT = '/webhook/codex/image_generator';
|
||||
private readonly GET_IMAGES_ENDPOINT = '/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/get_images';
|
||||
private readonly DELETE_IMAGE_ENDPOINT = '/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/delete_images';
|
||||
|
||||
/**
|
||||
* Gera uma imagem a partir de uma descrição em texto
|
||||
@@ -106,14 +138,39 @@ class ImageGenerationService {
|
||||
}
|
||||
);
|
||||
|
||||
// Verifica se a resposta indica erro
|
||||
if (!response.data.success) {
|
||||
throw {
|
||||
success: false,
|
||||
message: response.data.message || 'Erro ao gerar imagem',
|
||||
code: response.data.code,
|
||||
};
|
||||
}
|
||||
|
||||
return response.data;
|
||||
} catch (error: any) {
|
||||
// Trata erros específicos
|
||||
// Trata erros específicos da API
|
||||
console.error('Erro na geração de imagem:', error);
|
||||
|
||||
// Se o erro já tem a estrutura esperada (veio da validação acima), repassa
|
||||
if (error.success === false && error.message) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Se o erro veio da requisição HTTP, tenta extrair a resposta da API
|
||||
if (error.response?.data) {
|
||||
const apiError = error.response.data;
|
||||
throw {
|
||||
success: false,
|
||||
message: apiError.message || 'Erro ao gerar imagem',
|
||||
code: apiError.code,
|
||||
};
|
||||
}
|
||||
|
||||
// Erro genérico
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao gerar imagem',
|
||||
message: error.message || 'Erro ao gerar imagem. Tente novamente.',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
@@ -213,6 +270,150 @@ class ImageGenerationService {
|
||||
throw new Error('Não foi possível baixar a imagem');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lista imagens do banco de dados com paginação
|
||||
*
|
||||
* @param userEmail - Email do usuário
|
||||
* @param page - Número da página (padrão: 1)
|
||||
* @param perPage - Quantidade de itens por página (padrão: 10)
|
||||
* @returns Promise com a resposta paginada
|
||||
*/
|
||||
async getImages(
|
||||
userEmail?: string,
|
||||
page: number = 1,
|
||||
perPage: number = 10
|
||||
): Promise<ImageRecord[]> {
|
||||
// Usa valores do GlobalFunctions se não forem fornecidos
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Buscando imagens:', {
|
||||
userEmail: email,
|
||||
page,
|
||||
perPage,
|
||||
});
|
||||
|
||||
try {
|
||||
// Faz a requisição GET com parâmetros na URL e query
|
||||
const response = await apiService.get<ImageRecord[]>(
|
||||
`${this.GET_IMAGES_ENDPOINT}/${email}`,
|
||||
{
|
||||
params: {
|
||||
page: page.toString(),
|
||||
per_page: perPage.toString(),
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
console.log('Resposta completa da API:', response);
|
||||
console.log('response.data:', response.data);
|
||||
console.log('É array?:', Array.isArray(response.data));
|
||||
|
||||
// A API retorna diretamente o array de imagens
|
||||
// Garante que sempre retorna um array
|
||||
if (Array.isArray(response.data)) {
|
||||
return response.data;
|
||||
} else if (response.data && typeof response.data === 'object') {
|
||||
// Se a resposta for um objeto com uma propriedade 'images' ou similar
|
||||
console.warn('API retornou objeto em vez de array:', response.data);
|
||||
|
||||
// Tenta encontrar o array dentro do objeto
|
||||
if (Array.isArray((response.data as any).images)) {
|
||||
return (response.data as any).images;
|
||||
} else if (Array.isArray((response.data as any).data)) {
|
||||
return (response.data as any).data;
|
||||
}
|
||||
}
|
||||
|
||||
// Se não conseguir extrair array, retorna vazio
|
||||
console.warn('Não foi possível extrair array de imagens da resposta');
|
||||
return [];
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao buscar imagens:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao buscar imagens',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleta uma imagem do banco de dados
|
||||
*
|
||||
* @param imageId - ID da imagem a ser deletada
|
||||
* @param userEmail - Email do usuário (opcional)
|
||||
* @returns Promise com sucesso ou erro
|
||||
*/
|
||||
async deleteImage(imageId: string, userEmail?: string): Promise<{ success: boolean; message?: string }> {
|
||||
// Usa valores do GlobalFunctions se não forem fornecidos
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
if (!imageId) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID da imagem não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Deletando imagem:', {
|
||||
imageId,
|
||||
userEmail: email,
|
||||
});
|
||||
|
||||
try {
|
||||
// Faz a requisição DELETE com parâmetros na URL
|
||||
const response = await apiService.delete<{ success: boolean; message?: string } | Array<{ success: boolean; message?: string }>>(
|
||||
`${this.DELETE_IMAGE_ENDPOINT}/${email}/${imageId}`
|
||||
);
|
||||
|
||||
console.log('Resposta completa do DELETE:', response);
|
||||
console.log('response.data:', response.data);
|
||||
|
||||
// A API pode retornar um array com um objeto: [{"success":true}]
|
||||
// ou diretamente um objeto: {"success":true}
|
||||
let result: { success: boolean; message?: string };
|
||||
|
||||
if (Array.isArray(response.data)) {
|
||||
// Se for array, pega o primeiro elemento
|
||||
result = response.data[0];
|
||||
console.log('API retornou array, usando primeiro elemento:', result);
|
||||
} else {
|
||||
// Se for objeto direto
|
||||
result = response.data;
|
||||
console.log('API retornou objeto direto:', result);
|
||||
}
|
||||
|
||||
// Garante que tem a estrutura mínima
|
||||
return {
|
||||
success: result.success ?? true,
|
||||
message: result.message || 'Imagem deletada com sucesso',
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao deletar imagem:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao deletar imagem',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exporta instância única (Singleton)
|
||||
|
||||
@@ -6,7 +6,28 @@ export { apiService } from './api';
|
||||
export { transcriptionService } from './transcription';
|
||||
export { audioGenerationService, VOICE_OPTIONS } from './audioGeneration';
|
||||
export { imageGenerationService, IMAGE_SIZE_OPTIONS } from './imageGeneration';
|
||||
export { userProfileService } from './userProfile';
|
||||
export { asanaService } from './asana';
|
||||
export type { TranscriptionResponse, TranscriptionRequest } from './transcription';
|
||||
export type { AudioGenerationResponse, AudioGenerationRequest, VoiceType } from './audioGeneration';
|
||||
export type { ImageGenerationResponse, ImageGenerationRequest, ImageSize } from './imageGeneration';
|
||||
export type {
|
||||
UserProfile,
|
||||
CreateUserRequest,
|
||||
UpdateUserRequest,
|
||||
FinancialIndicators,
|
||||
ExpenseItem,
|
||||
ExpensesResponse,
|
||||
ExpensesFilters,
|
||||
ExpenseCategory
|
||||
} from './userProfile';
|
||||
export type {
|
||||
AsanaWorkspace,
|
||||
AsanaWorkspaceResponse,
|
||||
AsanaWorkspacesResponse,
|
||||
AsanaUser,
|
||||
AsanaUserResponse,
|
||||
AsanaUsersResponse,
|
||||
AsanaIntegrationResponse
|
||||
} from './asana';
|
||||
export type { ApiResponse, UserConfig, ApiError } from './types';
|
||||
|
||||
@@ -11,6 +11,22 @@ export interface TranscriptionResponse {
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para uma transcrição armazenada no banco de dados
|
||||
*/
|
||||
export interface TranscriptionRecord {
|
||||
id: string;
|
||||
user_email: string;
|
||||
estabelecimento_id: number;
|
||||
audio_file_name: string;
|
||||
audio_duration_seconds: number;
|
||||
transcription_text: string;
|
||||
model: string;
|
||||
audio_url: string;
|
||||
cost_usd: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para os dados necessários para transcrição
|
||||
*/
|
||||
@@ -25,6 +41,8 @@ export interface TranscriptionRequest {
|
||||
*/
|
||||
class TranscriptionService {
|
||||
private readonly TRANSCRIPTION_ENDPOINT = '/webhook/codex/transcrever_audio';
|
||||
private readonly GET_TRANSCRIPTIONS_ENDPOINT = '/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/get_transcrever_audio';
|
||||
private readonly DELETE_TRANSCRIPTION_ENDPOINT = '/webhook/fd073ec0-81ab-4681-8acd-b0da71f6ad30/codex/delete_transcrever_audio';
|
||||
|
||||
/**
|
||||
* Transcreve um arquivo de áudio
|
||||
@@ -105,6 +123,149 @@ class TranscriptionService {
|
||||
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Lista transcrições do banco de dados com paginação
|
||||
*
|
||||
* @param userEmail - Email do usuário
|
||||
* @param page - Número da página (padrão: 1)
|
||||
* @param perPage - Quantidade de itens por página (padrão: 10)
|
||||
* @returns Promise com o array de transcrições
|
||||
*/
|
||||
async getTranscriptions(
|
||||
userEmail?: string,
|
||||
page: number = 1,
|
||||
perPage: number = 10
|
||||
): Promise<TranscriptionRecord[]> {
|
||||
// Usa valores do GlobalFunctions se não forem fornecidos
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Buscando transcrições:', {
|
||||
userEmail: email,
|
||||
page,
|
||||
perPage,
|
||||
});
|
||||
|
||||
try {
|
||||
// Faz a requisição GET com parâmetros na URL e query
|
||||
const response = await apiService.get<TranscriptionRecord[]>(
|
||||
`${this.GET_TRANSCRIPTIONS_ENDPOINT}/${email}`,
|
||||
{
|
||||
params: {
|
||||
page: page.toString(),
|
||||
per_page: perPage.toString(),
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
console.log('Resposta completa da API:', response);
|
||||
console.log('response.data:', response.data);
|
||||
console.log('É array?:', Array.isArray(response.data));
|
||||
|
||||
// A API retorna diretamente o array de transcrições
|
||||
// Garante que sempre retorna um array
|
||||
if (Array.isArray(response.data)) {
|
||||
return response.data;
|
||||
} else if (response.data && typeof response.data === 'object') {
|
||||
// Se a resposta for um objeto com uma propriedade 'transcriptions' ou similar
|
||||
console.warn('API retornou objeto em vez de array:', response.data);
|
||||
|
||||
// Tenta encontrar o array dentro do objeto
|
||||
if (Array.isArray((response.data as any).transcriptions)) {
|
||||
return (response.data as any).transcriptions;
|
||||
} else if (Array.isArray((response.data as any).data)) {
|
||||
return (response.data as any).data;
|
||||
}
|
||||
}
|
||||
|
||||
// Se não conseguir extrair array, retorna vazio
|
||||
console.warn('Não foi possível extrair array de transcrições da resposta');
|
||||
return [];
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao buscar transcrições:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao buscar transcrições',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleta uma transcrição do banco de dados
|
||||
*
|
||||
* @param transcriptionId - ID da transcrição a ser deletada
|
||||
* @param userEmail - Email do usuário (opcional)
|
||||
* @returns Promise com sucesso ou erro
|
||||
*/
|
||||
async deleteTranscription(transcriptionId: string, userEmail?: string): Promise<{ success: boolean; message?: string }> {
|
||||
// Usa valores do GlobalFunctions se não forem fornecidos
|
||||
const email = userEmail || GlobalFunctions.getTransferProperty(TransferAreaProperties.UsuarioEmail);
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
if (!transcriptionId) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID da transcrição não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
console.log('Deletando transcrição:', {
|
||||
transcriptionId,
|
||||
userEmail: email,
|
||||
});
|
||||
|
||||
try {
|
||||
// Faz a requisição DELETE com parâmetros na URL
|
||||
const response = await apiService.delete<{ success: boolean; message?: string } | Array<{ success: boolean; message?: string }>>(
|
||||
`${this.DELETE_TRANSCRIPTION_ENDPOINT}/${email}/${transcriptionId}`
|
||||
);
|
||||
|
||||
console.log('Resposta completa do DELETE:', response);
|
||||
console.log('response.data:', response.data);
|
||||
|
||||
// A API retorna um array com um objeto: [{"success":true}]
|
||||
let result: { success: boolean; message?: string };
|
||||
|
||||
if (Array.isArray(response.data)) {
|
||||
// Se for array, pega o primeiro elemento
|
||||
result = response.data[0];
|
||||
console.log('API retornou array, usando primeiro elemento:', result);
|
||||
} else {
|
||||
// Se for objeto direto
|
||||
result = response.data;
|
||||
console.log('API retornou objeto direto:', result);
|
||||
}
|
||||
|
||||
// Garante que tem a estrutura mínima
|
||||
return {
|
||||
success: result.success ?? true,
|
||||
message: result.message || 'Transcrição deletada com sucesso',
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao deletar transcrição:', error);
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao deletar transcrição',
|
||||
status: error.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exporta instância única (Singleton)
|
||||
|
||||
@@ -0,0 +1,577 @@
|
||||
import { apiService } from './api';
|
||||
import { GlobalFunctions } from '@/GlobalFunctions';
|
||||
|
||||
/**
|
||||
* Interfaces para o serviço de perfil do usuário
|
||||
*/
|
||||
export interface UserProfile {
|
||||
success: boolean;
|
||||
id?: string;
|
||||
nome: string;
|
||||
email: string;
|
||||
whatsapp: string;
|
||||
followup: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface CreateUserRequest {
|
||||
nome: string;
|
||||
email: string;
|
||||
whatsapp: string;
|
||||
followup: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateUserRequest {
|
||||
nome: string;
|
||||
whatsapp: string;
|
||||
followup: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para indicadores financeiros
|
||||
*/
|
||||
export interface FinancialIndicators {
|
||||
success: boolean;
|
||||
id: string;
|
||||
nome: string;
|
||||
email: string;
|
||||
total_despesas: string;
|
||||
total_corporativo: string;
|
||||
total_pessoal: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para despesa individual da API
|
||||
*/
|
||||
export interface ExpenseItem {
|
||||
id: string;
|
||||
data_hora: string;
|
||||
descricao: string;
|
||||
tipo: "pessoal" | "corporativo";
|
||||
valor: string;
|
||||
categoria_id: number;
|
||||
categoria_nome: string;
|
||||
usuario_nome: string;
|
||||
usuario_email: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para resposta da API de despesas
|
||||
*/
|
||||
export interface ExpensesResponse {
|
||||
success: boolean;
|
||||
total_registros: number;
|
||||
total_paginas: number;
|
||||
per_page: number;
|
||||
pagina_atual: number;
|
||||
data: ExpenseItem[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para filtros de busca de despesas
|
||||
*/
|
||||
export interface ExpensesFilters {
|
||||
page?: number;
|
||||
per_page?: number;
|
||||
descricao?: string;
|
||||
categoria_id?: number;
|
||||
data_inicial?: string;
|
||||
data_final?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface para categoria de despesas
|
||||
*/
|
||||
export interface ExpenseCategory {
|
||||
id: number;
|
||||
nome: string;
|
||||
descricao: string;
|
||||
criado_em: string;
|
||||
atualizado_em: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serviço para gerenciamento de perfil do usuário
|
||||
*/
|
||||
class UserProfileService {
|
||||
// Em desenvolvimento, usa proxy do Vite para evitar CORS
|
||||
// Em produção, usa URL direta (requer que servidor permita PUT no CORS)
|
||||
private readonly BASE_URL = import.meta.env.DEV
|
||||
? '/api/intelligence'
|
||||
: 'https://prod-hgtx-intelligence-n8n.hgtx.com.br';
|
||||
private readonly WEBHOOK_ID = '2299acaf-70ee-47e3-a6fc-56dcc678d651';
|
||||
private readonly GET_USER_ENDPOINT = `${this.BASE_URL}/webhook/${this.WEBHOOK_ID}/codex/agente-pessoal/user`;
|
||||
private readonly CREATE_USER_ENDPOINT = `${this.BASE_URL}/webhook/codex/agente-pessoal/user`;
|
||||
private readonly UPDATE_USER_ENDPOINT = `${this.BASE_URL}/webhook/${this.WEBHOOK_ID}/codex/agente-pessoal/user`;
|
||||
private readonly GET_FINANCIAL_INDICATORS_ENDPOINT = `${this.BASE_URL}/webhook/${this.WEBHOOK_ID}/codex/agente-pessoal/financas/indicadores`;
|
||||
private readonly GET_EXPENSES_ENDPOINT = `${this.BASE_URL}/webhook/${this.WEBHOOK_ID}/codex/agente-pessoal/financas`;
|
||||
private readonly GET_CATEGORIES_ENDPOINT = `${this.BASE_URL}/webhook/codex/agente-pessoal/categorias`;
|
||||
|
||||
/**
|
||||
* Obtém os detalhes do usuário pelo email
|
||||
*
|
||||
* @param userEmail - Email do usuário (opcional, usa do GlobalFunctions se não fornecido)
|
||||
* @returns Promise com os dados do usuário ou erro se não existir
|
||||
*/
|
||||
async getUserProfile(userEmail?: string): Promise<UserProfile> {
|
||||
const email = userEmail || GlobalFunctions.getUsuarioLogado().email;
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário não fornecido',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
// Usa axios diretamente pois a URL é absoluta e diferente do baseURL
|
||||
const axios = (await import('axios')).default;
|
||||
|
||||
// Obtém o token JWT para autenticação
|
||||
const token = await GlobalFunctions.getToken();
|
||||
const apiKey = import.meta.env.VITE_API_KEY || '';
|
||||
|
||||
// Prepara headers de autenticação
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
// Adiciona API key (obrigatória)
|
||||
if (apiKey) {
|
||||
headers['apikey'] = apiKey;
|
||||
}
|
||||
|
||||
// Adiciona token JWT se disponível
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const response = await axios.get<UserProfile>(
|
||||
`${this.GET_USER_ENDPOINT}/${email}`,
|
||||
{ headers }
|
||||
);
|
||||
|
||||
return response.data;
|
||||
} catch (error: any) {
|
||||
// Se o usuário não existir, retorna o erro da API
|
||||
if (error.response?.data) {
|
||||
return error.response.data;
|
||||
}
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao buscar perfil do usuário',
|
||||
status: error.response?.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cria um novo usuário
|
||||
*
|
||||
* @param request - Dados do usuário a ser criado
|
||||
* @returns Promise com os dados do usuário criado
|
||||
*/
|
||||
async createUser(request: CreateUserRequest): Promise<UserProfile> {
|
||||
// Validações
|
||||
if (!request.nome || request.nome.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Nome é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
if (!request.email || request.email.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
if (!request.whatsapp || request.whatsapp.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'WhatsApp é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
// Remove formatação do WhatsApp (apenas números)
|
||||
const whatsappNumbers = request.whatsapp.replace(/\D/g, '');
|
||||
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
|
||||
// Obtém o token JWT para autenticação
|
||||
const token = await GlobalFunctions.getToken();
|
||||
const apiKey = import.meta.env.VITE_API_KEY || '';
|
||||
|
||||
// Prepara headers de autenticação
|
||||
// A API pode precisar apenas da apikey, não do token JWT
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
// Adiciona API key (obrigatória)
|
||||
if (apiKey) {
|
||||
headers['apikey'] = apiKey;
|
||||
} else {
|
||||
console.warn('VITE_API_KEY não configurada');
|
||||
}
|
||||
|
||||
// Adiciona token JWT se disponível (pode ser necessário)
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
console.log('Criando usuário:', {
|
||||
url: this.CREATE_USER_ENDPOINT,
|
||||
hasApiKey: !!apiKey,
|
||||
hasToken: !!token,
|
||||
data: {
|
||||
nome: request.nome.trim(),
|
||||
email: request.email.trim(),
|
||||
whatsapp: whatsappNumbers,
|
||||
followup: request.followup,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await axios.post<UserProfile>(
|
||||
this.CREATE_USER_ENDPOINT,
|
||||
{
|
||||
nome: request.nome.trim(),
|
||||
email: request.email.trim(),
|
||||
whatsapp: whatsappNumbers,
|
||||
followup: request.followup,
|
||||
},
|
||||
{ headers }
|
||||
);
|
||||
|
||||
return response.data;
|
||||
} catch (error: any) {
|
||||
// Retorna o erro da API se existir
|
||||
if (error.response?.data) {
|
||||
throw error.response.data;
|
||||
}
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao criar usuário',
|
||||
status: error.response?.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atualiza os dados do usuário
|
||||
*
|
||||
* @param userId - ID do usuário
|
||||
* @param request - Dados a serem atualizados
|
||||
* @returns Promise com os dados atualizados do usuário
|
||||
*/
|
||||
async updateUser(userId: string, request: UpdateUserRequest): Promise<UserProfile> {
|
||||
// Validações
|
||||
if (!userId || userId.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'ID do usuário é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
if (!request.nome || request.nome.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Nome é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
if (!request.whatsapp || request.whatsapp.trim().length === 0) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'WhatsApp é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
// Remove formatação do WhatsApp (apenas números)
|
||||
const whatsappNumbers = request.whatsapp.replace(/\D/g, '');
|
||||
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
|
||||
// Obtém o token JWT para autenticação
|
||||
const token = await GlobalFunctions.getToken();
|
||||
const apiKey = import.meta.env.VITE_API_KEY || '';
|
||||
|
||||
// Prepara headers de autenticação
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
// Adiciona API key (obrigatória)
|
||||
if (apiKey) {
|
||||
headers['apikey'] = apiKey;
|
||||
}
|
||||
|
||||
// Adiciona token JWT se disponível
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
console.log('Atualizando usuário:', {
|
||||
url: `${this.UPDATE_USER_ENDPOINT}/${userId}`,
|
||||
method: 'PUT',
|
||||
hasApiKey: !!apiKey,
|
||||
hasToken: !!token,
|
||||
isDev: import.meta.env.DEV,
|
||||
data: {
|
||||
nome: request.nome.trim(),
|
||||
whatsapp: whatsappNumbers,
|
||||
followup: request.followup,
|
||||
},
|
||||
});
|
||||
|
||||
// Usa PUT conforme documentação da API
|
||||
const response = await axios.put<UserProfile>(
|
||||
`${this.UPDATE_USER_ENDPOINT}/${userId}`,
|
||||
{
|
||||
nome: request.nome.trim(),
|
||||
whatsapp: whatsappNumbers,
|
||||
followup: request.followup,
|
||||
},
|
||||
{ headers }
|
||||
);
|
||||
|
||||
return response.data;
|
||||
} catch (error: any) {
|
||||
// Retorna o erro da API se existir
|
||||
if (error.response?.data) {
|
||||
throw error.response.data;
|
||||
}
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error.message || 'Erro ao atualizar usuário',
|
||||
status: error.response?.status,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtém os indicadores financeiros do usuário
|
||||
*
|
||||
* @param userEmail - Email do usuário (opcional, usa do GlobalFunctions se não fornecido)
|
||||
* @returns Promise com os indicadores financeiros
|
||||
*/
|
||||
async getFinancialIndicators(userEmail?: string): Promise<FinancialIndicators> {
|
||||
const email = userEmail || GlobalFunctions.getUsuarioLogado().email;
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
|
||||
// Obtém o token JWT para autenticação
|
||||
const token = await GlobalFunctions.getToken();
|
||||
const apiKey = import.meta.env.VITE_API_KEY || '';
|
||||
|
||||
// Prepara headers de autenticação
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
// Adiciona API key (obrigatória)
|
||||
if (apiKey) {
|
||||
headers['apikey'] = apiKey;
|
||||
}
|
||||
|
||||
// Adiciona token JWT se disponível
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const response = await axios.get<FinancialIndicators>(
|
||||
`${this.GET_FINANCIAL_INDICATORS_ENDPOINT}/${email}`,
|
||||
{ headers }
|
||||
);
|
||||
|
||||
return response.data;
|
||||
} catch (error: unknown) {
|
||||
// Retorna o erro da API se existir
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const axiosError = error as { response?: { data?: FinancialIndicators } };
|
||||
if (axiosError.response?.data) {
|
||||
throw axiosError.response.data;
|
||||
}
|
||||
}
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Erro ao buscar indicadores financeiros',
|
||||
status: error && typeof error === 'object' && 'response' in error
|
||||
? (error as { response?: { status?: number } }).response?.status
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtém a lista de despesas do usuário com paginação e filtros
|
||||
*
|
||||
* @param userEmail - Email do usuário (opcional, usa do GlobalFunctions se não fornecido)
|
||||
* @param filters - Filtros de busca (página, itens por página, descrição, categoria, datas)
|
||||
* @returns Promise com a lista de despesas paginada
|
||||
*/
|
||||
async getExpenses(userEmail?: string, filters?: ExpensesFilters): Promise<ExpensesResponse> {
|
||||
const email = userEmail || GlobalFunctions.getUsuarioLogado().email;
|
||||
|
||||
if (!email) {
|
||||
throw {
|
||||
success: false,
|
||||
message: 'Email do usuário é obrigatório',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
|
||||
// Obtém o token JWT para autenticação
|
||||
const token = await GlobalFunctions.getToken();
|
||||
const apiKey = import.meta.env.VITE_API_KEY || '';
|
||||
|
||||
// Prepara headers de autenticação
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
// Adiciona API key (obrigatória)
|
||||
if (apiKey) {
|
||||
headers['apikey'] = apiKey;
|
||||
}
|
||||
|
||||
// Adiciona token JWT se disponível
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// Constrói query params
|
||||
const params = new URLSearchParams();
|
||||
if (filters?.page) params.append('page', filters.page.toString());
|
||||
if (filters?.per_page) params.append('per_page', filters.per_page.toString());
|
||||
if (filters?.descricao) params.append('descricao', filters.descricao);
|
||||
if (filters?.categoria_id) params.append('categoria_id', filters.categoria_id.toString());
|
||||
if (filters?.data_inicial) params.append('data_inicial', filters.data_inicial);
|
||||
if (filters?.data_final) params.append('data_final', filters.data_final);
|
||||
|
||||
const queryString = params.toString();
|
||||
const url = `${this.GET_EXPENSES_ENDPOINT}/${email}${queryString ? `?${queryString}` : ''}`;
|
||||
|
||||
const response = await axios.get<ExpensesResponse[]>(url, { headers });
|
||||
|
||||
// A API retorna um array com um único objeto
|
||||
if (Array.isArray(response.data) && response.data.length > 0) {
|
||||
const expensesResponse = response.data[0];
|
||||
|
||||
// Valida e limpa o array de dados, removendo objetos vazios
|
||||
if (expensesResponse.data && Array.isArray(expensesResponse.data)) {
|
||||
// Filtra objetos vazios (sem propriedades ou apenas com propriedades vazias)
|
||||
expensesResponse.data = expensesResponse.data.filter((item) => {
|
||||
// Verifica se o objeto tem pelo menos uma propriedade válida
|
||||
return item && typeof item === 'object' && Object.keys(item).length > 0 && item.id;
|
||||
});
|
||||
|
||||
// Se após filtrar não há dados, garante que data seja um array vazio
|
||||
if (expensesResponse.data.length === 0) {
|
||||
expensesResponse.data = [];
|
||||
expensesResponse.total_registros = 0;
|
||||
expensesResponse.total_paginas = 0;
|
||||
}
|
||||
} else {
|
||||
// Se data não é um array válido, inicializa como array vazio
|
||||
expensesResponse.data = [];
|
||||
expensesResponse.total_registros = 0;
|
||||
expensesResponse.total_paginas = 0;
|
||||
}
|
||||
|
||||
return expensesResponse;
|
||||
}
|
||||
|
||||
// Fallback caso a estrutura seja diferente - retorna resposta vazia
|
||||
return {
|
||||
success: true,
|
||||
total_registros: 0,
|
||||
total_paginas: 0,
|
||||
per_page: filters?.per_page || 10,
|
||||
pagina_atual: filters?.page || 1,
|
||||
data: [],
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
// Retorna o erro da API se existir
|
||||
if (error && typeof error === 'object' && 'response' in error) {
|
||||
const axiosError = error as { response?: { data?: ExpensesResponse } };
|
||||
if (axiosError.response?.data) {
|
||||
throw axiosError.response.data;
|
||||
}
|
||||
}
|
||||
|
||||
throw {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Erro ao buscar despesas',
|
||||
status: error && typeof error === 'object' && 'response' in error
|
||||
? (error as { response?: { status?: number } }).response?.status
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtém a lista de categorias de despesas
|
||||
*
|
||||
* @returns Promise com a lista de categorias
|
||||
*/
|
||||
async getCategories(): Promise<ExpenseCategory[]> {
|
||||
try {
|
||||
const axios = (await import('axios')).default;
|
||||
|
||||
// Obtém o token JWT para autenticação
|
||||
const token = await GlobalFunctions.getToken();
|
||||
const apiKey = import.meta.env.VITE_API_KEY || '';
|
||||
|
||||
// Prepara headers de autenticação
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
// Adiciona API key (obrigatória)
|
||||
if (apiKey) {
|
||||
headers['apikey'] = apiKey;
|
||||
}
|
||||
|
||||
// Adiciona token JWT se disponível
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const response = await axios.get<ExpenseCategory[]>(this.GET_CATEGORIES_ENDPOINT, { headers });
|
||||
|
||||
// A API retorna um array de categorias
|
||||
if (Array.isArray(response.data)) {
|
||||
return response.data;
|
||||
}
|
||||
|
||||
return [];
|
||||
} catch (error: unknown) {
|
||||
console.error('Erro ao buscar categorias:', error);
|
||||
|
||||
// Retorna array vazio em caso de erro para não quebrar a aplicação
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exporta instância única (Singleton)
|
||||
export const userProfileService = new UserProfileService();
|
||||
@@ -34,6 +34,14 @@ export default {
|
||||
DEFAULT: "hsl(var(--destructive))",
|
||||
foreground: "hsl(var(--destructive-foreground))",
|
||||
},
|
||||
success: {
|
||||
DEFAULT: "hsl(var(--success))",
|
||||
foreground: "hsl(var(--success-foreground))",
|
||||
},
|
||||
warning: {
|
||||
DEFAULT: "hsl(var(--warning))",
|
||||
foreground: "hsl(var(--warning-foreground))",
|
||||
},
|
||||
muted: {
|
||||
DEFAULT: "hsl(var(--muted))",
|
||||
foreground: "hsl(var(--muted-foreground))",
|
||||
|
||||
@@ -8,6 +8,14 @@ export default defineConfig(({ mode }) => ({
|
||||
server: {
|
||||
host: "::",
|
||||
port: 8080,
|
||||
proxy: {
|
||||
'/api/intelligence': {
|
||||
target: 'https://prod-hgtx-intelligence-n8n.hgtx.com.br',
|
||||
changeOrigin: true,
|
||||
rewrite: (path) => path.replace(/^\/api\/intelligence/, ''),
|
||||
secure: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [react(), mode === "development" && componentTagger()].filter(Boolean),
|
||||
resolve: {
|
||||
|
||||
Reference in New Issue
Block a user