riseup-squad18/MEDICONNECT 2/scripts/criar-dados-teste.js

182 lines
5.3 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import fetch from "node-fetch";
const SUPABASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
const SUPABASE_ANON_KEY =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
// Credenciais admin para realizar INSERTs autenticados (RLS exige usuário autenticado)
const ADMIN_EMAIL = process.env.TEST_ADMIN_EMAIL || "riseup@popcode.com.br";
const ADMIN_PASSWORD =
process.env.TEST_ADMIN_PASSWORD || "riseup";
console.log("\n🔧 CRIANDO DADOS DE TESTE\n");
async function loginAdmin() {
console.log("🔐 Fazendo login como admin para inserir dados (RLS)...");
const res = await fetch(
`${SUPABASE_URL}/auth/v1/token?grant_type=password`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
apikey: SUPABASE_ANON_KEY,
},
body: JSON.stringify({ email: ADMIN_EMAIL, password: ADMIN_PASSWORD }),
}
);
if (!res.ok) {
const txt = await res.text();
throw new Error(`Falha no login admin (${res.status}): ${txt}`);
}
const data = await res.json();
console.log("✅ Login admin OK\n");
return data.access_token;
}
async function criarMedicoTeste(adminToken) {
console.log("👨‍⚕️ Criando médico de teste...");
const medico = {
full_name: "Dr. João Silva",
email: "drjoao@mediconnect.com",
crm: "12345",
crm_uf: "SE",
specialty: "Cardiologia",
phone_mobile: "79999999999",
cpf: "12345678900",
active: true,
};
try {
const response = await fetch(`${SUPABASE_URL}/rest/v1/doctors`, {
method: "POST",
headers: {
apikey: SUPABASE_ANON_KEY,
"Content-Type": "application/json",
// IMPORTANTE: usar token do admin autenticado para permitir INSERT (RLS)
Authorization: `Bearer ${adminToken}`,
Prefer: "return=representation",
},
body: JSON.stringify(medico),
});
if (response.ok) {
const data = await response.json();
console.log("✅ Médico criado com sucesso!");
console.log(" ID:", data[0]?.id);
console.log(" Nome:", data[0]?.full_name);
return data[0];
} else {
console.log("❌ Erro ao criar médico:", response.status);
const error = await response.text();
console.log(error);
return null;
}
} catch (error) {
console.error("❌ Erro:", error.message);
return null;
}
}
async function criarPacienteTeste(adminToken) {
console.log("\n👤 Criando paciente de teste...");
const paciente = {
full_name: "Maria Santos",
email: "maria@example.com",
phone_mobile: "79988888888",
cpf: "98765432100",
birth_date: "1990-05-15",
street: "Rua das Flores",
number: "100",
neighborhood: "Centro",
city: "Aracaju",
state: "SE",
cep: "49000-000",
};
try {
const response = await fetch(`${SUPABASE_URL}/rest/v1/patients`, {
method: "POST",
headers: {
apikey: SUPABASE_ANON_KEY,
"Content-Type": "application/json",
// IMPORTANTE: usar token do admin autenticado para permitir INSERT (RLS)
Authorization: `Bearer ${adminToken}`,
Prefer: "return=representation",
},
body: JSON.stringify(paciente),
});
if (response.ok) {
const data = await response.json();
console.log("✅ Paciente criado com sucesso!");
console.log(" ID:", data[0]?.id);
console.log(" Nome:", data[0]?.full_name);
return data[0];
} else {
console.log("❌ Erro ao criar paciente:", response.status);
const error = await response.text();
console.log(error);
if (response.status === 403 || response.status === 401) {
console.log("\n⚠ RLS está bloqueando a inserção anônima!");
console.log(" Você precisa:");
console.log(" 1. Criar uma política RLS que permita INSERT público");
console.log(
" 2. Ou usar a service_role key (não recomendado para front-end)"
);
console.log(
" 3. Ou criar através da interface de cadastro (com autenticação)"
);
}
return null;
}
} catch (error) {
console.error("❌ Erro:", error.message);
return null;
}
}
async function criar() {
const adminToken = await loginAdmin();
await criarMedicoTeste(adminToken);
await criarPacienteTeste(adminToken);
console.log("\n\n📊 VERIFICANDO RESULTADOS...\n");
// Verificar médicos
const respMedicos = await fetch(`${SUPABASE_URL}/rest/v1/doctors?select=*`, {
headers: {
apikey: SUPABASE_ANON_KEY,
Authorization: `Bearer ${SUPABASE_ANON_KEY}`,
},
});
if (respMedicos.ok) {
const medicos = await respMedicos.json();
console.log(`✅ Médicos cadastrados: ${medicos.length}`);
}
// Verificar pacientes
const respPacientes = await fetch(
`${SUPABASE_URL}/rest/v1/patients?select=*`,
{
headers: {
apikey: SUPABASE_ANON_KEY,
Authorization: `Bearer ${SUPABASE_ANON_KEY}`,
},
}
);
if (respPacientes.ok) {
const pacientes = await respPacientes.json();
console.log(`✅ Pacientes cadastrados: ${pacientes.length}`);
}
console.log("\n✨ Pronto! Agora os painéis devem mostrar os dados.\n");
}
criar();