import React, { useState, useEffect } from "react"; import { Save, Search, DollarSign } from "lucide-react"; import { Button } from "../Button"; import { useAuth } from "../../contexts/AuthContext"; import { toast } from "react-hot-toast"; const API_BASE_URL = import.meta.env.VITE_API_URL || "http://localhost:8080"; interface Role { id: string; nome: string; } interface EventType { id: string; nome: string; } interface Price { id?: string; funcao_profissional_id: string; tipo_evento_id: string; valor: number; } export const PriceTableEditor: React.FC = () => { const { token } = useAuth(); const [eventTypes, setEventTypes] = useState([]); const [roles, setRoles] = useState([]); const [prices, setPrices] = useState>({}); // roleId -> value const [selectedEventId, setSelectedEventId] = useState(""); const [loading, setLoading] = useState(false); const [saving, setSaving] = useState(false); // Initial Load useEffect(() => { const loadInitialData = async () => { try { const [eventsRes, rolesRes] = await Promise.all([ fetch(`${API_BASE_URL}/api/tipos-eventos`, { headers: { Authorization: `Bearer ${token}` } }), fetch(`${API_BASE_URL}/api/funcoes`, { headers: { Authorization: `Bearer ${token}` } }) ]); const eventsData = await eventsRes.json(); const rolesData = await rolesRes.json(); // Adjust for data wrapper if exists const events = (eventsData.data || eventsData) as EventType[]; const roles = (rolesData.data || rolesData) as Role[]; setEventTypes(events); setRoles(roles); if (events.length > 0) setSelectedEventId(events[0].id); } catch (error) { console.error(error); toast.error("Erro ao carregar dados iniciais"); } }; if (token) loadInitialData(); }, [token]); // Load Prices when Event Selected useEffect(() => { if (!selectedEventId || !token) return; const loadPrices = async () => { setLoading(true); try { // Assuming we use type-events/:id/precos or similar // Based on routes: GET /api/tipos-eventos/:id/precos const res = await fetch(`${API_BASE_URL}/api/tipos-eventos/${selectedEventId}/precos`, { headers: { Authorization: `Bearer ${token}` } }); if (!res.ok) throw new Error("Erro ao carregar preços"); const data = await res.json(); const priceList = (data.data || data) as Price[]; // Map to dictionary const priceMap: Record = {}; priceList.forEach(p => { priceMap[p.funcao_profissional_id] = p.valor; }); setPrices(priceMap); } catch (error) { toast.error("Erro ao carregar tabela de preços"); } finally { setLoading(false); } }; loadPrices(); }, [selectedEventId, token]); const handlePriceChange = (roleId: string, value: string) => { const numValue = parseFloat(value) || 0; setPrices(prev => ({ ...prev, [roleId]: numValue })); }; const handleSave = async () => { setSaving(true); try { // Need to save each price. Backend has POST /api/tipos-eventos/precos // Body: { tipo_evento_id, funcao_profissional_id, valor } // We can do parallel requests or backend bulk? // Existing route seems singular or accepts array? // "api.POST("/tipos-eventos/precos", tiposEventosHandler.SetPrice)" // I'll assume singular for safety, or create a loop. const promises = roles.map(role => { const valor = prices[role.id]; // If undefined, maybe skip? But maybe we want to save 0? if (valor === undefined) return Promise.resolve(); return fetch(`${API_BASE_URL}/api/tipos-eventos/precos`, { method: "POST", // or PUT check handlers headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` }, body: JSON.stringify({ tipo_evento_id: selectedEventId, funcao_profissional_id: role.id, valor: valor }) }); }); await Promise.all(promises); toast.success("Preços atualizados com sucesso!"); } catch (error) { console.error(error); toast.error("Erro ao salvar preços"); } finally { setSaving(false); } }; return (

Tabela de Preços (Cachês Base)

{loading ? ( ) : roles.map(role => ( ))}
Função Valor do Cachê (R$)
Carregando...
{role.nome}
R$ handlePriceChange(role.id, e.target.value)} placeholder="0,00" />
); };