riseup-squad18/MEDICONNECT 2/scripts/atribuir-guilherme-fernando.js

187 lines
5.9 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.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Script para atribuir o paciente Guilherme ao Fernando
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";
// Fernando user ID
const FERNANDO_USER_ID = "be1e3cba-534e-48c3-9590-b7e55861cade";
// Guilherme patient ID (do teste anterior)
const GUILHERME_ID = "864b1785-461f-4e92-8b74-2a6f17c58a80";
const GUILHERME_NOME = "Guilherme Silva Gomes - SQUAD 18";
async function atribuirGuilherme() {
try {
console.log("\n🔐 === ATRIBUIR GUILHERME AO FERNANDO ===\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} - ${await loginResponse.text()}`
);
}
const loginData = await loginResponse.json();
const accessToken = loginData.access_token;
const adminUserId = loginData.user.id;
console.log(`✅ Login admin realizado!`);
console.log(` Admin User ID: ${adminUserId}`);
// 2. Verificar se a atribuição já existe
console.log(`\n2⃣ Verificando atribuições existentes...`);
const checkResponse = await fetch(
`${SUPABASE_URL}/rest/v1/patient_assignments?user_id=eq.${FERNANDO_USER_ID}&patient_id=eq.${GUILHERME_ID}`,
{
headers: {
apikey: SUPABASE_ANON_KEY,
Authorization: `Bearer ${accessToken}`,
},
}
);
if (checkResponse.ok) {
const existing = await checkResponse.json();
if (existing.length > 0) {
console.log(`⚠️ Atribuição já existe!`);
console.log(` Assignment ID: ${existing[0].id}`);
console.log(` Criado em: ${existing[0].created_at}`);
console.log(`\n✅ Guilherme já está atribuído ao Fernando!`);
return;
}
}
console.log(` Nenhuma atribuição existente encontrada.`);
// 3. Criar nova atribuição
console.log(`\n3⃣ Criando nova atribuição...`);
console.log(` Paciente: ${GUILHERME_NOME}`);
console.log(` Médico: Fernando (${FERNANDO_USER_ID})`);
const atribuicao = {
patient_id: GUILHERME_ID,
user_id: FERNANDO_USER_ID,
role: "medico",
created_by: adminUserId,
};
const createResponse = await fetch(
`${SUPABASE_URL}/rest/v1/patient_assignments`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
apikey: SUPABASE_ANON_KEY,
Authorization: `Bearer ${accessToken}`,
Prefer: "return=representation",
},
body: JSON.stringify(atribuicao),
}
);
if (!createResponse.ok) {
const errorText = await createResponse.text();
throw new Error(
`Erro ao criar atribuição: ${createResponse.status} - ${errorText}`
);
}
const result = await createResponse.json();
const assignment = Array.isArray(result) ? result[0] : result;
console.log(`✅ Atribuição criada com sucesso!`);
console.log(` Assignment ID: ${assignment.id}`);
console.log(` Patient ID: ${assignment.patient_id}`);
console.log(` User ID: ${assignment.user_id}`);
console.log(` Role: ${assignment.role}`);
console.log(` Created At: ${assignment.created_at}`);
// 4. Verificar todas as atribuições do Fernando
console.log(`\n4⃣ Verificando todas as atribuições do Fernando...`);
const allAssignmentsResponse = await fetch(
`${SUPABASE_URL}/rest/v1/patient_assignments?user_id=eq.${FERNANDO_USER_ID}&select=*`,
{
headers: {
apikey: SUPABASE_ANON_KEY,
Authorization: `Bearer ${accessToken}`,
},
}
);
if (allAssignmentsResponse.ok) {
const assignments = await allAssignmentsResponse.json();
console.log(
`✅ Fernando possui ${assignments.length} paciente(s) atribuído(s):`
);
for (let i = 0; i < assignments.length; i++) {
const a = assignments[i];
// Buscar nome do paciente
const patientResponse = await fetch(
`${SUPABASE_URL}/rest/v1/patients?id=eq.${a.patient_id}&select=full_name`,
{
headers: {
apikey: SUPABASE_ANON_KEY,
Authorization: `Bearer ${accessToken}`,
},
}
);
let patientName = "Nome não encontrado";
if (patientResponse.ok) {
const patients = await patientResponse.json();
if (patients.length > 0) {
patientName = patients[0].full_name;
}
}
console.log(` ${i + 1}. ${patientName}`);
console.log(` ID: ${a.patient_id}`);
console.log(` Role: ${a.role}`);
}
}
console.log(`\n🎉 SUCESSO!`);
console.log(` Guilherme agora está atribuído ao Fernando!`);
console.log(` Fernando pode vê-lo no painel médico.`);
console.log(`\n Para testar:`);
console.log(
` 1. Faça login: fernando.pirichowski@souunit.com.br / fernando`
);
console.log(` 2. Acesse o painel médico`);
console.log(` 3. Clique em "Novo Relatório"`);
console.log(` 4. Guilherme deve aparecer na lista de pacientes!`);
} catch (error) {
console.error("\n❌ Erro:", error);
if (error instanceof Error) {
console.error(" Mensagem:", error.message);
}
}
}
// Executar
atribuirGuilherme();