vendaweb-api/src/app/DRE/teste.tsx

715 lines
27 KiB
TypeScript
Raw Normal View History

2025-10-08 04:19:15 +00:00
'use client';
import { LoaderPinwheel } from 'lucide-react';
2025-10-08 04:19:15 +00:00
import { useEffect, useState } from 'react';
import AnaliticoComponent from './analitico';
2025-10-08 04:19:15 +00:00
interface DREItem {
codfilial: string;
data_competencia: string;
data_cai: string;
grupo: string;
subgrupo: string;
centro_custo: string;
codigo_conta: number;
conta: string;
valor: string;
}
interface HierarchicalRow {
type: 'grupo' | 'subgrupo' | 'centro_custo' | 'conta';
level: number;
grupo?: string;
subgrupo?: string;
centro_custo?: string;
conta?: string;
codigo_conta?: number;
total?: number;
isExpanded?: boolean;
valoresPorMes?: Record<string, number>;
percentuaisPorMes?: Record<string, number>;
2025-10-08 04:19:15 +00:00
}
export default function Teste() {
const [data, setData] = useState<DREItem[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
const [expandedSubgrupos, setExpandedSubgrupos] = useState<Set<string>>(
new Set()
);
const [expandedCentros, setExpandedCentros] = useState<Set<string>>(
new Set()
);
const [mesesDisponiveis, setMesesDisponiveis] = useState<string[]>([]);
// Estados para analítico
const [analiticoFiltros, setAnaliticoFiltros] = useState({
dataInicio: '',
dataFim: '',
centroCusto: '',
codigoGrupo: '',
codigoSubgrupo: '',
codigoConta: '',
});
2025-10-08 05:30:37 +00:00
const [linhaSelecionada, setLinhaSelecionada] = useState<string | null>(null);
2025-10-08 04:19:15 +00:00
useEffect(() => {
fetchData();
}, []);
const fetchData = async () => {
try {
setLoading(true);
setError(null);
2025-10-08 04:19:15 +00:00
const response = await fetch('/api/dre');
2025-10-08 04:19:15 +00:00
if (!response.ok) {
throw new Error(`Erro ao carregar dados: ${response.status}`);
2025-10-08 04:19:15 +00:00
}
2025-10-08 04:19:15 +00:00
const result = await response.json();
setData(result);
// Extrair meses únicos dos dados
const meses = [
...new Set(
result.map((item: DREItem) => {
const dataCompetencia = new Date(item.data_competencia);
return `${dataCompetencia.getFullYear()}-${String(
dataCompetencia.getMonth() + 1
).padStart(2, '0')}`;
})
),
].sort() as string[];
setMesesDisponiveis(meses);
} catch (err) {
setError(err instanceof Error ? err.message : 'Erro desconhecido');
} finally {
setLoading(false);
}
};
const formatCurrency = (value: string | number) => {
const numValue = typeof value === 'string' ? parseFloat(value) : value;
return numValue.toLocaleString('pt-BR', {
style: 'currency',
currency: 'BRL',
});
};
2025-10-08 12:28:20 +00:00
const formatCurrencyWithColor = (value: string | number) => {
const numValue = typeof value === 'string' ? parseFloat(value) : value;
const formatted = formatCurrency(value);
const isNegative = numValue < 0;
return { formatted, isNegative };
};
// Função para extrair códigos dos grupos e subgrupos
const extractCodes = (grupo: string, subgrupo?: string) => {
const grupoMatch = grupo.match(/^(\d+)/);
const codigoGrupo = grupoMatch ? grupoMatch[1] : '';
let codigoSubgrupo = '';
if (subgrupo) {
// Primeiro tenta extrair código numérico (ex: "001.008 - LOJA 8" -> "001.008")
const subgrupoMatch = subgrupo.match(/^(\d+(?:\.\d+)+)/);
if (subgrupoMatch) {
codigoSubgrupo = subgrupoMatch[1];
} else {
// Se não tem código numérico, usa a descrição completa (ex: "DESPESAS ADMINISTRATIVAS")
codigoSubgrupo = subgrupo;
}
}
return { codigoGrupo, codigoSubgrupo };
};
// Função para lidar com clique nas linhas
2025-10-08 05:30:37 +00:00
const handleRowClick = (row: HierarchicalRow, mesSelecionado?: string) => {
if (!data.length) return;
// Pegar todas as datas disponíveis para definir o período
const datas = data.map((item) => item.data_competencia);
const dataInicio = Math.min(...datas.map((d) => new Date(d).getTime()));
const dataFim = Math.max(...datas.map((d) => new Date(d).getTime()));
const dataInicioStr = new Date(dataInicio).toISOString().substring(0, 7); // YYYY-MM
const dataFimStr = new Date(dataFim).toISOString().substring(0, 7); // YYYY-MM
const { codigoGrupo, codigoSubgrupo } = extractCodes(
row.grupo || '',
row.subgrupo
);
2025-10-08 05:30:37 +00:00
// Criar um identificador único para a linha
const linhaId = `${row.type}-${row.grupo || ''}-${row.subgrupo || ''}-${
row.centro_custo || ''
}-${row.codigo_conta || ''}`;
setLinhaSelecionada(linhaId);
// Se um mês específico foi selecionado, usar apenas esse mês
const dataInicioFiltro = mesSelecionado || dataInicioStr;
const dataFimFiltro = mesSelecionado || dataFimStr;
setAnaliticoFiltros({
2025-10-08 05:30:37 +00:00
dataInicio: dataInicioFiltro,
dataFim: dataFimFiltro,
centroCusto: row.centro_custo || '',
codigoGrupo,
codigoSubgrupo,
codigoConta: row.codigo_conta?.toString() || '',
});
};
2025-10-08 04:19:15 +00:00
const toggleGroup = (grupo: string) => {
const newExpanded = new Set(expandedGroups);
if (newExpanded.has(grupo)) {
newExpanded.delete(grupo);
} else {
newExpanded.add(grupo);
}
setExpandedGroups(newExpanded);
};
const toggleSubgrupo = (subgrupo: string) => {
const newExpanded = new Set(expandedSubgrupos);
if (newExpanded.has(subgrupo)) {
newExpanded.delete(subgrupo);
} else {
newExpanded.add(subgrupo);
}
setExpandedSubgrupos(newExpanded);
};
const toggleCentro = (centro: string) => {
const newExpanded = new Set(expandedCentros);
if (newExpanded.has(centro)) {
newExpanded.delete(centro);
} else {
newExpanded.add(centro);
}
setExpandedCentros(newExpanded);
};
const calcularValoresPorMes = (items: DREItem[]): Record<string, number> => {
const valoresPorMes: Record<string, number> = {};
items.forEach((item) => {
const dataCompetencia = new Date(item.data_competencia);
const anoMes = `${dataCompetencia.getFullYear()}-${String(
dataCompetencia.getMonth() + 1
).padStart(2, '0')}`;
if (!valoresPorMes[anoMes]) {
valoresPorMes[anoMes] = 0;
}
valoresPorMes[anoMes] += parseFloat(item.valor);
});
return valoresPorMes;
};
// Função para calcular percentuais baseado no grupo 03 como referência
const calcularPercentuaisPorMes = (
valoresPorMes: Record<string, number>,
grupo: string
): Record<string, number> => {
const percentuais: Record<string, number> = {};
// Se for o grupo 03, retorna 100% para todos os meses
if (grupo.includes('03')) {
Object.keys(valoresPorMes).forEach((mes) => {
percentuais[mes] = 100;
});
return percentuais;
}
// Para outros grupos, calcular percentual baseado no grupo 03
Object.keys(valoresPorMes).forEach((mes) => {
const valorAtual = valoresPorMes[mes];
// Encontrar o valor do grupo 03 para o mesmo mês
const grupo03Items = data.filter((item) => {
const dataCompetencia = new Date(item.data_competencia);
const anoMes = `${dataCompetencia.getFullYear()}-${String(
dataCompetencia.getMonth() + 1
).padStart(2, '0')}`;
return anoMes === mes && item.grupo.includes('03');
});
const valorGrupo03 = grupo03Items.reduce(
(sum, item) => sum + parseFloat(item.valor),
0
);
if (valorGrupo03 !== 0) {
percentuais[mes] = (valorAtual / valorGrupo03) * 100;
} else {
percentuais[mes] = 0;
}
});
return percentuais;
};
2025-10-08 04:19:15 +00:00
const buildHierarchicalData = (): HierarchicalRow[] => {
const rows: HierarchicalRow[] = [];
// Agrupar por grupo, mas tratar grupo 05 como subgrupo do grupo 04
2025-10-08 04:19:15 +00:00
const grupos = data.reduce((acc, item) => {
// Se for grupo 05, adicionar ao grupo 04 como subgrupo
if (item.grupo.includes('05')) {
// Encontrar grupo 04 existente ou criar um
const grupo04Key = Object.keys(acc).find((key) => key.includes('04'));
if (grupo04Key) {
acc[grupo04Key].push(item);
} else {
// Se não existe grupo 04, criar um grupo especial
const grupo04Nome =
Object.keys(acc).find((key) => key.includes('04')) ||
'04 - GRUPO 04';
if (!acc[grupo04Nome]) {
acc[grupo04Nome] = [];
}
acc[grupo04Nome].push(item);
}
} else {
// Para outros grupos, agrupar normalmente
if (!acc[item.grupo]) {
acc[item.grupo] = [];
}
acc[item.grupo].push(item);
2025-10-08 04:19:15 +00:00
}
return acc;
}, {} as Record<string, DREItem[]>);
// Ordenar grupos
const sortedGrupos = Object.entries(grupos).sort(([a], [b]) => a.localeCompare(b));
2025-10-08 04:19:15 +00:00
sortedGrupos.forEach(([grupo, items]) => {
const totalGrupo = items.reduce(
(sum, item) => sum + parseFloat(item.valor),
0
);
// Linha do grupo
const valoresPorMes = calcularValoresPorMes(items);
2025-10-08 04:19:15 +00:00
rows.push({
type: 'grupo',
level: 0,
grupo,
total: totalGrupo,
isExpanded: expandedGroups.has(grupo),
valoresPorMes,
percentuaisPorMes: calcularPercentuaisPorMes(valoresPorMes, grupo),
2025-10-08 04:19:15 +00:00
});
if (expandedGroups.has(grupo)) {
// Agrupar por subgrupo dentro do grupo
const subgrupos = items.reduce((acc, item) => {
// Se o item originalmente era do grupo 05, agrupar tudo sob o nome do grupo 05
if (item.grupo.includes('05')) {
const subgrupoKey = item.grupo; // Usar o nome completo do grupo 05
if (!acc[subgrupoKey]) {
acc[subgrupoKey] = [];
}
acc[subgrupoKey].push(item);
} else {
// Para outros itens, agrupar normalmente por subgrupo
if (!acc[item.subgrupo]) {
acc[item.subgrupo] = [];
}
acc[item.subgrupo].push(item);
2025-10-08 04:19:15 +00:00
}
return acc;
}, {} as Record<string, DREItem[]>);
// Ordenar subgrupos
const sortedSubgrupos = Object.entries(subgrupos).sort(([a], [b]) => a.localeCompare(b));
2025-10-08 04:19:15 +00:00
sortedSubgrupos.forEach(([subgrupo, subgrupoItems]) => {
const totalSubgrupo = subgrupoItems.reduce(
(sum, item) => sum + parseFloat(item.valor),
0
);
// Linha do subgrupo
const valoresSubgrupoPorMes = calcularValoresPorMes(subgrupoItems);
2025-10-08 04:19:15 +00:00
rows.push({
type: 'subgrupo',
level: 1,
grupo,
subgrupo,
total: totalSubgrupo,
isExpanded: expandedSubgrupos.has(`${grupo}-${subgrupo}`),
valoresPorMes: valoresSubgrupoPorMes,
percentuaisPorMes: calcularPercentuaisPorMes(
valoresSubgrupoPorMes,
grupo
),
2025-10-08 04:19:15 +00:00
});
if (expandedSubgrupos.has(`${grupo}-${subgrupo}`)) {
// Agrupar por centro de custo dentro do subgrupo
const centros = subgrupoItems.reduce((acc, item) => {
if (!acc[item.centro_custo]) {
acc[item.centro_custo] = [];
}
acc[item.centro_custo].push(item);
return acc;
}, {} as Record<string, DREItem[]>);
// Ordenar centros de custo
const sortedCentros = Object.entries(centros).sort(([a], [b]) => a.localeCompare(b));
2025-10-08 04:19:15 +00:00
sortedCentros.forEach(([centro, centroItems]) => {
const totalCentro = centroItems.reduce(
(sum, item) => sum + parseFloat(item.valor),
0
);
// Linha do centro de custo
const valoresCentroPorMes = calcularValoresPorMes(centroItems);
2025-10-08 04:19:15 +00:00
rows.push({
type: 'centro_custo',
level: 2,
grupo,
subgrupo,
centro_custo: centro,
total: totalCentro,
isExpanded: expandedCentros.has(
`${grupo}-${subgrupo}-${centro}`
),
valoresPorMes: valoresCentroPorMes,
percentuaisPorMes: calcularPercentuaisPorMes(
valoresCentroPorMes,
grupo
),
2025-10-08 04:19:15 +00:00
});
if (expandedCentros.has(`${grupo}-${subgrupo}-${centro}`)) {
// Agrupar por conta dentro do centro de custo
const contas = centroItems.reduce((acc, item) => {
if (!acc[item.conta]) {
acc[item.conta] = [];
}
acc[item.conta].push(item);
return acc;
}, {} as Record<string, DREItem[]>);
// Ordenar contas
const sortedContas = Object.entries(contas).sort(([a], [b]) => a.localeCompare(b));
2025-10-08 04:19:15 +00:00
sortedContas.forEach(([conta, contaItems]) => {
const totalConta = contaItems.reduce(
(sum, item) => sum + parseFloat(item.valor),
0
);
// Linha da conta (sem ano/mês no nome)
const valoresContaPorMes = calcularValoresPorMes(contaItems);
2025-10-08 04:19:15 +00:00
rows.push({
type: 'conta',
level: 3,
grupo,
subgrupo,
centro_custo: centro,
conta,
codigo_conta: contaItems[0].codigo_conta,
total: totalConta,
valoresPorMes: valoresContaPorMes,
percentuaisPorMes: calcularPercentuaisPorMes(
valoresContaPorMes,
grupo
),
2025-10-08 04:19:15 +00:00
});
});
}
});
}
});
}
});
return rows;
};
const getRowStyle = (row: HierarchicalRow) => {
const baseStyle = 'transition-all duration-200 hover:bg-gradient-to-r hover:from-blue-50/30 hover:to-indigo-50/30';
2025-10-08 04:19:15 +00:00
2025-10-08 05:30:37 +00:00
// Criar identificador único para a linha
const linhaId = `${row.type}-${row.grupo || ''}-${row.subgrupo || ''}-${
row.centro_custo || ''
}-${row.codigo_conta || ''}`;
const isSelected = linhaSelecionada === linhaId;
let style = baseStyle;
if (isSelected) {
style += ' bg-gradient-to-r from-blue-100 to-indigo-100 border-l-4 border-blue-500 shadow-lg';
2025-10-08 05:30:37 +00:00
}
2025-10-08 04:19:15 +00:00
switch (row.type) {
case 'grupo':
return `${style} bg-gradient-to-r from-blue-50/20 to-indigo-50/20 font-bold text-gray-900 border-b-2 border-blue-200`;
2025-10-08 04:19:15 +00:00
case 'subgrupo':
return `${style} bg-gradient-to-r from-gray-50/30 to-blue-50/20 font-semibold text-gray-800`;
2025-10-08 04:19:15 +00:00
case 'centro_custo':
return `${style} bg-gradient-to-r from-gray-50/20 to-gray-100/10 font-medium text-gray-700`;
2025-10-08 04:19:15 +00:00
case 'conta':
return `${style} bg-white font-normal text-gray-600`;
2025-10-08 04:19:15 +00:00
default:
2025-10-08 05:30:37 +00:00
return style;
2025-10-08 04:19:15 +00:00
}
};
const getIndentStyle = (level: number) => {
return { paddingLeft: `${level * 20}px` };
};
const renderCellContent = (row: HierarchicalRow) => {
switch (row.type) {
case 'grupo':
return (
<div className="flex items-center gap-3 whitespace-nowrap">
2025-10-08 04:19:15 +00:00
<button
onClick={() => toggleGroup(row.grupo!)}
className="p-2 hover:bg-blue-100 rounded-lg transition-all duration-200 flex items-center justify-center w-8 h-8 flex-shrink-0"
2025-10-08 04:19:15 +00:00
>
<span className="text-blue-600 font-bold text-sm">
{row.isExpanded ? '▼' : '▶'}
</span>
2025-10-08 04:19:15 +00:00
</button>
<button
onClick={() => handleRowClick(row)}
className="flex-1 text-left hover:bg-blue-50/50 p-2 rounded-lg cursor-pointer transition-all duration-200 truncate"
>
<span className="font-bold text-gray-900">{row.grupo}</span>
</button>
2025-10-08 04:19:15 +00:00
</div>
);
case 'subgrupo':
return (
<div className="flex items-center gap-3 whitespace-nowrap">
2025-10-08 04:19:15 +00:00
<button
onClick={() => toggleSubgrupo(`${row.grupo}-${row.subgrupo}`)}
className="p-2 hover:bg-blue-100 rounded-lg transition-all duration-200 flex items-center justify-center w-8 h-8 flex-shrink-0"
2025-10-08 04:19:15 +00:00
>
<span className="text-blue-600 font-bold text-sm">
{row.isExpanded ? '▼' : '▶'}
</span>
2025-10-08 04:19:15 +00:00
</button>
<button
onClick={() => handleRowClick(row)}
className="flex-1 text-left hover:bg-blue-50/50 p-2 rounded-lg cursor-pointer transition-all duration-200 truncate"
>
<span className="font-semibold text-gray-800">{row.subgrupo}</span>
</button>
2025-10-08 04:19:15 +00:00
</div>
);
case 'centro_custo':
return (
<div className="flex items-center gap-3 whitespace-nowrap">
2025-10-08 04:19:15 +00:00
<button
onClick={() =>
toggleCentro(`${row.grupo}-${row.subgrupo}-${row.centro_custo}`)
}
className="p-2 hover:bg-blue-100 rounded-lg transition-all duration-200 flex items-center justify-center w-8 h-8 flex-shrink-0"
2025-10-08 04:19:15 +00:00
>
<span className="text-blue-600 font-bold text-sm">
{row.isExpanded ? '▼' : '▶'}
</span>
2025-10-08 04:19:15 +00:00
</button>
<button
onClick={() => handleRowClick(row)}
className="flex-1 text-left hover:bg-blue-50/50 p-2 rounded-lg cursor-pointer transition-all duration-200 truncate"
>
<span className="font-medium text-gray-700">{row.centro_custo}</span>
</button>
2025-10-08 04:19:15 +00:00
</div>
);
case 'conta':
return (
<div className="flex items-center gap-3 whitespace-nowrap">
<div className="w-8 h-8 flex items-center justify-center flex-shrink-0">
<span className="text-gray-400 font-bold text-lg"></span>
</div>
<button
onClick={() => handleRowClick(row)}
className="flex-1 text-left hover:bg-blue-50/50 p-2 rounded-lg cursor-pointer transition-all duration-200 truncate"
>
<span className="font-normal text-gray-600">{row.conta}</span>
</button>
2025-10-08 04:19:15 +00:00
</div>
);
default:
return null;
}
};
if (loading) {
return (
<div className="w-full max-w-7xl mx-auto p-6">
<div className="mb-6">
<div className="flex items-center gap-3 mb-4">
<div className="w-12 h-12 bg-gradient-to-r from-blue-600 to-indigo-600 rounded-xl flex items-center justify-center shadow-lg">
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
</div>
<div>
<h1 className="text-2xl font-bold text-gray-900">DRE Gerencial</h1>
<p className="text-sm text-gray-500">Demonstração do Resultado do Exercício</p>
</div>
</div>
</div>
<div className="bg-white rounded-xl shadow-lg border border-gray-200 p-12">
<div className="flex flex-col items-center justify-center">
<div className="w-16 h-16 bg-gradient-to-r from-blue-100 to-indigo-100 rounded-full flex items-center justify-center mb-4">
<LoaderPinwheel className="h-8 w-8 text-blue-600 animate-spin" />
</div>
<h3 className="text-lg font-semibold text-gray-900 mb-2">Carregando dados...</h3>
<p className="text-sm text-gray-500">Aguarde enquanto processamos as informações</p>
2025-10-08 04:19:15 +00:00
</div>
</div>
</div>
);
}
if (error) {
return (
<div className="w-full max-w-7xl mx-auto p-6">
<div className="mb-6">
<div className="flex items-center gap-3 mb-4">
<div className="w-12 h-12 bg-gradient-to-r from-red-600 to-red-500 rounded-xl flex items-center justify-center shadow-lg">
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
</svg>
</div>
<div>
<h1 className="text-2xl font-bold text-gray-900">DRE Gerencial</h1>
<p className="text-sm text-gray-500">Demonstração do Resultado do Exercício</p>
</div>
</div>
</div>
<div className="bg-white rounded-xl shadow-xl border border-red-200 p-8">
<div className="flex flex-col items-center text-center">
<div className="w-16 h-16 bg-gradient-to-r from-red-100 to-red-50 rounded-full flex items-center justify-center mb-4">
<svg className="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
</svg>
</div>
<h3 className="text-lg font-semibold text-red-900 mb-2">Erro ao carregar DRE Gerencial</h3>
<p className="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg p-3 max-w-md">
{error}
</p>
</div>
2025-10-08 04:19:15 +00:00
</div>
</div>
);
}
const hierarchicalData = buildHierarchicalData();
return (
<div className="w-full max-w-7xl mx-auto p-6">
{/* Header Section */}
<div className="mb-6">
<div className="flex items-center gap-3 mb-4">
<div className="w-12 h-12 bg-gradient-to-r from-blue-600 to-indigo-600 rounded-xl flex items-center justify-center shadow-lg">
<svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
</div>
<div>
<h1 className="text-2xl font-bold text-gray-900">DRE Gerencial</h1>
<p className="text-sm text-gray-500">Demonstração do Resultado do Exercício</p>
</div>
</div>
2025-10-08 04:19:15 +00:00
</div>
{/* Table Container */}
<div className="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden">
{/* Table Header */}
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 border-b border-gray-200 sticky top-0 z-20">
<div className="flex items-center gap-4 px-4 py-3 text-xs font-semibold text-gray-700 uppercase tracking-wide">
<div className="flex-1 min-w-[300px] max-w-[400px]">Descrição</div>
2025-10-08 04:19:15 +00:00
{mesesDisponiveis.map((mes) => (
<div key={mes} className="flex min-w-[200px] max-w-[250px]">
<div className="flex-1 min-w-[100px] text-right">{mes}</div>
<div className="flex-1 min-w-[100px] text-left text-xs text-gray-500">%</div>
2025-10-08 04:26:38 +00:00
</div>
2025-10-08 04:19:15 +00:00
))}
<div className="flex-1 min-w-[120px] text-right">Total</div>
2025-10-08 04:26:38 +00:00
</div>
</div>
{/* Table Body */}
<div className="max-h-[500px] overflow-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100">
2025-10-08 04:45:26 +00:00
{hierarchicalData.map((row, index) => (
<div key={index} className={`flex items-center gap-4 px-4 py-3 text-sm border-b border-gray-100 hover:bg-gray-50 transition-colors ${getRowStyle(row)}`}>
<div className="flex-1 min-w-[300px] max-w-[400px] whitespace-nowrap overflow-hidden" style={getIndentStyle(row.level)}>
2025-10-08 04:45:26 +00:00
{renderCellContent(row)}
</div>
2025-10-08 04:19:15 +00:00
{mesesDisponiveis.map((mes) => (
<div key={mes} className="flex min-w-[200px] max-w-[250px]">
<div
className="flex-1 min-w-[100px] text-right font-semibold cursor-pointer hover:bg-blue-50/50 transition-colors duration-200 whitespace-nowrap overflow-hidden"
onClick={() => handleRowClick(row, mes)}
title={row.valoresPorMes && row.valoresPorMes[mes] ? formatCurrency(row.valoresPorMes[mes]) : '-'}
>
{row.valoresPorMes && row.valoresPorMes[mes]
? (() => {
const { formatted, isNegative } = formatCurrencyWithColor(row.valoresPorMes[mes]);
return (
<span className={isNegative ? 'text-red-600 font-bold' : 'text-gray-900'}>
{formatted}
</span>
);
})()
: '-'}
</div>
<div
className="flex-1 min-w-[100px] text-left font-medium cursor-pointer hover:bg-blue-50/50 transition-colors duration-200 whitespace-nowrap overflow-hidden"
onClick={() => handleRowClick(row, mes)}
title={row.percentuaisPorMes && row.percentuaisPorMes[mes] !== undefined ? `${row.percentuaisPorMes[mes].toFixed(1)}%` : '-'}
>
{row.percentuaisPorMes && row.percentuaisPorMes[mes] !== undefined
? `${row.percentuaisPorMes[mes].toFixed(1)}%`
: '-'}
</div>
2025-10-08 04:45:26 +00:00
</div>
))}
2025-10-08 05:30:37 +00:00
<div
className="flex-1 min-w-[120px] text-right font-semibold cursor-pointer hover:bg-blue-50/50 transition-colors duration-200 whitespace-nowrap overflow-hidden"
2025-10-08 05:30:37 +00:00
onClick={() => handleRowClick(row)}
title={row.total ? formatCurrency(row.total) : '-'}
2025-10-08 05:30:37 +00:00
>
2025-10-08 12:28:20 +00:00
{(() => {
const { formatted, isNegative } = formatCurrencyWithColor(row.total!);
2025-10-08 12:28:20 +00:00
return (
<span className={isNegative ? 'text-red-600 font-bold' : 'text-gray-900'}>
2025-10-08 12:28:20 +00:00
{formatted}
</span>
);
})()}
2025-10-08 04:45:26 +00:00
</div>
</div>
))}
</div>
2025-10-08 04:26:38 +00:00
</div>
{/* Componente Analítico */}
{!loading && data.length > 0 && (
<AnaliticoComponent filtros={analiticoFiltros} />
)}
2025-10-08 04:19:15 +00:00
</div>
);
}