Fix: Debug transaction fetching
Added more debug logs to `src/services/transacao/transacaoFetchService.ts` to investigate why transactions are not loading for specific users, including the user's email and `rodrigobm10@gmail.com`.
This commit is contained in:
parent
b82aced699
commit
0532e16041
@ -28,99 +28,80 @@ export async function getTransacoes(monthFilter?: string): Promise<Transaction[]
|
||||
const groupIds = await getUserGroups(normalizedEmail);
|
||||
console.log(`👥 [getTransacoes] Encontrados ${groupIds.length} grupos vinculados ao usuário:`, groupIds);
|
||||
|
||||
// ===== VERIFICAÇÕES DE DEBUG =====
|
||||
|
||||
// 1. Verificar total de registros na tabela
|
||||
console.log("🔍 [DEBUG] Verificando total de registros na tabela transacoes...");
|
||||
const { data: totalCount, error: countError } = await supabase
|
||||
.from('transacoes')
|
||||
.select('*', { count: 'exact' });
|
||||
|
||||
if (countError) {
|
||||
console.error("❌ [DEBUG] Erro ao contar registros:", countError);
|
||||
} else {
|
||||
console.log("📊 [DEBUG] Total de registros na tabela transacoes:", totalCount?.length || 0);
|
||||
}
|
||||
|
||||
// 2. Verificar registros com o email específico
|
||||
console.log("🔍 [DEBUG] Verificando registros para o email específico...");
|
||||
const { data: emailData, error: emailError } = await supabase
|
||||
// ===== TESTE DIRETO SEM FILTROS =====
|
||||
console.log("🧪 [DEBUG] Testando query direta para o email...");
|
||||
const { data: directEmailTest, error: directEmailError } = await supabase
|
||||
.from('transacoes')
|
||||
.select('*')
|
||||
.eq('login', normalizedEmail);
|
||||
|
||||
if (emailError) {
|
||||
console.error("❌ [DEBUG] Erro ao buscar por email:", emailError);
|
||||
} else {
|
||||
console.log("📧 [DEBUG] Registros encontrados para o email:", emailData?.length || 0);
|
||||
if (emailData && emailData.length > 0) {
|
||||
console.log("📧 [DEBUG] Primeiro registro encontrado:", emailData[0]);
|
||||
}
|
||||
console.log("🧪 [DEBUG] Resultado query direta:", directEmailTest?.length || 0, "registros");
|
||||
if (directEmailError) {
|
||||
console.error("🧪 [DEBUG] Erro na query direta:", directEmailError);
|
||||
}
|
||||
|
||||
// 3. Verificar todos os emails únicos na tabela
|
||||
console.log("🔍 [DEBUG] Verificando todos os emails únicos na tabela...");
|
||||
const { data: uniqueEmails, error: uniqueError } = await supabase
|
||||
// ===== TESTE COM ILIKE PARA EMAILS CASE-INSENSITIVE =====
|
||||
console.log("🧪 [DEBUG] Testando query com ilike (case-insensitive)...");
|
||||
const { data: ilikeTest, error: ilikeError } = await supabase
|
||||
.from('transacoes')
|
||||
.select('login')
|
||||
.not('login', 'is', null);
|
||||
.select('*')
|
||||
.ilike('login', normalizedEmail);
|
||||
|
||||
if (uniqueError) {
|
||||
console.error("❌ [DEBUG] Erro ao buscar emails únicos:", uniqueError);
|
||||
} else {
|
||||
const emails = [...new Set(uniqueEmails?.map(item => item.login))];
|
||||
console.log("📧 [DEBUG] Emails únicos encontrados na tabela:", emails);
|
||||
console.log("📧 [DEBUG] Email procurado existe na lista?", emails.includes(normalizedEmail));
|
||||
console.log("🧪 [DEBUG] Resultado query ilike:", ilikeTest?.length || 0, "registros");
|
||||
if (ilikeError) {
|
||||
console.error("🧪 [DEBUG] Erro na query ilike:", ilikeError);
|
||||
}
|
||||
|
||||
// 4. Verificar registros por grupo_id
|
||||
if (groupIds.length > 0) {
|
||||
console.log("🔍 [DEBUG] Verificando registros por grupo_id...");
|
||||
const { data: groupData, error: groupError } = await supabase
|
||||
// ===== TESTE COM TRIM =====
|
||||
console.log("🧪 [DEBUG] Testando diferentes variações do email...");
|
||||
const emailVariations = [
|
||||
normalizedEmail,
|
||||
normalizedEmail.trim(),
|
||||
normalizedEmail.toLowerCase(),
|
||||
normalizedEmail.toUpperCase()
|
||||
];
|
||||
|
||||
for (const emailVar of emailVariations) {
|
||||
const { data: varTest } = await supabase
|
||||
.from('transacoes')
|
||||
.select('*')
|
||||
.in('grupo_id', groupIds);
|
||||
.eq('login', emailVar)
|
||||
.limit(1);
|
||||
|
||||
if (groupError) {
|
||||
console.error("❌ [DEBUG] Erro ao buscar por grupo_id:", groupError);
|
||||
} else {
|
||||
console.log("👥 [DEBUG] Registros encontrados por grupo_id:", groupData?.length || 0);
|
||||
if (groupData && groupData.length > 0) {
|
||||
console.log("👥 [DEBUG] Primeiro registro por grupo:", groupData[0]);
|
||||
}
|
||||
}
|
||||
console.log(`🧪 [DEBUG] Email "${emailVar}": ${varTest?.length || 0} registros`);
|
||||
}
|
||||
|
||||
// ===== QUERY ORIGINAL =====
|
||||
// ===== QUERY ORIGINAL COM LOGS DETALHADOS =====
|
||||
console.log("🏗️ [getTransacoes] Iniciando query original...");
|
||||
|
||||
// Build the query with month filter if provided
|
||||
console.log("🏗️ [getTransacoes] Construindo query original...");
|
||||
let query = supabase.from('transacoes').select('*');
|
||||
|
||||
let query = supabase
|
||||
.from('transacoes')
|
||||
.select('*');
|
||||
// Log the filter being applied
|
||||
let filterDescription = "";
|
||||
|
||||
// Now let's build the proper filter
|
||||
if (groupIds.length > 0) {
|
||||
query = query.or(`login.eq.${normalizedEmail},grupo_id.in.(${groupIds.map(id => `"${id}"`).join(',')})`);
|
||||
console.log("🔍 [getTransacoes] Query com grupos:", `login.eq.${normalizedEmail},grupo_id.in.(${groupIds.map(id => `"${id}"`).join(',')})`);
|
||||
const orFilter = `login.eq.${normalizedEmail},grupo_id.in.(${groupIds.map(id => `"${id}"`).join(',')})`;
|
||||
filterDescription = `OR filter: ${orFilter}`;
|
||||
query = query.or(orFilter);
|
||||
} else {
|
||||
filterDescription = `Simple email filter: login = ${normalizedEmail}`;
|
||||
query = query.eq('login', normalizedEmail);
|
||||
console.log("🔍 [getTransacoes] Query apenas por email:", normalizedEmail);
|
||||
}
|
||||
|
||||
console.log("🔍 [getTransacoes] Filtro aplicado:", filterDescription);
|
||||
|
||||
// Apply month filter if provided
|
||||
if (monthFilter) {
|
||||
const startDate = `${monthFilter}-01`;
|
||||
const year = parseInt(monthFilter.split('-')[0]);
|
||||
const month = parseInt(monthFilter.split('-')[1]);
|
||||
const endDate = new Date(year, month, 0).toISOString().split('T')[0]; // Last day of the month
|
||||
const endDate = new Date(year, month, 0).toISOString().split('T')[0];
|
||||
|
||||
query = query
|
||||
.gte('quando', startDate)
|
||||
.lte('quando', `${endDate}T23:59:59.999Z`);
|
||||
|
||||
console.log(`📅 [getTransacoes] Aplicando filtro de mês: ${startDate} até ${endDate}`);
|
||||
console.log(`📅 [getTransacoes] Filtro de data aplicado: ${startDate} até ${endDate}`);
|
||||
}
|
||||
|
||||
query = query.order('quando', { ascending: false });
|
||||
@ -130,22 +111,31 @@ export async function getTransacoes(monthFilter?: string): Promise<Transaction[]
|
||||
|
||||
if (error) {
|
||||
console.error('❌ [getTransacoes] Erro ao executar query:', error);
|
||||
console.error('❌ [getTransacoes] Detalhes do erro:', JSON.stringify(error, null, 2));
|
||||
throw new Error('Não foi possível carregar as transações');
|
||||
}
|
||||
|
||||
console.log("✅ [getTransacoes] Transações encontradas:", data?.length || 0);
|
||||
console.log("📋 [getTransacoes] Dados retornados:", data);
|
||||
console.log("✅ [getTransacoes] Query executada com sucesso");
|
||||
console.log("📊 [getTransacoes] Número de registros retornados:", data?.length || 0);
|
||||
|
||||
if (data && data.length > 0) {
|
||||
console.log("📋 [getTransacoes] Primeiro registro retornado:", data[0]);
|
||||
console.log("📋 [getTransacoes] Estrutura dos dados:", Object.keys(data[0]));
|
||||
}
|
||||
|
||||
if (!data || data.length === 0) {
|
||||
console.warn("⚠️ [getTransacoes] Nenhuma transação encontrada para o usuário:", normalizedEmail);
|
||||
console.warn("⚠️ [getTransacoes] Nenhuma transação encontrada");
|
||||
console.warn("⚠️ [getTransacoes] Email buscado:", normalizedEmail);
|
||||
console.warn("⚠️ [getTransacoes] Filtro de mês:", monthFilter);
|
||||
console.warn("⚠️ [getTransacoes] Grupos do usuário:", groupIds);
|
||||
return [];
|
||||
}
|
||||
|
||||
// Transform the received data to the expected format, normalizing the types
|
||||
// Transform the received data to the expected format
|
||||
const transformedData = data.map((item: any) => ({
|
||||
id: item.id.toString(),
|
||||
user: item.user || '',
|
||||
login: item.login || normalizedEmail, // Ensure the login field is filled
|
||||
login: item.login || normalizedEmail,
|
||||
created_at: item.created_at,
|
||||
valor: item.tipo?.toLowerCase() === 'receita' ? Math.abs(item.valor || 0) : -Math.abs(item.valor || 0),
|
||||
quando: item.quando || new Date().toISOString(),
|
||||
@ -156,12 +146,13 @@ export async function getTransacoes(monthFilter?: string): Promise<Transaction[]
|
||||
grupo_id: item.grupo_id || null
|
||||
}));
|
||||
|
||||
console.log("🔄 [getTransacoes] Transações transformadas:", transformedData.length);
|
||||
console.log("🔄 [getTransacoes] Primeira transação transformada:", transformedData[0]);
|
||||
console.log("🔄 [getTransacoes] Dados transformados com sucesso");
|
||||
console.log("🔄 [getTransacoes] Total de transações processadas:", transformedData.length);
|
||||
|
||||
return transformedData;
|
||||
} catch (error) {
|
||||
console.error('💥 [getTransacoes] Erro geral na função:', error);
|
||||
console.error('💥 [getTransacoes] Stack trace:', error instanceof Error ? error.stack : 'Stack não disponível');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user