414 lines
13 KiB
JavaScript
414 lines
13 KiB
JavaScript
/**
|
||
* Script completo para criar usuário Guilherme com role "user"
|
||
* Email: guilhermesilvagomes1020@gmail.com
|
||
* Telefone: 79999521847
|
||
*/
|
||
|
||
const SUPABASE_URL = "https://yuanqfswhberkoevtmfr.supabase.co";
|
||
const SUPABASE_ANON_KEY =
|
||
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inl1YW5xZnN3aGJlcmtvZXZ0bWZyIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTQ5NTQzNjksImV4cCI6MjA3MDUzMDM2OX0.g8Fm4XAvtX46zifBZnYVH4tVuQkqUH6Ia9CXQj4DztQ";
|
||
|
||
// Admin credentials
|
||
const ADMIN_EMAIL = "riseup@popcode.com.br";
|
||
const ADMIN_PASSWORD = "riseup";
|
||
|
||
// Guilherme dados atualizados
|
||
const GUILHERME_EMAIL = "guilhermesilvagomes1020@gmail.com";
|
||
const GUILHERME_PASSWORD = "guilherme123";
|
||
const GUILHERME_NOME = "Guilherme Silva Gomes - SQUAD 18";
|
||
const GUILHERME_TELEFONE = "79999521847";
|
||
const GUILHERME_CPF = "11144477735"; // CPF válido para teste
|
||
|
||
// Fernando dados
|
||
const FERNANDO_USER_ID = "be1e3cba-534e-48c3-9590-b7e55861cade";
|
||
const FERNANDO_NOME = "Fernando Pirichowski - Squad 18";
|
||
|
||
async function criarGuilhermeCompleto() {
|
||
try {
|
||
console.log("\n🔐 === CRIAR GUILHERME COMPLETO ===\n");
|
||
|
||
// 1. Login como admin
|
||
console.log("1️⃣ Fazendo login como admin...");
|
||
const loginResponse = 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 (!loginResponse.ok) {
|
||
throw new Error(`Erro no login: ${loginResponse.status}`);
|
||
}
|
||
|
||
const loginData = await loginResponse.json();
|
||
const adminToken = loginData.access_token;
|
||
console.log("✅ Login admin realizado!\n");
|
||
|
||
// 2. Criar paciente Guilherme
|
||
console.log("2️⃣ Criando paciente Guilherme...");
|
||
console.log(` Nome: ${GUILHERME_NOME}`);
|
||
console.log(` Email: ${GUILHERME_EMAIL}`);
|
||
console.log(` Telefone: ${GUILHERME_TELEFONE}`);
|
||
console.log(` CPF: ${GUILHERME_CPF}\n`);
|
||
|
||
// Verificar se paciente já existe
|
||
const checkPatientResponse = await fetch(
|
||
`${SUPABASE_URL}/rest/v1/patients?email=eq.${encodeURIComponent(
|
||
GUILHERME_EMAIL
|
||
)}`,
|
||
{
|
||
headers: {
|
||
apikey: SUPABASE_ANON_KEY,
|
||
Authorization: `Bearer ${adminToken}`,
|
||
},
|
||
}
|
||
);
|
||
|
||
let existingPatients = await checkPatientResponse.json();
|
||
let guilhermePatientId;
|
||
|
||
// Verificar por email ou CPF
|
||
if (!existingPatients || existingPatients.length === 0) {
|
||
const checkByCpfResponse = await fetch(
|
||
`${SUPABASE_URL}/rest/v1/patients?cpf=eq.${GUILHERME_CPF}`,
|
||
{
|
||
headers: {
|
||
apikey: SUPABASE_ANON_KEY,
|
||
Authorization: `Bearer ${adminToken}`,
|
||
},
|
||
}
|
||
);
|
||
existingPatients = await checkByCpfResponse.json();
|
||
}
|
||
|
||
if (existingPatients && existingPatients.length > 0) {
|
||
guilhermePatientId = existingPatients[0].id;
|
||
console.log("✅ Paciente já existe!");
|
||
console.log(` Patient ID: ${guilhermePatientId}`);
|
||
console.log(` Nome: ${existingPatients[0].full_name}`);
|
||
console.log(` Email: ${existingPatients[0].email}\n`);
|
||
} else {
|
||
// Criar paciente
|
||
const createPatientResponse = await fetch(
|
||
`${SUPABASE_URL}/rest/v1/patients`,
|
||
{
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
Authorization: `Bearer ${adminToken}`,
|
||
apikey: SUPABASE_ANON_KEY,
|
||
Prefer: "return=representation",
|
||
},
|
||
body: JSON.stringify({
|
||
full_name: GUILHERME_NOME,
|
||
email: GUILHERME_EMAIL,
|
||
phone_mobile: GUILHERME_TELEFONE,
|
||
cpf: GUILHERME_CPF,
|
||
birth_date: "2000-10-20",
|
||
sex: "M",
|
||
}),
|
||
}
|
||
);
|
||
|
||
if (!createPatientResponse.ok) {
|
||
const error = await createPatientResponse.text();
|
||
console.error("❌ Erro ao criar paciente:", error);
|
||
throw new Error(error);
|
||
}
|
||
|
||
const patientData = await createPatientResponse.json();
|
||
guilhermePatientId = patientData[0]?.id || patientData.id;
|
||
console.log("✅ Paciente criado!");
|
||
console.log(` Patient ID: ${guilhermePatientId}\n`);
|
||
}
|
||
|
||
// 3. Criar usuário com role "user"
|
||
console.log("3️⃣ Criando usuário com role 'user'...");
|
||
console.log(` Email: ${GUILHERME_EMAIL}`);
|
||
console.log(` Senha: ${GUILHERME_PASSWORD}`);
|
||
console.log(` Role: user\n`);
|
||
|
||
// Verificar se usuário já existe
|
||
try {
|
||
const checkUserLogin = 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: GUILHERME_EMAIL,
|
||
password: GUILHERME_PASSWORD,
|
||
}),
|
||
}
|
||
);
|
||
|
||
if (checkUserLogin.ok) {
|
||
const userData = await checkUserLogin.json();
|
||
console.log("✅ Usuário já existe!");
|
||
console.log(` User ID: ${userData.user.id}\n`);
|
||
|
||
// Atribuir paciente ao usuário
|
||
await atribuirPaciente(
|
||
adminToken,
|
||
userData.user.id,
|
||
guilhermePatientId
|
||
);
|
||
await criarConsultas(guilhermePatientId);
|
||
mostrarResumo();
|
||
return;
|
||
}
|
||
} catch (e) {
|
||
console.log("ℹ️ Usuário não existe, criando...\n");
|
||
}
|
||
|
||
// Criar usuário via Edge Function
|
||
const createUserResponse = await fetch(
|
||
`${SUPABASE_URL}/functions/v1/create-user`,
|
||
{
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
Authorization: `Bearer ${adminToken}`,
|
||
apikey: SUPABASE_ANON_KEY,
|
||
},
|
||
body: JSON.stringify({
|
||
email: GUILHERME_EMAIL,
|
||
password: GUILHERME_PASSWORD,
|
||
full_name: GUILHERME_NOME,
|
||
role: "user",
|
||
}),
|
||
}
|
||
);
|
||
|
||
const createUserText = await createUserResponse.text();
|
||
console.log(" Resposta da criação:", createUserText);
|
||
|
||
let createUserData;
|
||
try {
|
||
createUserData = JSON.parse(createUserText);
|
||
} catch (e) {
|
||
console.error("❌ Erro ao parsear resposta:", createUserText);
|
||
throw new Error("Resposta inválida da API");
|
||
}
|
||
|
||
if (!createUserResponse.ok) {
|
||
console.error("❌ Erro ao criar usuário:", createUserData);
|
||
throw new Error(JSON.stringify(createUserData));
|
||
}
|
||
|
||
// Tentar obter user_id de várias formas
|
||
let guilhermeUserId =
|
||
createUserData.user_id ||
|
||
createUserData.id ||
|
||
createUserData.userId ||
|
||
createUserData.user?.id;
|
||
|
||
if (!guilhermeUserId) {
|
||
// Tentar fazer login para obter o ID
|
||
console.log(" Tentando obter ID via login...");
|
||
const loginGuilherme = 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: GUILHERME_EMAIL,
|
||
password: GUILHERME_PASSWORD,
|
||
}),
|
||
}
|
||
);
|
||
|
||
if (loginGuilherme.ok) {
|
||
const loginData = await loginGuilherme.json();
|
||
guilhermeUserId = loginData.user.id;
|
||
}
|
||
}
|
||
|
||
if (!guilhermeUserId) {
|
||
console.error("❌ Não foi possível obter o User ID!");
|
||
console.error(" Resposta:", createUserData);
|
||
throw new Error("User ID não disponível");
|
||
}
|
||
|
||
console.log("✅ Usuário criado com sucesso!");
|
||
console.log(` User ID: ${guilhermeUserId}\n`);
|
||
|
||
// 4. Atribuir paciente ao usuário
|
||
await atribuirPaciente(adminToken, guilhermeUserId, guilhermePatientId);
|
||
|
||
// 5. Criar consultas
|
||
await criarConsultas(guilhermePatientId);
|
||
|
||
// 6. Mostrar resumo
|
||
mostrarResumo();
|
||
} catch (error) {
|
||
console.error("\n❌ ERRO:", error.message);
|
||
if (error.stack) {
|
||
console.error(error.stack);
|
||
}
|
||
process.exit(1);
|
||
}
|
||
}
|
||
|
||
async function atribuirPaciente(adminToken, userId, patientId) {
|
||
console.log("4️⃣ Atribuindo paciente ao usuário...");
|
||
|
||
// Verificar se atribuição já existe
|
||
const checkResponse = await fetch(
|
||
`${SUPABASE_URL}/rest/v1/patient_assignments?user_id=eq.${userId}&patient_id=eq.${patientId}`,
|
||
{
|
||
headers: {
|
||
apikey: SUPABASE_ANON_KEY,
|
||
Authorization: `Bearer ${adminToken}`,
|
||
},
|
||
}
|
||
);
|
||
|
||
const existing = await checkResponse.json();
|
||
|
||
if (existing && existing.length > 0) {
|
||
console.log("✅ Atribuição já existe!\n");
|
||
return;
|
||
}
|
||
|
||
// Criar atribuição
|
||
const assignResponse = await fetch(
|
||
`${SUPABASE_URL}/rest/v1/patient_assignments`,
|
||
{
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
Authorization: `Bearer ${adminToken}`,
|
||
apikey: SUPABASE_ANON_KEY,
|
||
Prefer: "return=representation",
|
||
},
|
||
body: JSON.stringify({
|
||
user_id: userId,
|
||
patient_id: patientId,
|
||
role: "user", // Adicionar role na atribuição
|
||
}),
|
||
}
|
||
);
|
||
|
||
if (!assignResponse.ok) {
|
||
const error = await assignResponse.text();
|
||
console.error("⚠️ Erro ao criar atribuição:", error);
|
||
} else {
|
||
console.log("✅ Paciente atribuído ao usuário!\n");
|
||
}
|
||
}
|
||
|
||
async function criarConsultas(guilhermePatientId) {
|
||
console.log("5️⃣ Criando consultas de demonstração...\n");
|
||
|
||
const consultas = [
|
||
{
|
||
id: "consulta-demo-guilherme-001",
|
||
pacienteId: guilhermePatientId,
|
||
medicoId: FERNANDO_USER_ID,
|
||
pacienteNome: GUILHERME_NOME,
|
||
medicoNome: FERNANDO_NOME,
|
||
dataHora: "2025-10-05T10:00:00",
|
||
status: "agendada",
|
||
tipo: "Consulta",
|
||
observacoes: "Primeira consulta - Check-up geral",
|
||
},
|
||
{
|
||
id: "consulta-demo-guilherme-002",
|
||
pacienteId: guilhermePatientId,
|
||
medicoId: FERNANDO_USER_ID,
|
||
pacienteNome: GUILHERME_NOME,
|
||
medicoNome: FERNANDO_NOME,
|
||
dataHora: "2025-09-28T14:30:00",
|
||
status: "realizada",
|
||
tipo: "Retorno",
|
||
observacoes: "Consulta de retorno - Avaliação de exames",
|
||
},
|
||
{
|
||
id: "consulta-demo-guilherme-003",
|
||
pacienteId: guilhermePatientId,
|
||
medicoId: FERNANDO_USER_ID,
|
||
pacienteNome: GUILHERME_NOME,
|
||
medicoNome: FERNANDO_NOME,
|
||
dataHora: "2025-10-10T09:00:00",
|
||
status: "confirmada",
|
||
tipo: "Consulta",
|
||
observacoes: "Consulta de acompanhamento mensal",
|
||
},
|
||
];
|
||
|
||
// Usar import dinâmico para módulos ES
|
||
const fs = await import("fs");
|
||
const path = await import("path");
|
||
const { fileURLToPath } = await import("url");
|
||
const { dirname } = await import("path");
|
||
|
||
const __filename = fileURLToPath(import.meta.url);
|
||
const __dirname = dirname(__filename);
|
||
|
||
const dataDir = path.join(__dirname, "..", "src", "data");
|
||
|
||
if (!fs.existsSync(dataDir)) {
|
||
fs.mkdirSync(dataDir, { recursive: true });
|
||
console.log(" 📁 Diretório src/data criado");
|
||
}
|
||
|
||
const consultasPath = path.join(dataDir, "consultas-demo.json");
|
||
fs.writeFileSync(consultasPath, JSON.stringify(consultas, null, 2));
|
||
|
||
console.log(" ✅ Consultas salvas em src/data/consultas-demo.json");
|
||
console.log(` 📊 ${consultas.length} consultas criadas:`);
|
||
consultas.forEach((c, i) => {
|
||
console.log(` ${i + 1}. ${c.dataHora} - ${c.status} - ${c.tipo}`);
|
||
});
|
||
console.log();
|
||
}
|
||
|
||
function mostrarResumo() {
|
||
console.log("\n✅ === CONFIGURAÇÃO CONCLUÍDA COM SUCESSO! ===\n");
|
||
console.log("📋 CREDENCIAIS DE LOGIN:\n");
|
||
console.log(" Email: guilhermesilvagomes1020@gmail.com");
|
||
console.log(" Senha: guilherme123");
|
||
console.log(" Role: user (acesso ao painel paciente)\n");
|
||
console.log("📱 DADOS DO PACIENTE:\n");
|
||
console.log(" Nome: Guilherme Silva Gomes - SQUAD 18");
|
||
console.log(" Telefone: 79999521847");
|
||
console.log(" Médico: Fernando Pirichowski - Squad 18\n");
|
||
console.log("🔗 PRÓXIMOS PASSOS:\n");
|
||
console.log(" 1. Acesse http://localhost:5173/paciente no navegador");
|
||
console.log(
|
||
" 2. Faça login com: guilhermesilvagomes1020@gmail.com / guilherme123"
|
||
);
|
||
console.log(" 3. Você verá o painel do paciente com as consultas");
|
||
console.log(" 4. As consultas também aparecem no painel do Dr. Fernando");
|
||
console.log(" 5. E no painel da secretária\n");
|
||
console.log("💡 PARA CARREGAR AS CONSULTAS NO NAVEGADOR:\n");
|
||
console.log(" - Abra o console (F12)");
|
||
console.log(
|
||
" - Execute: fetch('/src/data/consultas-demo.json').then(r=>r.json()).then(c=>{"
|
||
);
|
||
console.log(
|
||
" localStorage.setItem('consultas_local', JSON.stringify(c));"
|
||
);
|
||
console.log(" location.reload();");
|
||
console.log(" })");
|
||
console.log();
|
||
}
|
||
|
||
// Executar
|
||
criarGuilhermeCompleto();
|