196 lines
6.2 KiB
JavaScript
196 lines
6.2 KiB
JavaScript
/**
|
||
* Script para testar a criação de relatórios na API
|
||
* Verifica se a tabela reports existe e testa criação de relatório
|
||
*/
|
||
|
||
import axios from "axios";
|
||
|
||
const SUPABASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
|
||
const SUPABASE_ANON_KEY =
|
||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
|
||
|
||
// Credenciais do médico Fernando
|
||
const FERNANDO_EMAIL = "fernando.pirichowski@souunit.com.br";
|
||
const FERNANDO_PASSWORD = "fernando";
|
||
|
||
async function main() {
|
||
try {
|
||
console.log("🔐 Fazendo login como médico Fernando...\n");
|
||
|
||
// 1. Login do médico
|
||
const loginResponse = await axios.post(
|
||
`${SUPABASE_URL}/auth/v1/token?grant_type=password`,
|
||
{
|
||
email: FERNANDO_EMAIL,
|
||
password: FERNANDO_PASSWORD,
|
||
},
|
||
{
|
||
headers: {
|
||
apikey: SUPABASE_ANON_KEY,
|
||
"Content-Type": "application/json",
|
||
},
|
||
}
|
||
);
|
||
|
||
const token = loginResponse.data.access_token;
|
||
const userId = loginResponse.data.user.id;
|
||
|
||
console.log("✅ Login realizado com sucesso!");
|
||
console.log(` User ID: ${userId}\n`);
|
||
|
||
// 2. Verificar se tabela reports existe
|
||
console.log("🔍 Verificando se tabela reports existe...\n");
|
||
|
||
try {
|
||
const checkTableResponse = await axios.get(
|
||
`${SUPABASE_URL}/rest/v1/reports?select=id&limit=1`,
|
||
{
|
||
headers: {
|
||
apikey: SUPABASE_ANON_KEY,
|
||
Authorization: `Bearer ${token}`,
|
||
},
|
||
}
|
||
);
|
||
|
||
console.log("✅ Tabela reports existe!");
|
||
console.log(
|
||
` Registros encontrados: ${checkTableResponse.data.length}\n`
|
||
);
|
||
} catch (error) {
|
||
if (error.response?.status === 404) {
|
||
console.log("❌ ERRO: Tabela reports NÃO existe no Supabase!\n");
|
||
console.log(
|
||
"💡 SOLUÇÃO: Execute o SQL abaixo no Supabase SQL Editor:\n"
|
||
);
|
||
console.log("```sql");
|
||
console.log(`CREATE TABLE IF NOT EXISTS public.reports (
|
||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||
titulo TEXT NOT NULL,
|
||
tipo TEXT CHECK (tipo IN ('consultas', 'pacientes', 'financeiro', 'medicos')) NOT NULL,
|
||
descricao TEXT,
|
||
data_inicio DATE NOT NULL,
|
||
data_fim DATE NOT NULL,
|
||
dados JSONB DEFAULT '{}'::jsonb,
|
||
gerado_por UUID REFERENCES auth.users(id),
|
||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||
);
|
||
|
||
-- Habilitar RLS
|
||
ALTER TABLE public.reports ENABLE ROW LEVEL SECURITY;
|
||
|
||
-- Políticas de acesso
|
||
CREATE POLICY "reports_select_authenticated" ON public.reports
|
||
FOR SELECT TO authenticated USING (true);
|
||
|
||
CREATE POLICY "reports_insert_authenticated" ON public.reports
|
||
FOR INSERT TO authenticated WITH CHECK (true);
|
||
|
||
CREATE POLICY "reports_update_own" ON public.reports
|
||
FOR UPDATE TO authenticated USING (gerado_por = auth.uid());
|
||
|
||
CREATE POLICY "reports_delete_own" ON public.reports
|
||
FOR DELETE TO authenticated USING (gerado_por = auth.uid());
|
||
\`\`\`\n`);
|
||
return;
|
||
}
|
||
throw error;
|
||
}
|
||
|
||
// 3. Criar relatório de teste
|
||
console.log("📝 Criando relatório de teste...\n");
|
||
|
||
const relatorioData = {
|
||
titulo: "Relatório de Teste - Consultas Outubro 2025",
|
||
tipo: "consultas",
|
||
descricao:
|
||
"Relatório gerado automaticamente para testar a funcionalidade",
|
||
data_inicio: "2025-10-01",
|
||
data_fim: "2025-10-31",
|
||
dados: {
|
||
medicoId: userId,
|
||
medicoNome: "Fernando Pirichowski - Squad 18",
|
||
totalConsultas: 0,
|
||
testScript: true,
|
||
},
|
||
gerado_por: userId,
|
||
};
|
||
|
||
const createResponse = await axios.post(
|
||
`${SUPABASE_URL}/rest/v1/reports`,
|
||
relatorioData,
|
||
{
|
||
headers: {
|
||
apikey: SUPABASE_ANON_KEY,
|
||
Authorization: `Bearer ${token}`,
|
||
"Content-Type": "application/json",
|
||
Prefer: "return=representation",
|
||
},
|
||
}
|
||
);
|
||
|
||
const relatorio = Array.isArray(createResponse.data)
|
||
? createResponse.data[0]
|
||
: createResponse.data;
|
||
|
||
console.log("✅ Relatório criado com sucesso!\n");
|
||
console.log("📋 Detalhes do relatório:");
|
||
console.log(` ID: ${relatorio.id}`);
|
||
console.log(` Título: ${relatorio.titulo}`);
|
||
console.log(` Tipo: ${relatorio.tipo}`);
|
||
console.log(` Período: ${relatorio.data_inicio} a ${relatorio.data_fim}`);
|
||
console.log(` Gerado por: ${relatorio.gerado_por}`);
|
||
console.log(` Criado em: ${relatorio.created_at}\n`);
|
||
|
||
// 4. Listar todos os relatórios
|
||
console.log("📊 Listando todos os relatórios...\n");
|
||
|
||
const listResponse = await axios.get(
|
||
`${SUPABASE_URL}/rest/v1/reports?select=*&order=created_at.desc`,
|
||
{
|
||
headers: {
|
||
apikey: SUPABASE_ANON_KEY,
|
||
Authorization: `Bearer ${token}`,
|
||
},
|
||
}
|
||
);
|
||
|
||
console.log(`Total de relatórios: ${listResponse.data.length}\n`);
|
||
listResponse.data.forEach((rel, index) => {
|
||
console.log(`${index + 1}. ${rel.titulo}`);
|
||
console.log(
|
||
` Tipo: ${rel.tipo} | Período: ${rel.data_inicio} a ${rel.data_fim}`
|
||
);
|
||
console.log(` Criado em: ${rel.created_at}\n`);
|
||
});
|
||
|
||
// 5. Resumo
|
||
console.log("✅ TESTE COMPLETO!\n");
|
||
console.log("🎉 Sistema de relatórios funcionando corretamente!");
|
||
console.log(
|
||
'✅ Botão "Novo Relatório" no painel médico está conectado à API\n'
|
||
);
|
||
} catch (error) {
|
||
console.error("❌ ERRO:", error.response?.data || error.message);
|
||
if (error.response) {
|
||
console.error("Status:", error.response.status);
|
||
|
||
if (error.response.status === 404) {
|
||
console.error("\n⚠️ Tabela reports não encontrada!");
|
||
console.error("Execute o SQL de criação da tabela mostrado acima.");
|
||
} else if (error.response.status === 401) {
|
||
console.error("\n⚠️ Erro de autenticação");
|
||
console.error("Verifique se o token JWT está válido");
|
||
} else if (error.response.status === 400) {
|
||
console.error("\n⚠️ Erro de validação");
|
||
console.error(
|
||
"Detalhes:",
|
||
JSON.stringify(error.response.data, null, 2)
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
main();
|