Spaces:
Sleeping
Sleeping
Download app.js from FelipeFavalli/behring-bjj-face-api: direct link, hf CLI and curl.
- Browser
- Download file 178 kB
-
https://huggingface.co/spaces/FelipeFavalli/behring-bjj-face-api/resolve/main/app.js
- Command line
-
hf download hf://spaces/FelipeFavalli/behring-bjj-face-api/app.js
-
curl -L -o app.js https://huggingface.co/spaces/FelipeFavalli/behring-bjj-face-api/resolve/main/app.js
178 kB
// Helper to initialize missing student fields
function initializeStudentFields(student) {
if (student.password === undefined) student.password = 'aluno123';
if (student.email === undefined) student.email = '';
if (student.whatsapp === undefined) student.whatsapp = '';
if (student.address === undefined) student.address = '';
if (student.age === undefined) student.age = 18;
if (student.faceEmbedding === undefined) student.faceEmbedding = null;
if (student.guardian === undefined) student.guardian = '';
if (student.objective === undefined) student.objective = '';
if (student.weeklyGoal === undefined) student.weeklyGoal = 3;
if (student.profession === undefined) student.profession = '';
if (student.schoolName === undefined) student.schoolName = '';
if (student.hasLoan === undefined) student.hasLoan = false;
if (student.kimonoBrand === undefined) student.kimonoBrand = '';
if (student.kimonoSize === undefined) student.kimonoSize = '';
if (student.kimonoDate === undefined) student.kimonoDate = '';
if (student.evaluationParents === undefined) student.evaluationParents = 'Pendente';
if (student.evaluationSchool === undefined) student.evaluationSchool = 'Pendente';
}
const ADULT_BELTS = ['Branca', 'Azul', 'Roxa', 'Marrom', 'Preta'];
const KIDS_BELTS = [
'Branca',
'Cinza e Branca',
'Cinza',
'Cinza e Preta',
'Amarela e Branca',
'Amarela',
'Amarela e Preta',
'Laranja e Branca',
'Laranja',
'Laranja e Preta',
'Verde e Branca',
'Verde',
'Verde e Preta'
];
// State Management with LocalStorage persistence
const DEFAULT_STUDENTS = [
{ id: 'lucas', name: 'Lucas Souza', email: 'lucas@email.com', whatsapp: '(35) 99999-0001', belt: 'Branca', degrees: 2, attendanceCount: 24, selfie: null, streak: 80, address: 'Rua das Flores, 123 - Centro', age: 15, guardian: 'Ana Souza', objective: 'Aprender defesa pessoal e ganhar disciplina', weeklyGoal: 3, profession: 'Estudante', schoolName: 'E.E. Pandiá Calógeras', hasLoan: true, kimonoBrand: 'Koral', kimonoSize: 'M2', kimonoDate: '2026-05-15' },
{ id: 'thiago', name: 'Thiago Behring', email: 'thiago@email.com', whatsapp: '(35) 99999-0002', belt: 'Azul', degrees: 1, attendanceCount: 52, selfie: 'preset_thiago', streak: 90, address: 'Av. Tiradentes, 45 - Alto', age: 22, guardian: '', objective: 'Focar em competição e condicionamento', weeklyGoal: 4, profession: 'Educador Físico', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'felipe', name: 'Felipe Santana', email: 'felipe@email.com', whatsapp: '(35) 99999-0003', belt: 'Roxa', degrees: 3, attendanceCount: 112, selfie: 'preset_felipe', streak: 95, address: 'Rua São Bento, 987 - Vista Alegre', age: 28, guardian: '', objective: 'Estilo de vida e evolução na arte marcial', weeklyGoal: 3, profession: 'Desenvolvedor', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'gabriela', name: 'Gabriela Lima', email: 'gabriela@email.com', whatsapp: '(35) 99999-0004', belt: 'Marrom', degrees: 0, attendanceCount: 198, selfie: null, streak: 65, address: 'Serrinha da Aliança, Km 4', age: 32, guardian: '', objective: 'Competir e um dia dar aulas', weeklyGoal: 2, profession: 'Veterinária', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'roberto', name: 'Roberto Alencar', email: 'roberto@email.com', whatsapp: '(35) 99999-0005', belt: 'Preta', degrees: 2, attendanceCount: 342, selfie: 'preset_roberto', streak: 85, address: 'Rua do Cruzeiro, 50 - Centro', age: 45, guardian: '', objective: 'Manter a saúde e passar a tradição adiante', weeklyGoal: 5, profession: 'Empresário', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'senpai_lucas', name: 'Senpai Lucas', email: 'senpai.lucas@email.com', whatsapp: '(35) 99999-0006', belt: 'Azul', degrees: 2, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 25, guardian: '', objective: 'Evolução técnica e auxílio nas aulas', weeklyGoal: 3, profession: 'Professor Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'senpai_marcelo', name: 'Senpai Marcelo', email: 'senpai.marcelo@email.com', whatsapp: '(35) 99999-0007', belt: 'Roxa', degrees: 1, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 27, guardian: '', objective: 'Evolução técnica e competição', weeklyGoal: 3, profession: 'Professor Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'senpai_maju', name: 'Senpai Maju', email: 'senpai.maju@email.com', whatsapp: '(35) 99999-0008', belt: 'Roxa', degrees: 2, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 23, guardian: '', objective: 'Evolução técnica e liderança feminina no tatame', weeklyGoal: 3, profession: 'Professora Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'senpai_rogerio', name: 'Senpai Rogério', email: 'senpai.rogerio@email.com', whatsapp: '(35) 99999-0009', belt: 'Roxa', degrees: 3, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 29, guardian: '', objective: 'Evolução técnica e auxílio nas aulas', weeklyGoal: 3, profession: 'Professor Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'senpai_felicio', name: 'Senpai Felício', email: 'senpai.felicio@email.com', whatsapp: '(35) 99999-0010', belt: 'Roxa', degrees: 2, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 26, guardian: '', objective: 'Evolução técnica e auxílio nas aulas', weeklyGoal: 3, profession: 'Professor Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'senpai_isadora', name: 'Senpai Isadora', email: 'senpai.isadora@email.com', whatsapp: '(35) 99999-0011', belt: 'Azul', degrees: 4, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 24, guardian: '', objective: 'Evolução técnica e liderança feminina no tatame', weeklyGoal: 3, profession: 'Professora Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' }
];
const DEFAULT_EVENTS = [
{ id: 1, title: 'Treino de Graduação e Defesa Pessoal', type: 'Treino', date: '2026-06-06', time: '10:00' },
{ id: 2, title: 'Seminário de Passagem de Guarda', type: 'Seminário', date: '2026-06-15', time: '19:30' },
{ id: 3, title: 'Exame Geral de Faixas', type: 'Graduação', date: '2026-07-04', time: '19:00' }
];
const DEFAULT_ANNOUNCEMENTS = [
{ id: 1, title: 'Patches da Associação Behring', content: 'Atenção alunos: para o próximo exame geral de faixas em Julho, todos os kimonos devem estar devidamente equipados com o patch oficial da associação Behring. Disponíveis na secretaria.', date: '2026-06-04' },
{ id: 2, title: 'Foco na Assiduidade', content: 'Lembramos a todos que a frequência é monitorada pelo app (check-in manual ou foto IA). A assiduidade é o critério principal para indicação aos graus nas faixas.', date: '2026-06-01' }
];
const DEFAULT_HISTORY = [
{ date: '2026-06-03', time: '19:15', studentId: 'lucas', studentName: 'Lucas Souza', belt: 'Branca', method: 'manual' },
{ date: '2026-06-03', time: '19:10', studentId: 'thiago', studentName: 'Thiago Behring', belt: 'Azul', method: 'ia' },
{ date: '2026-06-03', time: '19:10', studentId: 'felipe', studentName: 'Felipe Santana', belt: 'Roxa', method: 'ia' },
{ date: '2026-06-02', time: '19:05', studentId: 'lucas', studentName: 'Lucas Souza', belt: 'Branca', method: 'manual' },
{ date: '2026-06-02', time: '19:05', studentId: 'gabriela', studentName: 'Gabriela Lima', belt: 'Marrom', method: 'manual' }
];
const DEFAULT_BJJ_HISTORY = {
text: `A história do Jiu-Jitsu no Brasil começou no início do século XX. O mestre japonês Mitsuyo Maeda, conhecido como "Conde Koma", chegou ao Brasil em 1914. Ele viajou demonstrando o Kodokan Judo (então chamado de Jiu-Jitsu Kano ou simplesmente Jiu-Jitsu).
Em Belém do Pará, Maeda conheceu Carlos Gracie. Carlos se interessou pelas demonstrações de Maeda e tornou-se seu aluno. Carlos ensinou a seus irmãos, incluindo Oswaldo, Gastão Jr., Jorge e Hélio Gracie.
Hélio Gracie, sendo mais franzino, adaptou as técnicas para focar no uso da alavanca em vez da força bruta, dando origem ao Jiu-Jitsu Brasileiro (BJJ).
O Jiu-Jitsu da linhagem Behring carrega as tradições técnicas e éticas estabelecidas pelo Grande Mestre Sylvio Behring, focando na defesa pessoal, respeito mútuo e disciplina dentro e fora dos tatames. A escola de São Bento do Sapucaí orgulha-se de manter este legado vivo.`,
videos: [
{ id: 1, title: 'A Origem do Jiu-Jitsu Brasileiro (BJJ)', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ' },
{ id: 2, title: 'Defesa Pessoal Behring BJJ - Fundamentos', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ' }
]
};
const DEFAULT_DOJO_SCHEDULES = {
centro: [
{ day: "Segunda", type: "Adulto", time: "10:00h e 18:30h" },
{ day: "Terça", type: "Kids", time: "18h" },
{ day: "Quarta", type: "Adulto", time: "10:00h e 18:30h" },
{ day: "Quinta", type: "Kids", time: "18h" },
{ day: "Sábado", type: "Misto", time: "10:00h" }
],
quilombo: [
{ day: "Segunda", type: "Misto", time: "18:30h" },
{ day: "Quinta", type: "Misto", time: "18:30h" }
]
};
// App State
let db = {
students: JSON.parse(localStorage.getItem('bjj_students')) || DEFAULT_STUDENTS,
events: JSON.parse(localStorage.getItem('bjj_events')) || DEFAULT_EVENTS,
announcements: JSON.parse(localStorage.getItem('bjj_announcements')) || DEFAULT_ANNOUNCEMENTS,
history: JSON.parse(localStorage.getItem('bjj_history')) || DEFAULT_HISTORY,
bjjHistory: JSON.parse(localStorage.getItem('bjj_history_content')) || DEFAULT_BJJ_HISTORY,
dojoSchedules: JSON.parse(localStorage.getItem('bjj_dojo_schedules')) || DEFAULT_DOJO_SCHEDULES
};
// Make sure all students have profile properties initialized
db.students.forEach(initializeStudentFields);
// Re-compute student attendance counts dynamically from history to ensure local database consistency on startup
if (db.students && db.history) {
db.students.forEach(student => {
student.attendanceCount = db.history.filter(h => h.studentId === student.id).length;
});
}
let currentSession = {
user: null,
role: null,
activeTab: null
};
// Supabase Configuration
const SUPABASE_URL = 'https://kvhcvuagncabwqtvrsnd.supabase.co';
const SUPABASE_KEY = 'sb_publishable_11I2BcMoKAoAr2uvSLuPwA_8PkDyBll';
const supabaseClient = (window.supabase) ? window.supabase.createClient(SUPABASE_URL, SUPABASE_KEY) : null;
// Helper to map student record from Supabase schema to local database schema
function mapSupabaseStudent(s) {
return {
id: s.id,
name: s.name,
email: s.email || '',
whatsapp: s.whatsapp || '',
password: s.senha || 'aluno123',
belt: s.belt,
degrees: s.degrees,
attendanceCount: s.attendance_count,
selfie: s.selfie,
streak: s.streak,
address: s.address,
age: s.age,
guardian: s.guardian,
objective: s.objective,
weeklyGoal: s.weekly_goal,
profession: s.profession,
schoolName: s.school_name,
hasLoan: s.has_loan,
kimonoBrand: s.kimono_brand,
kimonoSize: s.kimono_size,
kimonoDate: s.kimono_date,
classTime: s.class_time || 'Qualquer Horário',
evaluationParents: s.evaluation_parents || 'Pendente',
evaluationSchool: s.evaluation_school || 'Pendente',
faceEmbedding: s.face_embedding || null
};
}
// Ensure every logged-in professor has a corresponding student record (now and future)
async function ensureStudentRecordForProfessor(profId, profName) {
let student = db.students.find(s => s.id === profId);
const isSensei = profId.startsWith('sensei_');
const isSenpai = profId.startsWith('senpai_');
if (student) {
if (isSensei && student.belt !== 'Preta') {
student.belt = 'Preta';
await syncStudentToCloud(student);
saveDB();
}
return;
}
student = {
id: profId,
name: profName,
password: 'aluno123',
email: '',
whatsapp: '',
belt: isSensei ? 'Preta' : (isSenpai ? 'Pendente' : 'Preta'),
degrees: 0,
attendanceCount: 0,
selfie: null,
streak: 100,
address: '',
age: null,
guardian: '',
objective: '',
weeklyGoal: 3,
profession: 'Professor',
schoolName: '',
hasLoan: false,
kimonoBrand: '',
kimonoSize: '',
kimonoDate: '',
classTime: 'Qualquer Horário'
};
db.students.push(student);
try {
await syncStudentToCloud(student);
} catch(e) {
console.error("Failed to sync auto-created student profile for professor", e);
}
saveDB();
}
let manualPresenceList = {}; // Temp store for today's check-ins
let currentGroupPhoto = null;
let lastRecognitionWasFallback = false;
let currentIARecognitionResult = [];
// Supabase Async Seeding Helpers
async function seedSupabaseStudents() {
for (let s of DEFAULT_STUDENTS) {
await supabaseClient.from('students').insert({
id: s.id,
name: s.name,
email: s.email || '',
senha: s.password || 'aluno123',
belt: s.belt,
degrees: s.degrees,
attendance_count: s.attendanceCount,
selfie: s.selfie,
streak: s.streak,
address: s.address,
age: s.age,
guardian: s.guardian,
objective: s.objective,
weekly_goal: s.weeklyGoal,
profession: s.profession,
school_name: s.schoolName,
has_loan: s.hasLoan,
kimono_brand: s.kimonoBrand,
kimono_size: s.kimonoSize,
kimono_date: s.kimonoDate
});
}
}
async function seedSupabaseEvents() {
for (let ev of DEFAULT_EVENTS) {
await supabaseClient.from('events').insert({
id: ev.id,
title: ev.title,
type: ev.type,
date: ev.date,
time: ev.time
});
}
}
async function seedSupabaseAnnouncements() {
for (let ann of DEFAULT_ANNOUNCEMENTS) {
await supabaseClient.from('announcements').insert({
id: ann.id,
title: ann.title,
content: ann.content,
date: ann.date
});
}
}
async function seedSupabaseBJJHistory() {
await supabaseClient.from('bjj_history').insert({
id: 1,
text: DEFAULT_BJJ_HISTORY.text,
videos: DEFAULT_BJJ_HISTORY.videos
});
}
// Supabase Async Sync Operations
async function loadDBFromSupabase() {
if (!supabaseClient) {
console.warn("Supabase client not loaded. Running in local fallback mode.");
return;
}
try {
// 1. Fetch Students
const { data: studentsData, error: studentsError } = await supabaseClient.from('students').select('*');
if (studentsError) throw studentsError;
if (studentsData && studentsData.length > 0) {
db.students = studentsData.map(mapSupabaseStudent);
localStorage.setItem('bjj_students_seeded', 'true');
} else {
const seededStudents = localStorage.getItem('bjj_students_seeded');
if (!seededStudents) {
await seedSupabaseStudents();
localStorage.setItem('bjj_students_seeded', 'true');
const { data: reloadedData } = await supabaseClient.from('students').select('*');
if (reloadedData) {
db.students = reloadedData.map(mapSupabaseStudent);
}
} else {
db.students = [];
}
}
// 2. Fetch Events
const { data: eventsData, error: eventsError } = await supabaseClient.from('events').select('*');
if (eventsError) throw eventsError;
if (eventsData && eventsData.length > 0) {
db.events = eventsData;
localStorage.setItem('bjj_events_seeded', 'true');
} else {
const seededEvents = localStorage.getItem('bjj_events_seeded');
if (!seededEvents) {
await seedSupabaseEvents();
localStorage.setItem('bjj_events_seeded', 'true');
const { data: reloadedEvents } = await supabaseClient.from('events').select('*');
if (reloadedEvents) db.events = reloadedEvents;
} else {
db.events = [];
}
}
// 3. Fetch Announcements
const { data: announcementsData, error: announcementsError } = await supabaseClient.from('announcements').select('*');
if (announcementsError) throw announcementsError;
if (announcementsData && announcementsData.length > 0) {
db.announcements = announcementsData;
localStorage.setItem('bjj_announcements_seeded', 'true');
} else {
const seededAnnouncements = localStorage.getItem('bjj_announcements_seeded');
if (!seededAnnouncements) {
await seedSupabaseAnnouncements();
localStorage.setItem('bjj_announcements_seeded', 'true');
const { data: reloadedAnnouncements } = await supabaseClient.from('announcements').select('*');
if (reloadedAnnouncements) db.announcements = reloadedAnnouncements;
} else {
db.announcements = [];
}
}
// 4. Fetch History
const { data: historyData, error: historyError } = await supabaseClient.from('attendance_history').select('*');
if (historyError) throw historyError;
if (historyData) {
db.history = historyData.map(h => {
return {
id: h.id,
date: h.date,
time: h.time,
studentId: h.student_id,
studentName: h.student_name,
belt: h.belt,
method: h.method,
classTime: h.class_time || 'Qualquer Horário',
teacherName: h.teacher_name || 'ADM'
};
});
// Sort by descending (latest first)
db.history.sort((a, b) => b.date.localeCompare(a.date) || b.time.localeCompare(a.time));
}
// 5. Fetch BJJ History Content
const { data: bjjHistoryData, error: bjjHistoryError } = await supabaseClient.from('bjj_history').select('*').eq('id', 1).single();
if (bjjHistoryError && bjjHistoryError.code !== 'PGRST116') throw bjjHistoryError;
if (bjjHistoryData) {
db.bjjHistory = bjjHistoryData;
localStorage.setItem('bjj_history_seeded', 'true');
} else {
const seededHistory = localStorage.getItem('bjj_history_seeded');
if (!seededHistory) {
await seedSupabaseBJJHistory();
localStorage.setItem('bjj_history_seeded', 'true');
const { data: reloadedHistory } = await supabaseClient.from('bjj_history').select('*').eq('id', 1).single();
if (reloadedHistory) db.bjjHistory = reloadedHistory;
} else {
db.bjjHistory = { text: '', videos: [] };
}
}
// 6. Fetch Dojo Schedules
if (supabaseClient) {
try {
const { data: schedData, error: schedError } = await supabaseClient.from('dojo_schedules').select('*').eq('id', 'schedule').single();
if (!schedError && schedData) {
db.dojoSchedules = schedData.data;
localStorage.setItem('bjj_schedules_seeded', 'true');
} else {
const seededSchedules = localStorage.getItem('bjj_schedules_seeded');
if (!seededSchedules) {
await supabaseClient.from('dojo_schedules').upsert({ id: 'schedule', data: db.dojoSchedules });
localStorage.setItem('bjj_schedules_seeded', 'true');
}
}
} catch(e) {
console.warn("Could not load dojo schedules from Supabase", e);
}
}
// 7. Fetch Face API Configuration (URL & Threshold) from Supabase dojo_schedules table
if (supabaseClient) {
try {
const { data: configData, error: configError } = await supabaseClient.from('dojo_schedules').select('*').eq('id', 'config').single();
if (!configError && configData && configData.data) {
if (configData.data.face_api_url) {
localStorage.setItem('face_api_url', configData.data.face_api_url);
const apiInput = document.getElementById('ia-api-url');
if (apiInput) apiInput.value = configData.data.face_api_url;
const settingsApiInput = document.getElementById('settings-ia-api-url');
if (settingsApiInput) settingsApiInput.value = configData.data.face_api_url;
}
if (configData.data.face_api_threshold) {
localStorage.setItem('face_api_threshold', configData.data.face_api_threshold);
const thresholdInput = document.getElementById('ia-threshold');
if (thresholdInput) {
thresholdInput.value = configData.data.face_api_threshold;
const display = document.getElementById('ia-threshold-value');
if (display) display.textContent = parseFloat(configData.data.face_api_threshold).toFixed(2);
}
const settingsThresholdInput = document.getElementById('settings-ia-threshold');
if (settingsThresholdInput) {
settingsThresholdInput.value = configData.data.face_api_threshold;
const display = document.getElementById('settings-ia-threshold-value');
if (display) display.textContent = parseFloat(configData.data.face_api_threshold).toFixed(2);
}
}
}
} catch(e) {
console.warn("Could not load face api config from Supabase", e);
}
}
// Re-compute student attendance counts dynamically from history to ensure database consistency after cloud load
if (db.students && db.history) {
db.students.forEach(student => {
student.attendanceCount = db.history.filter(h => h.studentId === student.id).length;
});
}
// Save local backup copy
saveDBLocallyOnly();
populateClassTimeSelects();
} catch (e) {
console.warn("Could not sync with Supabase tables. Running locally on LocalStorage.", e);
}
}
function saveSessionToLocalStorage() {
try {
const sessionCopy = JSON.parse(JSON.stringify(currentSession));
if (sessionCopy.user && sessionCopy.user.selfie && sessionCopy.user.selfie.startsWith('data:')) {
sessionCopy.user.selfie = 'placeholder';
}
localStorage.setItem('bjj_session', JSON.stringify(sessionCopy));
} catch (err) {
console.error("Failed to save session to localStorage:", err);
}
}
function saveDBLocallyOnly() {
try {
const studentsClean = db.students.map(s => {
const copy = { ...s };
// If the selfie is a large base64 string, do not write it to localStorage to prevent QuotaExceededError
if (copy.selfie && copy.selfie.startsWith('data:')) {
copy.selfie = 'placeholder';
}
return copy;
});
localStorage.setItem('bjj_students', JSON.stringify(studentsClean));
localStorage.setItem('bjj_events', JSON.stringify(db.events));
localStorage.setItem('bjj_announcements', JSON.stringify(db.announcements));
localStorage.setItem('bjj_history', JSON.stringify(db.history));
localStorage.setItem('bjj_history_content', JSON.stringify(db.bjjHistory));
localStorage.setItem('bjj_dojo_schedules', JSON.stringify(db.dojoSchedules));
} catch (err) {
console.error("Failed to save database to localStorage:", err);
}
}
// Central Cloud Sync Writer
async function syncStudentToCloud(student) {
if (!supabaseClient) {
console.warn("Supabase client not loaded. Running in local fallback mode.");
return;
}
try {
const { error } = await supabaseClient.from('students').upsert({
id: student.id,
name: student.name,
email: student.email || '',
whatsapp: student.whatsapp || '',
senha: student.password || 'aluno123',
belt: student.belt,
degrees: student.degrees,
attendance_count: student.attendanceCount,
selfie: student.selfie,
streak: student.streak,
address: student.address,
age: student.age,
guardian: student.guardian,
objective: student.objective,
weekly_goal: student.weeklyGoal,
profession: student.profession,
school_name: student.schoolName,
has_loan: student.hasLoan,
kimono_brand: student.kimonoBrand,
kimono_size: student.kimonoSize,
kimono_date: student.kimonoDate,
class_time: student.classTime || 'Qualquer Horário',
evaluation_parents: student.evaluationParents || 'Pendente',
evaluation_school: student.evaluationSchool || 'Pendente',
face_embedding: student.faceEmbedding || null
});
if (error) throw error;
} catch(e) {
console.error("Supabase Sync Failed (Student):", e);
alert("Erro ao sincronizar dados do aluno com o Supabase (Verifique se a tabela 'students' possui todas as colunas do schema.sql e se o RLS está desabilitado):\n" + (e.message || JSON.stringify(e)));
throw e;
}
}
function setupSidebar() {
const toggleBtn = document.getElementById('sidebar-toggle');
const sidebar = document.getElementById('app-sidebar');
const toggleIconPath = document.getElementById('toggle-icon-path');
if (toggleBtn && sidebar) {
toggleBtn.addEventListener('click', () => {
sidebar.classList.toggle('collapsed');
const isCollapsed = sidebar.classList.contains('collapsed');
localStorage.setItem('bjj_sidebar_collapsed', isCollapsed);
if (toggleIconPath) {
if (isCollapsed) {
toggleIconPath.setAttribute('d', 'M9 5l7 7-7 7');
} else {
toggleIconPath.setAttribute('d', 'M15 19l-7-7 7-7');
}
}
});
const wasCollapsed = localStorage.getItem('bjj_sidebar_collapsed') === 'true';
if (wasCollapsed) {
sidebar.classList.add('collapsed');
if (toggleIconPath) {
toggleIconPath.setAttribute('d', 'M9 5l7 7-7 7');
}
}
}
}
// Initialize application
// Initialize application
document.addEventListener('DOMContentLoaded', () => {
setupSidebar();
// Check if session exists in localStorage immediately for instant rendering
const savedSession = localStorage.getItem('bjj_session');
if (savedSession) {
currentSession = JSON.parse(savedSession);
setupUserInterface();
} else {
showLoginScreen();
}
// Set current date in Presence View
const dateDisplay = document.getElementById('presence-current-date');
if (dateDisplay) {
const today = new Date();
dateDisplay.textContent = today.toLocaleDateString('pt-BR');
}
// Populate training time select dropdowns with cached data immediately
populateClassTimeSelects();
// Load from Supabase asynchronously in the background to prevent blocking
loadDBFromSupabase().then(() => {
// Re-setup UI if a session was active, to sync live data
if (currentSession.user) {
setupUserInterface();
}
populateClassTimeSelects(); // Sync again with live Supabase schedules data
}).catch(err => {
console.warn("Background database sync failed", err);
});
});
// Database Save Helper
function saveDB() {
saveDBLocallyOnly();
}
// Authentication handlers
function toggleAuthForm(mode) {
const loginForm = document.getElementById('login-form');
const registerForm = document.getElementById('register-form');
if (mode === 'register') {
loginForm.style.display = 'none';
registerForm.style.display = 'block';
} else {
loginForm.style.display = 'block';
registerForm.style.display = 'none';
}
}
async function handleLogin(event) {
event.preventDefault();
const usernameInput = document.getElementById('username').value.trim();
const passwordInput = document.getElementById('password').value;
const roleInput = document.getElementById('login-role').value;
if (roleInput === 'professor') {
const normalizedUser = usernameInput.toLowerCase().replace(/\s+/g, ' ').trim();
let professorName = '';
if (normalizedUser === 'sensei hugo') {
professorName = 'Sensei Hugo';
} else if (normalizedUser === 'sensei leo') {
professorName = 'Sensei Leo';
} else if (normalizedUser === 'adm') {
professorName = 'ADM';
} else if (normalizedUser === 'professor') {
professorName = 'Prof. Felipe';
} else if (normalizedUser === 'senpai lucas') {
professorName = 'Senpai Lucas';
} else if (normalizedUser === 'sensei marcio' || normalizedUser === 'sensei márcio') {
professorName = 'Sensei Márcio';
} else if (normalizedUser === 'senpai marcelo') {
professorName = 'Senpai Marcelo';
} else if (normalizedUser === 'senpai maju') {
professorName = 'Senpai Maju';
} else if (normalizedUser === 'senpai rogerio' || normalizedUser === 'senpai rogério') {
professorName = 'Senpai Rogério';
} else if (normalizedUser === 'senpai felicio' || normalizedUser === 'senpai felício') {
professorName = 'Senpai Felício';
} else if (normalizedUser === 'senpai isadora') {
professorName = 'Senpai Isadora';
}
if (professorName && passwordInput === 'bjj123') {
currentSession.user = { id: normalizedUser.replace(/\s+/g, '_'), name: professorName };
currentSession.role = 'professor';
currentSession.activeTab = 'prof-presence';
saveSessionToLocalStorage();
if (currentSession.user.id !== 'adm') {
await ensureStudentRecordForProfessor(currentSession.user.id, professorName);
}
setupUserInterface();
return;
} else {
alert('Credenciais de Professor incorretas! Verifique o nome do professor e a senha bjj123.');
return;
}
} else {
// Student login
const studentId = usernameInput.toLowerCase().replace(/\s+/g, '_');
let student = db.students.find(s => s.id === studentId);
// Fast-path: check if student exists in local memory first for instant response
if (student) {
initializeStudentFields(student);
if (student.password === passwordInput) {
currentSession.user = student;
currentSession.role = 'student';
currentSession.activeTab = 'stud-home';
saveSessionToLocalStorage();
setupUserInterface();
// Fetch latest update in background to refresh LocalStorage sync
if (supabaseClient) {
supabaseClient.from('students').select('*').eq('id', studentId).single().then(({ data }) => {
if (data) {
const updated = mapSupabaseStudent(data);
const idx = db.students.findIndex(s => s.id === studentId);
if (idx !== -1) {
db.students[idx] = updated;
}
saveDB();
// Immediately update session user and profile views if currently active
if (currentSession.user && currentSession.user.id === studentId) {
currentSession.user = updated;
saveSessionToLocalStorage();
renderStudentProfile();
renderStudentHome();
}
}
}).catch(e => console.warn("Background credentials refresh failed", e));
}
return;
} else {
alert('Senha incorreta para este aluno!');
return;
}
}
// Slow-path: Student not in local memory (e.g. fresh registration on another device)
if (supabaseClient) {
const btn = event.submitter || document.querySelector('#login-form button[type="submit"]');
const originalText = btn ? btn.textContent : "Entrar no App";
if (btn) {
btn.textContent = "Verificando...";
btn.disabled = true;
}
try {
const { data, error } = await supabaseClient.from('students').select('*').eq('id', studentId).single();
if (btn) {
btn.textContent = originalText;
btn.disabled = false;
}
if (data) {
student = mapSupabaseStudent(data);
db.students.push(student);
saveDB();
initializeStudentFields(student);
if (student.password === passwordInput) {
currentSession.user = student;
currentSession.role = 'student';
currentSession.activeTab = 'stud-home';
saveSessionToLocalStorage();
setupUserInterface();
return;
} else {
alert('Senha incorreta para este aluno!');
return;
}
}
} catch (e) {
console.warn("Supabase credentials fetch failed", e);
if (btn) {
btn.textContent = originalText;
btn.disabled = false;
}
}
}
alert('Aluno não cadastrado! Por favor, use a opção de cadastro abaixo.');
}
}
async function handleRegister(event) {
event.preventDefault();
const nameInput = document.getElementById('reg-name').value.trim();
const emailInput = document.getElementById('reg-email').value.trim();
const whatsappInput = document.getElementById('reg-whatsapp').value.trim();
const classTimeInput = 'Qualquer Horário';
const passwordInput = document.getElementById('reg-password').value;
const confirmInput = document.getElementById('reg-confirm').value;
if (passwordInput !== confirmInput) {
alert('As senhas não coincidem!');
return;
}
const studentId = nameInput.toLowerCase().replace(/\s+/g, '_');
// Check if student ID already exists
let exists = db.students.some(s => s.id === studentId);
if (!exists) {
try {
const { data, error } = await supabaseClient.from('students').select('id').eq('id', studentId);
if (data && data.length > 0) {
exists = true;
}
} catch (e) {
console.warn("Could not check duplicate username in Supabase", e);
}
}
if (exists) {
alert('Já existe um aluno cadastrado com este nome!');
return;
}
const newStudent = {
id: studentId,
name: nameInput,
email: emailInput,
whatsapp: whatsappInput,
password: passwordInput,
belt: 'Branca',
degrees: 0,
attendanceCount: 0,
selfie: null,
streak: 100,
address: '',
age: 18,
guardian: '',
objective: '',
weeklyGoal: 3,
profession: '',
schoolName: '',
hasLoan: false,
kimonoBrand: '',
kimonoSize: '',
kimonoDate: '',
classTime: classTimeInput || 'Qualquer Horário'
};
try {
const { error } = await supabaseClient.from('students').insert({
id: newStudent.id,
name: newStudent.name,
email: newStudent.email,
senha: newStudent.password,
belt: newStudent.belt,
degrees: newStudent.degrees,
attendance_count: newStudent.attendanceCount,
selfie: newStudent.selfie,
streak: newStudent.streak,
address: newStudent.address,
age: newStudent.age,
guardian: newStudent.guardian,
objective: newStudent.objective,
weekly_goal: newStudent.weeklyGoal,
profession: newStudent.profession,
school_name: newStudent.schoolName,
has_loan: newStudent.hasLoan,
kimono_brand: newStudent.kimonoBrand,
kimono_size: newStudent.kimonoSize,
kimono_date: newStudent.kimonoDate
});
if (error) throw error;
} catch (e) {
console.error("Failed to sync new student to Supabase", e);
alert("Erro ao salvar cadastro no banco de dados na nuvem:\n" + (e.message || JSON.stringify(e)));
return;
}
db.students.push(newStudent);
saveDB();
// Automatically log in
currentSession.user = newStudent;
currentSession.role = 'student';
currentSession.activeTab = 'stud-home';
saveSessionToLocalStorage();
// Reset inputs & toggle form back for next logouts
document.getElementById('reg-name').value = '';
document.getElementById('reg-email').value = '';
document.getElementById('reg-password').value = '';
document.getElementById('reg-confirm').value = '';
toggleAuthForm('login');
setupUserInterface();
alert('Sua conta foi criada e você foi logado com sucesso!');
}
function handleLogout() {
currentSession = { user: null, role: null, activeTab: null };
localStorage.removeItem('bjj_session');
showLoginScreen();
}
function showLoginScreen() {
document.getElementById('auth-screen').style.display = 'flex';
document.getElementById('app-container').style.display = 'none';
}
function setupUserInterface() {
document.getElementById('auth-screen').style.display = 'none';
document.getElementById('app-container').style.display = 'flex';
// Set User Profile headers
document.getElementById('nav-user-display').textContent = currentSession.user.name;
document.getElementById('nav-user-role-display').textContent =
currentSession.role === 'professor' ? 'Professor / Admin' : 'Aluno';
// Show/hide navigation tabs depending on role
if (currentSession.role === 'professor') {
document.getElementById('professor-tabs').style.display = 'flex';
document.getElementById('student-tabs').style.display = 'none';
// Initialize Face API configurations
const apiInput = document.getElementById('ia-api-url');
if (apiInput) {
apiInput.value = localStorage.getItem('face_api_url') || 'http://localhost:8000';
}
const thresholdInput = document.getElementById('ia-threshold');
if (thresholdInput) {
const val = localStorage.getItem('face_api_threshold') || '0.40';
thresholdInput.value = val;
const display = document.getElementById('ia-threshold-value');
if (display) display.textContent = parseFloat(val).toFixed(2);
}
// Populate Professor views
renderProfessorDashboard();
renderStudentsTable();
renderPresenceChecklist();
renderGeneralHistoryTable();
renderProfessorEventsAndAnnouncements();
// Asynchronously check and migrate any student selfies without vector embeddings
backfillMissingEmbeddings();
// Check if professor onboarding is complete (selfie for Sensei/Senpai, belt for Senpai)
if (currentSession.user.id !== 'adm') {
const profRecord = db.students.find(s => s.id === currentSession.user.id);
const isSenpai = currentSession.user.id.startsWith('senpai_');
const needsPhoto = !profRecord || !profRecord.selfie;
const needsBelt = isSenpai && (!profRecord || profRecord.belt === 'Pendente' || !profRecord.belt);
if (needsPhoto || needsBelt) {
document.getElementById('prof-photo-modal-name').textContent = currentSession.user.name;
// Show/hide Senpai belt selection
const beltSelectionGroup = document.getElementById('prof-belt-selection-group');
if (beltSelectionGroup) {
beltSelectionGroup.style.display = needsBelt ? 'block' : 'none';
if (profRecord && profRecord.belt && profRecord.belt !== 'Pendente') {
document.getElementById('prof-photo-modal-belt').value = profRecord.belt;
} else {
document.getElementById('prof-photo-modal-belt').value = 'Branca';
}
}
const previewImg = document.getElementById('prof-photo-modal-preview');
if (profRecord && profRecord.selfie) {
previewImg.src = profRecord.selfie;
} else {
previewImg.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%236f6f78'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z'/%3E%3C/svg%3E";
}
const saveBtn = document.getElementById('btn-save-prof-photo');
if (saveBtn) {
saveBtn.disabled = needsPhoto; // if they need a photo, they must capture it first. If they don't, they can save.
}
openModal('professor-photo-modal');
}
}
} else {
document.getElementById('professor-tabs').style.display = 'none';
document.getElementById('student-tabs').style.display = 'flex';
// Sync student local info from DB (since details like degrees/selfie might change)
const updatedStudent = db.students.find(s => s.id === currentSession.user.id);
if (updatedStudent) {
initializeStudentFields(updatedStudent);
currentSession.user = updatedStudent;
}
// Populate Student views
renderStudentHome();
renderStudentProfile();
renderStudentHistoryTable();
renderStudentEventsAndAnnouncements();
}
// Switch to active tab
switchTab(currentSession.activeTab);
}
// Tab Switching Routing
function switchTab(tabId) {
// Redirect deleted tabs to default
if (currentSession.role === 'professor') {
if (tabId === 'prof-ia-photo' || tabId === 'prof-bjj-history') {
tabId = 'prof-presence';
}
} else {
if (tabId === 'stud-events') {
tabId = 'stud-home';
}
}
currentSession.activeTab = tabId;
saveSessionToLocalStorage();
// Remove active classes
document.querySelectorAll('.nav-tab-item').forEach(item => item.classList.remove('active'));
document.querySelectorAll('.view-section').forEach(item => item.classList.remove('active'));
// Map tabId to navigation element and view section
let navItem, sectionItem;
if (currentSession.role === 'professor') {
// Professor tabs
const tabMap = {
'prof-presence': 1,
'prof-dashboard': 2,
'prof-students': 3,
'prof-history': 4,
'prof-events': 5,
'prof-settings': 6
};
const idx = tabMap[tabId];
navItem = document.querySelector(`#professor-tabs .nav-tab-item:nth-child(${idx})`);
sectionItem = document.getElementById(`view-${tabId}`);
} else {
// Student tabs
const tabMap = {
'stud-home': 1,
'stud-profile': 2,
'stud-history': 3
};
const idx = tabMap[tabId];
navItem = document.querySelector(`#student-tabs .nav-tab-item:nth-child(${idx})`);
sectionItem = document.getElementById(`view-${tabId}`);
}
if (navItem) navItem.classList.add('active');
if (sectionItem) sectionItem.classList.add('active');
// Trigger re-renders for live lists
if (tabId === 'prof-presence') setPresenceTab('ia');
if (tabId === 'prof-dashboard') renderProfessorDashboard();
if (tabId === 'prof-students') renderStudentsTable();
if (tabId === 'prof-history') renderGeneralHistoryTable();
if (tabId === 'prof-settings') renderProfessorSettings();
if (tabId === 'stud-home') renderStudentHome();
if (tabId === 'stud-profile') renderStudentProfile();
if (tabId === 'stud-history') renderStudentHistoryTable();
}
function setPresenceTab(type) {
const btnIA = document.getElementById('btn-presence-toggle-ia');
const btnManual = document.getElementById('btn-presence-toggle-manual');
const containerIA = document.getElementById('presence-ia-container');
const containerManual = document.getElementById('presence-manual-container');
if (type === 'ia') {
if (containerIA) containerIA.style.display = 'block';
if (containerManual) containerManual.style.display = 'none';
if (btnIA) {
btnIA.className = 'btn btn-primary btn-sm';
btnIA.style.background = 'var(--accent-color)';
btnIA.style.border = '1px solid var(--accent-color)';
btnIA.style.color = '#ffffff';
}
if (btnManual) {
btnManual.className = 'btn btn-secondary btn-sm';
btnManual.style.background = 'transparent';
btnManual.style.border = 'none';
btnManual.style.color = 'var(--text-muted)';
}
// Update backfill count for IA view
updateBackfillCount();
} else {
if (containerIA) containerIA.style.display = 'none';
if (containerManual) containerManual.style.display = 'block';
if (btnIA) {
btnIA.className = 'btn btn-secondary btn-sm';
btnIA.style.background = 'transparent';
btnIA.style.border = 'none';
btnIA.style.color = 'var(--text-muted)';
}
if (btnManual) {
btnManual.className = 'btn btn-primary btn-sm';
btnManual.style.background = 'var(--accent-color)';
btnManual.style.border = '1px solid var(--accent-color)';
btnManual.style.color = '#ffffff';
}
// Render manual checklist
renderPresenceChecklist();
}
}
// Helper to turn text URLs into clickable links
function linkify(text) {
if (!text) return '';
const urlPattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(urlPattern, '<a href="$1" target="_blank" style="color: var(--accent-color); text-decoration: underline; font-weight: 600;">$1</a>');
}
// Helper to format date
function formatDateStr(dateStr) {
const parts = dateStr.split('-');
if (parts.length === 3) {
return `${parts[2]}/${parts[1]}/${parts[0]}`;
}
return dateStr;
}
// Helper to get initials
function getInitials(name) {
const names = name.split(' ');
if (names.length > 1) {
return (names[0][0] + names[names.length - 1][0]).toUpperCase();
}
return name[0].toUpperCase();
}
// ==================== PROFESSOR VIEW CONTROLLERS ====================
function renderProfessorDashboard() {
document.getElementById('dashboard-total-students').textContent = db.students.length;
// Count today's presences in history
const today = new Date().toISOString().split('T')[0];
const todayPresences = db.history.filter(h => h.date === today).length;
document.getElementById('dashboard-today-presence').textContent = todayPresences;
document.getElementById('dashboard-next-events').textContent = db.events.length;
document.getElementById('dashboard-announcements-count').textContent = db.announcements.length;
// Belt Distribution (Chart Builder)
const beltCounts = { 'Branca': 0, 'Azul': 0, 'Roxa': 0, 'Marrom': 0, 'Preta': 0 };
db.students.forEach(s => {
if (beltCounts[s.belt] !== undefined) beltCounts[s.belt]++;
});
const chartContainer = document.getElementById('belt-chart-container');
chartContainer.innerHTML = '';
const maxCount = Math.max(...Object.values(beltCounts), 1); // Avoid division by zero
const beltColors = {
'Branca': { bar: '#f0f0f5', text: '#111111' },
'Azul': { bar: '#1e40af', text: '#ffffff' },
'Roxa': { bar: '#6d28d9', text: '#ffffff' },
'Marrom': { bar: '#78350f', text: '#ffffff' },
'Preta': { bar: '#1f2937', text: '#ff0000', border: 'red' }
};
Object.keys(beltCounts).forEach(belt => {
const count = beltCounts[belt];
const pct = (count / maxCount) * 100;
const row = document.createElement('div');
row.style.display = 'flex';
row.style.alignItems = 'center';
row.style.gap = '16px';
const borderStyle = belt === 'Preta' ? '1px solid red' : '1px solid rgba(255,255,255,0.1)';
row.innerHTML = `
<div style="width: 80px; font-size: 13px; font-weight: 600; color: var(--text-secondary);">${belt}</div>
<div style="flex: 1; height: 16px; background: rgba(255,255,255,0.03); border-radius: 4px; overflow: hidden; border: 1px solid var(--border-color);">
<div style="width: ${pct}%; height: 100%; background: ${beltColors[belt].bar}; border-radius: 4px; transition: width 0.8s ease;"></div>
</div>
<div style="width: 24px; font-size: 14px; font-weight: 700; text-align: right;">${count}</div>
`;
chartContainer.appendChild(row);
});
// Recent Events Dashboard List
const eventsList = document.getElementById('dashboard-events-list');
eventsList.innerHTML = '';
if (db.events.length === 0) {
eventsList.innerHTML = '<p style="color: var(--text-muted); font-size: 13px;">Nenhum evento agendado.</p>';
} else {
db.events.slice(0, 3).forEach(ev => {
const dateObj = new Date(ev.date + 'T00:00:00');
const day = String(dateObj.getDate()).padStart(2, '0');
const month = dateObj.toLocaleDateString('pt-BR', { month: 'short' }).slice(0, 3).toUpperCase();
const item = document.createElement('div');
item.className = 'event-item';
item.innerHTML = `
<div class="event-date-box">
<span class="event-date-day">${day}</span>
<span class="event-date-month">${month}</span>
</div>
<div class="event-details">
<h4>${ev.title}</h4>
<p>${ev.type} • ${ev.time}h</p>
</div>
`;
eventsList.appendChild(item);
});
}
// Dashboard Announcements List
const dashboardAnnList = document.getElementById('dashboard-announcements-list');
if (dashboardAnnList) {
dashboardAnnList.innerHTML = '';
if (db.announcements.length === 0) {
dashboardAnnList.innerHTML = '<p style="color: var(--text-muted); font-size: 13px; text-align: center; padding: 20px;">Nenhum aviso publicado.</p>';
} else {
db.announcements.slice(0, 3).forEach(ann => {
const item = document.createElement('div');
item.style.padding = '12px 0';
item.style.borderBottom = '1px solid var(--border-color)';
item.innerHTML = `
<h4 style="font-size: 14px; font-weight: 600; margin-bottom: 2px;">${linkify(ann.title)}</h4>
<span style="font-size: 10px; color: var(--text-muted); display: block; margin-bottom: 6px;">${formatDateStr(ann.date)}</span>
<p style="font-size: 12px; color: var(--text-secondary); line-height: 1.4;">${linkify(ann.content)}</p>
`;
dashboardAnnList.appendChild(item);
});
}
}
// Dashboard Dojo Schedules List
const dashCentroTbody = document.getElementById('dashboard-schedule-centro-tbody');
if (dashCentroTbody) {
dashCentroTbody.innerHTML = '';
const centroList = db.dojoSchedules.centro || [];
if (centroList.length === 0) {
dashCentroTbody.innerHTML = '<tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 12px;">Nenhum horário cadastrado.</td></tr>';
} else {
centroList.forEach(item => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td><strong>${item.day}</strong></td>
<td><span class="badge badge-orange" style="font-size: 9px; padding: 2px 4px;">${item.type}</span></td>
<td>${item.time}</td>
`;
dashCentroTbody.appendChild(tr);
});
}
}
const dashQuilomboTbody = document.getElementById('dashboard-schedule-quilombo-tbody');
if (dashQuilomboTbody) {
dashQuilomboTbody.innerHTML = '';
const quilomboList = db.dojoSchedules.quilombo || [];
if (quilomboList.length === 0) {
dashQuilomboTbody.innerHTML = '<tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 12px;">Nenhum horário cadastrado.</td></tr>';
} else {
quilomboList.forEach(item => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td><strong>${item.day}</strong></td>
<td><span class="badge badge-secondary" style="font-size: 9px; padding: 2px 4px; background: rgba(255,255,255,0.15);">${item.type}</span></td>
<td>${item.time}</td>
`;
dashQuilomboTbody.appendChild(tr);
});
}
}
}
function renderStudentsTable(filteredStudents = null) {
const list = filteredStudents || db.students;
const tbody = document.getElementById('students-table-body');
tbody.innerHTML = '';
if (list.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 40px;">Nenhum aluno encontrado.</td></tr>';
return;
}
list.forEach(student => {
const tr = document.createElement('tr');
// Avatar logic (Reference selfie)
let selfieHTML = `
<div style="width: 32px; height: 32px; border-radius: 50%; background: rgba(224,90,0,0.1); border: 1px dashed var(--accent-color); font-size: 10px; display: flex; align-items: center; justify-content: center; color: var(--accent-color); font-weight: bold;">
N/A
</div>
`;
if (student.selfie) {
const src = student.selfie.startsWith('data:') ? student.selfie : getPresetAvatar(student.id);
selfieHTML = `
<img src="${src}" style="width: 32px; height: 32px; border-radius: 50%; object-fit: cover; border: 1.5px solid var(--success-color);">
`;
}
// Belt badge class mapping (replace spaces and accents for kids' belts)
const beltClass = 'belt-' + student.belt.toLowerCase().replace(/á/g, 'a').replace(/ê/g, 'e').replace(/\s+/g, '-');
let eligibilityHTML = '';
if (student.age !== null && student.age < 16 && student.attendanceCount >= 100) {
eligibilityHTML = `<span class="badge badge-success" style="font-size: 9px; padding: 2px 6px; margin-top: 4px; display: inline-block; font-weight: bold;">👑 Elegível</span>`;
}
tr.innerHTML = `
<td>
<div style="display: flex; align-items: center; gap: 12px;">
<div style="width: 32px; height: 32px; border-radius: 50%; background: var(--bg-secondary); display: flex; align-items: center; justify-content: center; font-size: 12px; font-weight: 700; color: var(--text-secondary); border: 1px solid var(--border-color);">
${getInitials(student.name)}
</div>
<div>
<div style="font-weight: 600;">${student.name}</div>
<div style="font-size: 11px; display: flex; gap: 8px; flex-wrap: wrap;">
<span style="color: var(--text-muted);">ID: ${student.id}</span>
${student.whatsapp ? `<a href="https://wa.me/${student.whatsapp.replace(/\D/g, '')}" target="_blank" style="color: #25D366; text-decoration: none; font-weight: 500; display: inline-flex; align-items: center; gap: 3px;">💬 WhatsApp: ${student.whatsapp}</a>` : ''}
</div>
</div>
</div>
</td>
<td>
<div style="display: flex; align-items: center; gap: 8px;">
<span class="belt-badge ${beltClass}">${student.belt}</span>
<span style="font-size: 12px; color: var(--text-secondary); font-weight: 600;">${student.degrees} Graus</span>
</div>
</td>
<td>
<div style="display: flex; flex-direction: column;">
<span style="font-weight: bold;">${student.attendanceCount} treinos</span>
<span style="font-size: 11px; color: var(--text-muted);">Assiduidade: ${student.streak}%</span>
${eligibilityHTML}
</div>
</td>
<td>${selfieHTML}</td>
<td>
<button class="btn btn-secondary btn-sm" onclick="openGraduationModal('${student.id}')" style="padding: 6px 12px; font-size: 11px;">
🥋 Graduar / Editar
</button>
</td>
`;
tbody.appendChild(tr);
});
}
function filterStudents() {
const query = document.getElementById('search-students').value.toLowerCase();
const beltFilter = document.getElementById('filter-belt').value;
const filtered = db.students.filter(student => {
const matchesQuery = student.name.toLowerCase().includes(query) || student.id.toLowerCase().includes(query);
const matchesBelt = beltFilter === 'all' || student.belt === beltFilter;
return matchesQuery && matchesBelt;
});
renderStudentsTable(filtered);
}
function renderPresenceChecklist() {
const grid = document.getElementById('presence-checklist-grid');
grid.innerHTML = '';
if (db.students.length === 0) {
grid.innerHTML = '<p style="grid-column: span 3; text-align: center; color: var(--text-muted); padding: 40px;">Cadastre alunos para gerenciar presenças.</p>';
return;
}
const classFilter = document.getElementById('presence-class-filter').value;
const searchQuery = document.getElementById('presence-search-input').value.toLowerCase().trim();
// Filter students: stop filtering by student's preferred class time.
// The presence list shows all students, allowing easy name/belt search.
let filteredStudents = db.students.filter(student => {
if (searchQuery !== '') {
return student.name.toLowerCase().includes(searchQuery) ||
student.belt.toLowerCase().includes(searchQuery);
}
return true;
});
if (filteredStudents.length === 0) {
grid.innerHTML = '<p style="grid-column: span 3; text-align: center; color: var(--text-muted); padding: 24px;">Nenhum aluno encontrado para os filtros selecionados.</p>';
return;
}
// Sort by name
filteredStudents.sort((a, b) => a.name.localeCompare(b.name));
filteredStudents.forEach(student => {
const isChecked = manualPresenceList[student.id] ? true : false;
const card = document.createElement('div');
card.className = `card text-center ${isChecked ? 'match' : ''}`;
card.style.padding = '16px';
card.style.cursor = 'pointer';
card.style.border = isChecked ? '1px solid var(--accent-color)' : '1px solid var(--border-color)';
card.onclick = () => {
manualPresenceList[student.id] = !manualPresenceList[student.id];
renderPresenceChecklist();
};
const initials = getInitials(student.name);
card.innerHTML = `
<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
<span class="badge ${student.belt === 'Branca' ? 'badge-secondary' : 'badge-orange'}" style="font-size: 8px;">${student.belt}</span>
<input type="checkbox" ${isChecked ? 'checked' : ''} style="accent-color: var(--accent-color); pointer-events: none;">
</div>
<div style="width: 44px; height: 44px; border-radius: 50%; background: var(--bg-primary); display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 700; margin: 0 auto 8px; color: var(--text-secondary); border: 1.5px solid ${isChecked ? 'var(--accent-color)' : 'var(--border-color)'};">
${initials}
</div>
<div style="font-weight: 600; font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${student.name}</div>
<div style="font-size: 10px; color: var(--text-muted); margin-top: 4px;">${student.classTime || 'Qualquer Horário'}</div>
`;
grid.appendChild(card);
});
}
async function saveManualPresence() {
const today = new Date().toISOString().split('T')[0];
const timeStr = new Date().toTimeString().slice(0, 5);
const classFilterVal = document.getElementById('presence-class-filter').value;
const selectedClass = classFilterVal === 'all' ? 'Qualquer Horário' : classFilterVal;
const teacherName = (currentSession && currentSession.user && currentSession.user.name) ? currentSession.user.name : 'ADM';
let markedCount = 0;
const promises = [];
// Check if we checked any student
for (let studentId of Object.keys(manualPresenceList)) {
if (manualPresenceList[studentId]) {
const student = db.students.find(s => s.id === studentId);
if (student) {
// Check if already marked presence today to avoid duplicates
const hasPresenceToday = db.history.some(h => h.studentId === studentId && h.date === today);
if (!hasPresenceToday) {
student.attendanceCount++;
// Automatically calculate degrees for kids
if (student.age !== null && student.age < 16) {
if (student.attendanceCount >= 80) student.degrees = 4;
else if (student.attendanceCount >= 60) student.degrees = 3;
else if (student.attendanceCount >= 40) student.degrees = 2;
else if (student.attendanceCount >= 20) student.degrees = 1;
else student.degrees = 0;
}
// Supabase operations
promises.push((async () => {
try {
const { error: histError } = await supabaseClient.from('attendance_history').insert({
date: today,
time: timeStr,
student_id: student.id,
student_name: student.name,
belt: student.belt,
method: 'manual',
class_time: selectedClass,
teacher_name: teacherName
});
if (histError) throw histError;
const { error: studError } = await supabaseClient.from('students').update({
attendance_count: student.attendanceCount,
degrees: student.degrees
}).eq('id', student.id);
if (studError) throw studError;
} catch (e) {
console.error("Failed to sync manual presence to Supabase", e);
alert(`Erro ao sincronizar presença de ${student.name} no Supabase:\n` + (e.message || JSON.stringify(e)));
}
})());
// Local fallback
db.history.unshift({
date: today,
time: timeStr,
studentId: student.id,
studentName: student.name,
belt: student.belt,
method: 'manual',
classTime: selectedClass,
teacherName: teacherName
});
markedCount++;
}
}
}
}
if (markedCount > 0) {
if (promises.length > 0) {
await Promise.all(promises);
}
await loadDBFromSupabase(); // sync with the cloud (fetches database IDs)
saveDB();
alert(`Presença salva com sucesso! ${markedCount} presenças registradas.`);
manualPresenceList = {};
renderPresenceChecklist();
setPresenceTab('ia');
} else {
alert('Selecione os alunos que compareceram à aula hoje antes de salvar.');
}
}
// Preset Avatars for mock data
function getPresetAvatar(studentId) {
// Generate inline SVG generic avatar using BJJ theme colors
const colors = {
lucas: '#ffffff',
thiago: '#0033cc',
felipe: '#6600cc',
gabriela: '#4d2600',
roberto: '#111111'
};
const fill = colors[studentId] || '#e05a00';
return `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ccircle cx='50' cy='50' r='50' fill='${encodeURIComponent(fill)}'/%3E%3Cpath d='M30,75 C30,60 40,55 50,55 C60,55 70,60 70,75' fill='none' stroke='%23ffffff' stroke-width='4'/%3E%3Ccircle cx='50' cy='35' r='15' fill='%23ffffff'/%3E%3C/svg%3E`;
}
// Group photo preview loader
function previewGroupPhoto(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
currentGroupPhoto = e.target.result;
document.getElementById('group-photo-preview').src = currentGroupPhoto;
document.getElementById('group-photo-preview-container').style.display = 'block';
// Reset AI results section
document.getElementById('ia-no-result').style.display = 'block';
document.getElementById('ia-result-container').style.display = 'none';
};
reader.readAsDataURL(file);
}
}
async function simulateIARecognition() {
const btn = document.getElementById('btn-run-ia');
if (btn) {
btn.disabled = true;
btn.textContent = 'Analisando foto com InsightFace...';
}
const apiUrl = getFaceApiUrl();
const thresholdInput = document.getElementById('ia-threshold');
const threshold = thresholdInput ? parseFloat(thresholdInput.value) : (localStorage.getItem('face_api_threshold') ? parseFloat(localStorage.getItem('face_api_threshold')) : 0.40);
let apiResult = null;
let useFallback = false;
// Filter students with embeddings to send to the API
const studentsWithEmbeddings = db.students
.filter(s => s.faceEmbedding && Array.isArray(s.faceEmbedding) && s.faceEmbedding.length > 0)
.map(s => ({ id: s.id, embedding: s.faceEmbedding }));
if (currentGroupPhoto && studentsWithEmbeddings.length > 0) {
try {
const response = await fetch(`${apiUrl}/recognize-presence`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
group_image_base64: currentGroupPhoto,
students: studentsWithEmbeddings,
threshold: threshold
})
});
if (!response.ok) {
const err = await response.json();
throw new Error(err.detail || 'Erro no processamento da imagem.');
}
apiResult = await response.json();
} catch (e) {
console.error("Cloud Face API failed, falling back to simulation.", e);
useFallback = true;
}
} else {
useFallback = true;
if (!currentGroupPhoto) {
alert("Por favor, selecione ou tire uma foto de grupo primeiro.");
if (btn) {
btn.disabled = false;
btn.textContent = 'Simular Reconhecimento IA';
}
return;
}
}
lastRecognitionWasFallback = useFallback;
// Toggle connection banners
const warningEl = document.getElementById('ia-connection-warning');
const successEl = document.getElementById('ia-connection-success');
if (warningEl && successEl) {
if (useFallback) {
warningEl.style.display = 'flex';
successEl.style.display = 'none';
const warningTextEl = warningEl.querySelector('div');
if (warningTextEl) {
if (currentGroupPhoto && studentsWithEmbeddings.length === 0) {
warningTextEl.innerHTML = `<strong>Nenhum Vetor IA Cadastrado:</strong> Nenhum aluno possui selfie com biometria gerada no tatame. Usando modo de simulação/contingência local com presenças simuladas.`;
} else {
warningTextEl.innerHTML = `<strong>Servidor de IA Indisponível:</strong> Não foi possível conectar ao servidor de Reconhecimento Facial em nuvem (${getFaceApiUrl()}). Usando modo de simulação/contingência local.`;
}
}
} else {
warningEl.style.display = 'none';
successEl.style.display = 'flex';
const successTextEl = successEl.querySelector('div');
if (successTextEl) {
successTextEl.innerHTML = `<strong>Conexão Estabelecida:</strong> Reconhecimento facial processado com sucesso pelo servidor de IA em nuvem (${getFaceApiUrl()}).`;
}
}
}
// Populate teacher info card
const teacherContainer = document.getElementById('ia-teacher-photo-container');
if (teacherContainer) {
const teacherRecord = db.students.find(s => s.id === currentSession.user.id);
if (teacherRecord && teacherRecord.selfie) {
teacherContainer.innerHTML = `<img src="${teacherRecord.selfie}" style="width: 44px; height: 44px; border-radius: 50%; object-fit: cover; border: 1.5px solid var(--accent-color);">`;
} else {
const initials = getInitials(currentSession.user.name);
teacherContainer.innerHTML = `<div style="width: 44px; height: 44px; border-radius: 50%; background: var(--bg-secondary); border: 1.5px solid var(--accent-color); display: flex; align-items: center; justify-content: center; font-weight: 700; color: var(--accent-color); font-size: 14px;">${initials}</div>`;
}
}
const teacherNameEl = document.getElementById('ia-teacher-name');
if (teacherNameEl) {
teacherNameEl.textContent = currentSession.user.name;
}
currentIARecognitionResult = [];
db.students.forEach(student => {
const hasSelfie = student.selfie !== null && student.selfie !== '' && student.selfie !== undefined;
let match = false;
let confidence = 0;
if (useFallback) {
if (student.selfie !== null) {
match = Math.random() < 0.30;
if (match) {
confidence = Math.floor(Math.random() * 8) + 91;
}
}
} else if (apiResult && apiResult.matches) {
const apiMatch = apiResult.matches.find(m => m.studentId === student.id);
if (apiMatch) {
match = apiMatch.match;
confidence = apiMatch.confidence;
}
}
currentIARecognitionResult.push({
studentId: student.id,
name: student.name,
belt: student.belt,
hasSelfie: hasSelfie,
match: match,
confidence: confidence
});
});
// Render result table
const tbody = document.getElementById('ia-result-tbody');
tbody.innerHTML = '';
currentIARecognitionResult.forEach(res => {
const tr = document.createElement('tr');
let statusHTML = '';
if (!res.hasSelfie) {
statusHTML = `
<div style="display: flex; align-items: center; gap: 8px;">
<input type="checkbox" disabled style="opacity: 0.5; width: 16px; height: 16px;">
<span class="badge badge-danger">Sem Selfie</span>
</div>
`;
} else {
statusHTML = `
<div style="display: flex; align-items: center; gap: 8px;">
<input type="checkbox" class="ia-toggle" data-student-id="${res.studentId}" ${res.match ? 'checked' : ''} style="accent-color: var(--accent-color); cursor: pointer; width: 16px; height: 16px;">
<span id="ia-status-badge-${res.studentId}" class="badge ${res.match ? 'badge-success' : 'badge-danger'}">
${res.match ? 'Reconhecido' : 'Não Detectado'}
</span>
</div>
`;
}
const confHTML = res.match ? `${res.confidence}%` : '-';
const initials = getInitials(res.name);
tr.innerHTML = `
<td>
<div style="display: flex; align-items: center; gap: 10px;">
<div style="width: 28px; height: 28px; border-radius: 50%; background: var(--bg-secondary); display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: 700; color: var(--text-secondary); border: 1px solid var(--border-color);">
${initials}
</div>
<div style="font-weight: 500; font-size: 13px;">${res.name}</div>
</div>
</td>
<td>${statusHTML}</td>
<td id="ia-confidence-${res.studentId}" style="font-weight: 600; font-size: 13px; color: ${res.match ? 'var(--success-color)' : 'var(--text-muted)'}">${confHTML}</td>
`;
tbody.appendChild(tr);
});
// Add event listeners to toggles
tbody.querySelectorAll('.ia-toggle').forEach(chk => {
chk.addEventListener('change', (e) => {
const studentId = e.target.getAttribute('data-student-id');
const isChecked = e.target.checked;
const resultItem = currentIARecognitionResult.find(r => r.studentId === studentId);
if (resultItem) {
resultItem.match = isChecked;
if (isChecked) {
resultItem.confidence = Math.floor(Math.random() * 8) + 91;
} else {
resultItem.confidence = 0;
}
// Update badge
const badge = document.getElementById(`ia-status-badge-${studentId}`);
if (badge) {
badge.className = isChecked ? 'badge badge-success' : 'badge badge-danger';
badge.textContent = isChecked ? 'Reconhecido' : 'Não Detectado';
}
// Update confidence
const confEl = document.getElementById(`ia-confidence-${studentId}`);
if (confEl) {
confEl.textContent = isChecked ? `${resultItem.confidence}%` : '-';
confEl.style.color = isChecked ? 'var(--success-color)' : 'var(--text-muted)';
}
// Recalculate stats
updateIAStats();
}
});
});
// Initial stats render
updateIAStats();
document.getElementById('ia-no-result').style.display = 'none';
document.getElementById('ia-result-container').style.display = 'block';
if (btn) {
btn.disabled = false;
btn.textContent = 'Reconhecer Faces com InsightFace';
}
}
function updateIAStats() {
const recognizedCount = currentIARecognitionResult.filter(r => r.match).length;
const statsEl = document.getElementById('ia-stats');
let modeBadge = '';
if (lastRecognitionWasFallback) {
modeBadge = `<div class="badge badge-danger" style="margin-bottom: 12px; font-weight: 700; padding: 6px 12px; font-size: 11px; background: rgba(220, 53, 69, 0.15); border: 1px solid #dc3545; color: #dc3545; border-radius: var(--radius-sm); display: inline-block;">⚠️ MODO DE SIMULAÇÃO (API OFFLINE)</div><br>`;
} else {
modeBadge = `<div class="badge badge-success" style="margin-bottom: 12px; font-weight: 700; padding: 6px 12px; font-size: 11px; background: rgba(40, 167, 69, 0.15); border: 1px solid var(--success-color); color: var(--success-color); border-radius: var(--radius-sm); display: inline-block;">✅ PROCESSADO COM INSIGHTFACE CLOUD</div><br>`;
}
if (statsEl) {
statsEl.innerHTML = `
${modeBadge}
<strong>Resultado da Foto do Treino:</strong> <span class="text-accent">${recognizedCount}</span> alunos detectados de <span class="text-accent">${db.students.length}</span> totais.<br>
<span style="font-size: 11px; color: var(--text-muted); display: block; margin-top: 4px;">Alunos sem selfie cadastrada não puderam ser escaneados pela IA. Você pode ajustar os resultados marcando/desmarcando os alunos na lista abaixo antes de aplicar.</span>
`;
}
}
async function applyIAPresence() {
const today = new Date().toISOString().split('T')[0];
const timeStr = new Date().toTimeString().slice(0, 5);
const selectedClass = document.getElementById('ia-class-filter').value;
const teacherName = (currentSession && currentSession.user && currentSession.user.name) ? currentSession.user.name : 'ADM';
let appliedCount = 0;
const promises = [];
for (let res of currentIARecognitionResult) {
if (res.match) {
const student = db.students.find(s => s.id === res.studentId);
if (student) {
// Ensure no double logs for same day
const hasPresenceToday = db.history.some(h => h.studentId === res.studentId && h.date === today);
if (!hasPresenceToday) {
student.attendanceCount++;
// Automatically calculate degrees for kids
if (student.age !== null && student.age < 16) {
if (student.attendanceCount >= 80) student.degrees = 4;
else if (student.attendanceCount >= 60) student.degrees = 3;
else if (student.attendanceCount >= 40) student.degrees = 2;
else if (student.attendanceCount >= 20) student.degrees = 1;
else student.degrees = 0;
}
// Supabase operations
promises.push((async () => {
try {
const { error: histError } = await supabaseClient.from('attendance_history').insert({
date: today,
time: timeStr,
student_id: student.id,
student_name: student.name,
belt: student.belt,
method: 'ia',
class_time: selectedClass,
teacher_name: teacherName
});
if (histError) throw histError;
const { error: studError } = await supabaseClient.from('students').update({
attendance_count: student.attendanceCount,
degrees: student.degrees
}).eq('id', student.id);
if (studError) throw studError;
} catch (e) {
console.error("Failed to sync AI presence to Supabase", e);
alert(`Erro ao sincronizar presença de ${student.name} no Supabase:\n` + (e.message || JSON.stringify(e)));
}
})());
// Local fallback
db.history.unshift({
date: today,
time: timeStr,
studentId: student.id,
studentName: student.name,
belt: student.belt,
method: 'ia',
classTime: selectedClass,
teacherName: teacherName
});
appliedCount++;
}
}
}
}
if (promises.length > 0) {
await Promise.all(promises);
}
await loadDBFromSupabase(); // sync with the cloud (fetches database IDs)
saveDB();
alert(`${appliedCount} presenças registradas automaticamente no banco de dados!`);
// Clear page state
document.getElementById('group-photo-preview-container').style.display = 'none';
document.getElementById('group-photo-input').value = '';
document.getElementById('ia-result-container').style.display = 'none';
document.getElementById('ia-no-result').style.display = 'block';
// Return to initial landing sub-tab on the take-attendance screen
setPresenceTab('ia');
}
// Attendance History (Professor View)
function renderGeneralHistoryTable(filteredHistory = null) {
const list = filteredHistory || db.history;
const tbody = document.getElementById('prof-history-tbody');
tbody.innerHTML = '';
if (list.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: var(--text-muted); padding: 40px;">Nenhum registro de presença encontrado.</td></tr>';
return;
}
list.forEach((log, index) => {
const tr = document.createElement('tr');
const methodHTML = log.method === 'ia'
? '<span class="badge badge-success">🤖 Foto IA</span>'
: '<span class="badge badge-orange">👤 Manual</span>';
const formattedDate = formatDateStr(log.date);
tr.innerHTML = `
<td style="font-weight: 600;">${formattedDate} • ${log.time}</td>
<td style="font-weight: 600; color: var(--text-primary);">${log.studentName}</td>
<td><span class="belt-badge belt-${log.belt.toLowerCase()}" style="font-size: 10px; padding: 4px 8px;">${log.belt}</span></td>
<td><span style="font-size: 12px; font-weight: 500; color: var(--text-secondary);">${log.classTime || 'Qualquer Horário'}</span></td>
<td>${methodHTML}</td>
<td>
<button class="btn btn-danger btn-sm" onclick="deleteHistoryEntry(${index})" style="padding: 6px 12px; font-size: 11px;">
Excluir
</button>
</td>
`;
tbody.appendChild(tr);
});
}
function filterGeneralHistory() {
const studentQuery = document.getElementById('search-history-student').value.toLowerCase();
const dateFilter = document.getElementById('filter-history-date').value;
const methodFilter = document.getElementById('filter-history-method').value;
const filtered = db.history.filter(log => {
const matchesStudent = log.studentName.toLowerCase().includes(studentQuery) || log.studentId.toLowerCase().includes(studentQuery);
const matchesDate = !dateFilter || log.date === dateFilter;
const matchesMethod = methodFilter === 'all' || log.method === methodFilter;
return matchesStudent && matchesDate && matchesMethod;
});
renderGeneralHistoryTable(filtered);
}
function exportAttendanceToPDF() {
const { jsPDF } = window.jspdf;
if (!jsPDF) {
alert("Erro: Biblioteca jsPDF não foi carregada.");
return;
}
const studentQuery = document.getElementById('search-history-student').value.trim();
const dateQuery = document.getElementById('filter-history-date').value;
const methodQuery = document.getElementById('filter-history-method').value;
let list = [...db.history];
if (studentQuery) {
const q = studentQuery.toLowerCase();
list = list.filter(h => h.studentName.toLowerCase().includes(q) || h.studentId.toLowerCase().includes(q));
}
if (dateQuery) {
list = list.filter(h => h.date === dateQuery);
}
if (methodQuery !== 'all') {
list = list.filter(h => h.method === methodQuery);
}
if (list.length === 0) {
alert("Nenhum registro de presença encontrado com os filtros atuais para exportar.");
return;
}
const doc = new jsPDF();
// Behring BJJ Branding Colors (Navy: #1E3A8A, Orange Accent: #E05A00)
// Blue banner
doc.setFillColor(30, 58, 138);
doc.rect(0, 0, 210, 35, 'F');
// Header Title
doc.setTextColor(255, 255, 255);
doc.setFont("helvetica", "bold");
doc.setFontSize(16);
doc.text("ASSOCIAÇÃO BEHRING JIU-JITSU", 105, 14, { align: "center" });
doc.setFont("helvetica", "normal");
doc.setFontSize(10);
doc.text("Relatório de Frequência e Presença de Alunos", 105, 24, { align: "center" });
// Document Metadata Details
doc.setTextColor(50, 50, 50);
doc.setFontSize(9);
let filterText = "Filtros aplicados: ";
const filters = [];
if (studentQuery) filters.push(`Aluno: ${studentQuery}`);
if (dateQuery) filters.push(`Data: ${formatDateStr(dateQuery)}`);
if (methodQuery !== 'all') filters.push(`Método: ${methodQuery === 'ia' ? 'Foto IA' : 'Manual'}`);
filterText += filters.length > 0 ? filters.join(" | ") : "Nenhum (Todos os Registros)";
doc.text(`Data de Emissão: ${new Date().toLocaleDateString('pt-BR')} às ${new Date().toLocaleTimeString('pt-BR')}`, 14, 45);
doc.text(filterText, 14, 51);
doc.text(`Total de Presenças Listadas: ${list.length}`, 14, 57);
// Separator Line
doc.setDrawColor(220, 220, 220);
doc.line(14, 61, 196, 61);
// Rows Data
const tableColumns = ["Data", "Horário", "Aluno", "Faixa", "Turma", "Método"];
const tableRows = list.map(h => [
formatDateStr(h.date),
h.time || '',
h.studentName,
h.belt,
h.classTime || 'Qualquer Horário',
h.method === 'ia' ? 'Foto IA' : 'Manual'
]);
doc.autoTable({
head: [tableColumns],
body: tableRows,
startY: 65,
theme: 'striped',
headStyles: { fillColor: [30, 58, 138], textColor: [255, 255, 255], fontStyle: 'bold' },
alternateRowStyles: { fillColor: [248, 249, 250] },
margin: { top: 65 },
styles: { fontSize: 8.5, cellPadding: 3 }
});
// Save filename based on filters
let fileName = "relatorio_presencas.pdf";
if (studentQuery) {
fileName = `presencas_aluno_${studentQuery.toLowerCase().replace(/\s+/g, '_')}.pdf`;
} else if (dateQuery) {
fileName = `presencas_dia_${dateQuery}.pdf`;
}
doc.save(fileName);
}
async function deleteHistoryEntry(index) {
if (confirm('Deseja realmente excluir este registro de presença? A frequência do aluno será deduzida.')) {
const log = db.history[index];
const student = db.students.find(s => s.id === log.studentId);
if (log.id) {
try {
await supabaseClient.from('attendance_history').delete().eq('id', log.id);
if (student) {
const newCount = Math.max(0, student.attendanceCount - 1);
await supabaseClient.from('students').update({ attendance_count: newCount }).eq('id', student.id);
}
} catch (e) {
console.error("Failed to delete presence record from Supabase", e);
}
}
if (student && student.attendanceCount > 0) {
student.attendanceCount--;
}
db.history.splice(index, 1);
saveDB();
await loadDBFromSupabase();
renderGeneralHistoryTable();
}
}
// Announcements & Events Admin List
function renderProfessorEventsAndAnnouncements() {
// Events List
const evList = document.getElementById('prof-events-list');
evList.innerHTML = '';
if (db.events.length === 0) {
evList.innerHTML = '<p style="color: var(--text-muted); font-size: 13px; text-align: center; padding: 20px;">Nenhum evento agendado.</p>';
} else {
db.events.forEach(ev => {
const dateObj = new Date(ev.date + 'T00:00:00');
const day = String(dateObj.getDate()).padStart(2, '0');
const month = dateObj.toLocaleDateString('pt-BR', { month: 'short' }).slice(0, 3).toUpperCase();
const div = document.createElement('div');
div.className = 'event-item';
div.innerHTML = `
<div class="event-date-box">
<span class="event-date-day">${day}</span>
<span class="event-date-month">${month}</span>
</div>
<div class="event-details" style="flex: 1;">
<h4>${ev.title}</h4>
<p>${ev.type} • Horário: ${ev.time}h</p>
</div>
<div style="display: flex; gap: 8px; align-self: center;">
<button class="btn btn-secondary btn-sm" onclick="openEditEventModal(${ev.id})" style="padding: 6px 12px;">
Editar
</button>
<button class="btn btn-secondary btn-sm" onclick="deleteEvent(${ev.id})" style="padding: 6px 12px; background-color: #dc3545; border-color: #dc3545; color: white;">
Remover
</button>
</div>
`;
evList.appendChild(div);
});
}
// Announcements List
const annList = document.getElementById('prof-announcements-list');
annList.innerHTML = '';
if (db.announcements.length === 0) {
annList.innerHTML = '<p style="color: var(--text-muted); font-size: 13px; text-align: center; padding: 20px;">Mural de avisos vazio.</p>';
} else {
db.announcements.forEach(ann => {
const div = document.createElement('div');
div.style.padding = '16px 0';
div.style.borderBottom = '1px solid var(--border-color)';
div.innerHTML = `
<div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px;">
<div>
<h4 style="font-size: 15px; font-weight: 600;">${ann.title}</h4>
<span style="font-size: 11px; color: var(--text-muted);">${formatDateStr(ann.date)}</span>
</div>
<div style="display: flex; gap: 8px;">
<button class="btn btn-secondary btn-sm" onclick="openEditAnnouncementModal(${ann.id})" style="padding: 4px 8px; font-size: 10px;">
Editar
</button>
<button class="btn btn-secondary btn-sm" onclick="deleteAnnouncement(${ann.id})" style="padding: 4px 8px; font-size: 10px; background-color: #dc3545; border-color: #dc3545; color: white;">
Remover
</button>
</div>
</div>
<p style="font-size: 13px; line-height: 1.5; color: var(--text-secondary);">${ann.content}</p>
`;
annList.appendChild(div);
});
}
// Render dojo schedules editor
renderProfessorSchedules();
}
// Add/Delete Student Handlers
async function handleAddStudent(event) {
event.preventDefault();
const name = document.getElementById('new-student-name').value.trim();
const belt = document.getElementById('new-student-belt').value;
const degrees = parseInt(document.getElementById('new-student-degrees').value);
const id = name.toLowerCase().replace(/\s+/g, '_');
if (db.students.some(s => s.id === id)) {
alert('Este aluno já está cadastrado!');
return;
}
const newStudent = {
id,
name,
belt,
degrees,
attendanceCount: 0,
selfie: null,
streak: 100,
address: '',
age: 18,
guardian: '',
objective: '',
weeklyGoal: 3,
profession: '',
schoolName: '',
hasLoan: false,
kimonoBrand: '',
kimonoSize: '',
kimonoDate: '',
evaluationParents: 'Pendente',
evaluationSchool: 'Pendente'
};
try {
const { error } = await supabaseClient.from('students').insert({
id: newStudent.id,
name: newStudent.name,
senha: newStudent.password || 'aluno123',
belt: newStudent.belt,
degrees: newStudent.degrees,
attendance_count: newStudent.attendanceCount,
selfie: newStudent.selfie,
streak: newStudent.streak,
address: newStudent.address,
age: newStudent.age,
guardian: newStudent.guardian,
objective: newStudent.objective,
weekly_goal: newStudent.weeklyGoal,
profession: newStudent.profession,
school_name: newStudent.schoolName,
has_loan: newStudent.hasLoan,
kimono_brand: newStudent.kimonoBrand,
kimono_size: newStudent.kimonoSize,
kimono_date: newStudent.kimonoDate,
evaluation_parents: newStudent.evaluationParents,
evaluation_school: newStudent.evaluationSchool,
face_embedding: null
});
if (error) throw error;
} catch (e) {
console.error("Failed to sync new student creation to Supabase", e);
alert("Erro ao salvar aluno no banco de dados na nuvem:\n" + (e.message || JSON.stringify(e)));
return;
}
db.students.push(newStudent);
saveDB();
closeModal('add-student-modal');
document.getElementById('new-student-name').value = '';
renderStudentsTable();
alert(`Aluno ${name} cadastrado com sucesso!`);
}
// Promot Graduation Modal
// Promot Graduation Modal
function openGraduationModal(studentId) {
const student = db.students.find(s => s.id === studentId);
if (student) {
document.getElementById('grad-modal-student-id').value = student.id;
document.getElementById('grad-modal-student-name').textContent = student.name;
document.getElementById('grad-modal-student-info').textContent = `Faixa: ${student.belt} • ${student.degrees} Graus`;
const avatar = document.getElementById('grad-modal-avatar');
if (student.selfie) {
avatar.src = student.selfie.startsWith('data:') ? student.selfie : getPresetAvatar(student.id);
} else {
avatar.src = getPresetAvatar(student.id);
}
// Populate fields
document.getElementById('grad-student-name').value = student.name || '';
document.getElementById('grad-student-email').value = student.email || '';
document.getElementById('grad-student-whatsapp').value = student.whatsapp || '';
document.getElementById('grad-student-password').value = student.password || 'aluno123';
document.getElementById('grad-student-age').value = (student.age !== null && student.age !== undefined) ? student.age : '';
document.getElementById('grad-student-guardian').value = student.guardian || '';
document.getElementById('grad-student-address').value = student.address || '';
document.getElementById('grad-student-profession').value = student.profession || '';
document.getElementById('grad-student-school-name').value = student.schoolName || '';
document.getElementById('grad-student-objective').value = student.objective || '';
document.getElementById('grad-student-weekly-goal').value = student.weeklyGoal || 3;
const hasLoanChk = document.getElementById('grad-student-has-loan');
hasLoanChk.checked = student.hasLoan || false;
document.getElementById('grad-student-kimono-brand').value = student.kimonoBrand || '';
document.getElementById('grad-student-kimono-size').value = student.kimonoSize || '';
document.getElementById('grad-student-kimono-date').value = student.kimonoDate || '';
// Dynamically configure inputs based on initial age
handleGradAgeChange();
// Restore belt and degrees to the student's specific saved values
document.getElementById('grad-student-belt').value = student.belt || 'Branca';
document.getElementById('grad-student-degrees').value = student.degrees || 0;
toggleGradKimonoInputs();
openModal('grad-student-modal');
}
}
function toggleGradGuardianInput() {
const ageVal = document.getElementById('grad-student-age').value;
const age = ageVal !== '' ? parseInt(ageVal) : null;
const guardianGroup = document.getElementById('grad-guardian-group');
if (age !== null && age < 18) {
guardianGroup.style.display = 'block';
} else {
guardianGroup.style.display = 'none';
}
}
function handleGradAgeChange() {
toggleGradGuardianInput();
const studentId = document.getElementById('grad-modal-student-id').value;
const ageVal = document.getElementById('grad-student-age').value;
const isKid = ageVal !== '' && parseInt(ageVal) < 16;
const student = db.students.find(s => s.id === studentId);
if (student) {
const beltSelect = document.getElementById('grad-student-belt');
const currentSelectedBelt = beltSelect.value;
beltSelect.innerHTML = '';
const beltList = isKid ? KIDS_BELTS : ADULT_BELTS;
beltList.forEach(belt => {
const opt = document.createElement('option');
opt.value = belt;
opt.textContent = belt;
beltSelect.appendChild(opt);
});
if (beltList.includes(currentSelectedBelt)) {
beltSelect.value = currentSelectedBelt;
} else {
beltSelect.value = 'Branca';
}
const kidsPanel = document.getElementById('kids-evaluation-panel');
if (kidsPanel) {
if (isKid) {
kidsPanel.style.display = 'block';
const dojoInput = document.getElementById('grad-pillar-dojo');
const isEligible = student.attendanceCount >= 100;
dojoInput.value = isEligible ? 'Elegível' : `Pendente (${student.attendanceCount}/100)`;
dojoInput.style.color = isEligible ? 'var(--success-color)' : 'var(--text-muted)';
const badgeContainer = document.getElementById('kids-eligibility-badge');
if (isEligible) {
badgeContainer.innerHTML = `<span class="badge badge-success" style="font-size: 11px; padding: 6px 12px; text-transform: uppercase;">👑 Elegível para Avaliação de Faixa (100+ Treinos)</span>`;
} else {
badgeContainer.innerHTML = `<span class="badge badge-danger" style="font-size: 11px; padding: 6px 12px; text-transform: uppercase;">Abaixo de 100 Treinos (${student.attendanceCount}/100)</span>`;
}
document.getElementById('grad-pillar-parents').value = student.evaluationParents || 'Pendente';
document.getElementById('grad-pillar-school').value = student.evaluationSchool || 'Pendente';
} else {
kidsPanel.style.display = 'none';
}
}
}
}
function toggleGradKimonoInputs() {
const hasLoan = document.getElementById('grad-student-has-loan').checked;
const kimonoInputsDiv = document.getElementById('grad-kimono-loan-inputs');
if (hasLoan) {
kimonoInputsDiv.style.display = 'block';
} else {
kimonoInputsDiv.style.display = 'none';
}
}
async function handleSaveGraduation(event) {
try {
event.preventDefault();
const id = document.getElementById('grad-modal-student-id').value;
const student = db.students.find(s => s.id === id);
if (student) {
const oldBelt = student.belt;
student.belt = document.getElementById('grad-student-belt').value;
student.degrees = parseInt(document.getElementById('grad-student-degrees').value);
student.classTime = 'Qualquer Horário';
student.name = document.getElementById('grad-student-name').value.trim();
student.email = document.getElementById('grad-student-email').value.trim();
student.whatsapp = document.getElementById('grad-student-whatsapp').value.trim();
student.password = document.getElementById('grad-student-password').value.trim() || 'aluno123';
const ageVal = document.getElementById('grad-student-age').value;
student.age = ageVal !== '' ? parseInt(ageVal) : null;
const isKid = student.age !== null && student.age < 16;
const isMinor = student.age !== null && student.age < 18;
// Reset attendance count if belt changed
if (oldBelt !== student.belt) {
student.attendanceCount = 0;
if (isKid) student.degrees = 0;
}
if (isKid) {
student.evaluationParents = document.getElementById('grad-pillar-parents').value;
student.evaluationSchool = document.getElementById('grad-pillar-school').value;
} else {
student.evaluationParents = 'Pendente';
student.evaluationSchool = 'Pendente';
}
if (isMinor) {
student.guardian = document.getElementById('grad-student-guardian').value.trim();
} else {
student.guardian = '';
}
student.address = document.getElementById('grad-student-address').value.trim();
student.profession = document.getElementById('grad-student-profession').value.trim();
student.schoolName = document.getElementById('grad-student-school-name').value.trim();
student.objective = document.getElementById('grad-student-objective').value.trim();
student.weeklyGoal = parseInt(document.getElementById('grad-student-weekly-goal').value) || 3;
student.hasLoan = document.getElementById('grad-student-has-loan').checked;
if (student.hasLoan) {
student.kimonoBrand = document.getElementById('grad-student-kimono-brand').value.trim();
student.kimonoSize = document.getElementById('grad-student-kimono-size').value.trim();
student.kimonoDate = document.getElementById('grad-student-kimono-date').value;
} else {
student.kimonoBrand = '';
student.kimonoSize = '';
student.kimonoDate = '';
}
let syncSuccess = true;
try {
await syncStudentToCloud(student);
} catch (e) {
console.error("Failed to save student details to Supabase", e);
syncSuccess = false;
}
saveDB();
closeModal('grad-student-modal');
renderStudentsTable();
if (syncSuccess) {
alert('Ficha do aluno atualizada com sucesso!');
} else {
alert('Aviso: Os dados foram salvos temporariamente no navegador, mas falharam ao sincronizar com o Supabase. Por favor, verifique sua conexão ou a estrutura do banco de dados.');
}
}
} catch (err) {
console.error("Critical error in handleSaveGraduation:", err);
alert("Erro crítico ao salvar dados do aluno: " + err.message);
closeModal('grad-student-modal');
}
}
async function handleDeleteStudent() {
const id = document.getElementById('grad-modal-student-id').value;
const student = db.students.find(s => s.id === id);
if (!student) return;
const confirmDelete = confirm(`Tem certeza que deseja excluir o aluno "${student.name}" definitivamente? Todos os dados dele serão apagados.`);
if (!confirmDelete) return;
// 1. Delete from Supabase
if (supabaseClient) {
try {
// First check if the student exists in Supabase to know if it's an RLS issue or just missing from cloud
const { data: existsData, error: existsError } = await supabaseClient.from('students').select('id').eq('id', student.id);
if (existsError) throw existsError;
const existedInCloud = existsData && existsData.length > 0;
// Delete associated attendance logs from Supabase
await supabaseClient.from('attendance_history').delete().eq('student_id', student.id);
// Delete the student from Supabase
const { data: deleteData, error: deleteError } = await supabaseClient.from('students').delete().eq('id', student.id).select();
if (deleteError) throw deleteError;
// If it existed in the cloud but nothing was deleted, it is likely an RLS permission issue
if (existedInCloud && (!deleteData || deleteData.length === 0)) {
throw new Error("O registro existe no Supabase, mas não pôde ser excluído. Isso geralmente ocorre devido a políticas de Segurança de Nível de Linha (RLS) ativas. Certifique-se de que o RLS está desativado no Supabase para a tabela 'students' (execute ALTER TABLE public.students DISABLE ROW LEVEL SECURITY; no SQL Editor).");
}
} catch (e) {
console.error("Failed to delete student from Supabase", e);
alert("Erro ao excluir aluno do banco de dados na nuvem:\n" + (e.message || e));
return;
}
}
// 2. Delete from local db
db.students = db.students.filter(s => s.id !== student.id);
// Also clean up local history logs for this student
db.history = db.history.filter(h => h.studentId !== student.id);
saveDB();
// 3. Clear from manual attendance list if present
if (manualPresenceList[student.id] !== undefined) {
delete manualPresenceList[student.id];
}
closeModal('grad-student-modal');
renderStudentsTable();
renderPresenceChecklist();
alert("Aluno excluído com sucesso!");
}
// Add/Delete Events & Announcements Handlers
async function handleAddEvent(event) {
event.preventDefault();
const title = document.getElementById('event-title').value.trim();
const type = document.getElementById('event-type').value;
const date = document.getElementById('event-date').value;
const time = document.getElementById('event-time').value;
const idVal = document.getElementById('edit-event-id').value;
const isEdit = idVal !== '';
const publishApp = document.getElementById('event-publish-app') ? document.getElementById('event-publish-app').checked : true;
const shareWhatsapp = document.getElementById('event-share-whatsapp') ? document.getElementById('event-share-whatsapp').checked : false;
const newEvent = {
id: isEdit ? parseInt(idVal) : Date.now(),
title,
type,
date,
time
};
if (publishApp) {
try {
await supabaseClient.from('events').upsert(newEvent);
} catch (e) {
console.error("Failed to save event to Supabase", e);
}
if (isEdit) {
const idx = db.events.findIndex(e => e.id === newEvent.id);
if (idx !== -1) {
db.events[idx] = newEvent;
}
} else {
db.events.push(newEvent);
}
saveDB();
renderProfessorEventsAndAnnouncements();
}
if (shareWhatsapp) {
const formattedDate = formatDateStr(date);
const msg = `*BEHRING JIU-JITSU - NOVO EVENTO* 🗓️\n\n*${title}*\nTipo: ${type}\nData: ${formattedDate} às ${time}h\n\nAcesse o aplicativo para confirmar presença:\nhttps://associacaobehring.netlify.app`;
navigator.clipboard.writeText(msg).catch(err => console.error("Clipboard copy failed:", err));
alert("Notificação copiada para a área de transferência! Cole-a no grupo do WhatsApp a seguir.");
window.open("https://chat.whatsapp.com/EAwwEG6l84XFLo5M0WChVo", "_blank");
}
closeModal('add-event-modal');
document.getElementById('event-title').value = '';
document.getElementById('event-date').value = '';
document.getElementById('edit-event-id').value = '';
if (document.getElementById('event-share-whatsapp')) {
document.getElementById('event-share-whatsapp').checked = false;
}
alert(isEdit ? 'Evento atualizado com sucesso!' : 'Novo evento agendado com sucesso!');
}
async function deleteEvent(id) {
if (confirm('Deseja realmente excluir este evento?')) {
try {
await supabaseClient.from('events').delete().eq('id', id);
} catch (e) {
console.error("Failed to delete event from Supabase", e);
}
db.events = db.events.filter(e => e.id !== id);
saveDB();
renderProfessorEventsAndAnnouncements();
}
}
async function handleAddAnnouncement(event) {
event.preventDefault();
const title = document.getElementById('ann-title').value.trim();
const content = document.getElementById('ann-content').value.trim();
const idVal = document.getElementById('edit-ann-id').value;
const isEdit = idVal !== '';
const date = isEdit ? db.announcements.find(a => a.id === parseInt(idVal)).date : new Date().toISOString().split('T')[0];
const publishApp = document.getElementById('ann-publish-app') ? document.getElementById('ann-publish-app').checked : true;
const shareWhatsapp = document.getElementById('ann-share-whatsapp') ? document.getElementById('ann-share-whatsapp').checked : false;
const newAnn = {
id: isEdit ? parseInt(idVal) : Date.now(),
title,
content,
date
};
if (publishApp) {
try {
await supabaseClient.from('announcements').upsert(newAnn);
} catch (e) {
console.error("Failed to save announcement to Supabase", e);
}
if (isEdit) {
const idx = db.announcements.findIndex(a => a.id === newAnn.id);
if (idx !== -1) {
db.announcements[idx] = newAnn;
}
} else {
db.announcements.push(newAnn);
}
saveDB();
renderProfessorEventsAndAnnouncements();
}
if (shareWhatsapp) {
const msg = `*BEHRING JIU-JITSU - COMUNICADO OFICIAL* 🥋\n\n*${title}*\n\n${content}\n\nLeia mais no aplicativo:\nhttps://associacaobehring.netlify.app`;
navigator.clipboard.writeText(msg).catch(err => console.error("Clipboard copy failed:", err));
alert("Notificação copiada para a área de transferência! Cole-a no grupo do WhatsApp a seguir.");
window.open("https://chat.whatsapp.com/EAwwEG6l84XFLo5M0WChVo", "_blank");
}
closeModal('add-announcement-modal');
document.getElementById('ann-title').value = '';
document.getElementById('ann-content').value = '';
document.getElementById('edit-ann-id').value = '';
if (document.getElementById('ann-share-whatsapp')) {
document.getElementById('ann-share-whatsapp').checked = false;
}
alert(isEdit ? 'Comunicado atualizado com sucesso!' : 'Aviso publicado com sucesso!');
}
async function deleteAnnouncement(id) {
if (confirm('Deseja realmente remover este aviso?')) {
try {
await supabaseClient.from('announcements').delete().eq('id', id);
} catch (e) {
console.error("Failed to delete announcement from Supabase", e);
}
db.announcements = db.announcements.filter(a => a.id !== id);
saveDB();
renderProfessorEventsAndAnnouncements();
}
}
// ==================== STUDENT VIEW CONTROLLERS ====================
function renderStudentHome() {
const student = currentSession.user;
// Dynamically calculate attendance count from history
const actualPresenceCount = db.history.filter(h => h.studentId === student.id).length;
student.attendanceCount = actualPresenceCount;
document.getElementById('student-welcome-title').textContent = `Olá, ${student.name.split(' ')[0]}!`;
document.getElementById('student-total-classes').textContent = actualPresenceCount;
document.getElementById('student-streak').textContent = `${student.streak}%`;
const beltEl = document.getElementById('student-belt-name');
if (beltEl) {
const sanitized = student.belt.toLowerCase().replace(/á/g, 'a').replace(/ê/g, 'e').replace(/\s+/g, '-');
beltEl.innerHTML = `<span class="belt-badge belt-${sanitized}" style="font-size: 14px; padding: 6px 14px; display: inline-block;">${student.belt}</span> <span style="font-size: 12px; margin-left: 8px; font-weight: 600; color: var(--text-secondary);">${student.degrees} ${student.degrees === 1 ? 'Grau' : 'Graus'}</span>`;
}
// Warning Banner if selfie is missing
const selfieAlert = document.getElementById('student-selfie-alert');
if (!student.selfie) {
selfieAlert.style.display = 'flex';
} else {
selfieAlert.style.display = 'none';
}
// Latest Announcements on Student Home
const annTimeline = document.getElementById('student-home-announcements');
annTimeline.innerHTML = '';
if (db.announcements.length === 0) {
annTimeline.innerHTML = '<p style="color: var(--text-muted); font-size: 13px;">Nenhum aviso no mural.</p>';
} else {
db.announcements.slice(0, 2).forEach(ann => {
const div = document.createElement('div');
div.style.padding = '12px;';
div.style.borderLeft = '3px solid var(--accent-color)';
div.style.background = 'rgba(255, 255, 255, 0.01)';
div.style.marginBottom = '12px';
div.style.paddingLeft = '12px';
div.innerHTML = `
<h4 style="font-size: 14px; font-weight: 600; margin-bottom: 2px;">${linkify(ann.title)}</h4>
<span style="font-size: 10px; color: var(--text-muted); display: block; margin-bottom: 6px;">${formatDateStr(ann.date)}</span>
<p style="font-size: 12px; line-height: 1.4;">${linkify(ann.content)}</p>
`;
annTimeline.appendChild(div);
});
}
// Upcoming Events on Student Home
const evList = document.getElementById('student-home-events');
evList.innerHTML = '';
if (db.events.length === 0) {
evList.innerHTML = '<p style="color: var(--text-muted); font-size: 13px;">Nenhum evento na agenda.</p>';
} else {
db.events.slice(0, 2).forEach(ev => {
const dateObj = new Date(ev.date + 'T00:00:00');
const day = String(dateObj.getDate()).padStart(2, '0');
const month = dateObj.toLocaleDateString('pt-BR', { month: 'short' }).slice(0, 3).toUpperCase();
const div = document.createElement('div');
div.className = 'event-item';
div.innerHTML = `
<div class="event-date-box" style="width: 50px; height: 50px;">
<span class="event-date-day" style="font-size: 16px;">${day}</span>
<span class="event-date-month" style="font-size: 9px;">${month}</span>
</div>
<div class="event-details">
<h4 style="font-size: 14px;">${linkify(ev.title)}</h4>
<p style="font-size: 11px;">${ev.type} • ${ev.time}h</p>
</div>
`;
evList.appendChild(div);
});
}
}
function renderStudentProfile() {
const student = currentSession.user;
// Dynamically calculate attendance count from history
const actualPresenceCount = db.history.filter(h => h.studentId === student.id).length;
student.attendanceCount = actualPresenceCount;
document.getElementById('student-profile-name').textContent = student.name;
// Set profile picture
const pic = document.getElementById('student-profile-pic');
if (student.selfie) {
pic.src = student.selfie.startsWith('data:') ? student.selfie : getPresetAvatar(student.id);
pic.style.border = '3px solid var(--success-color)';
} else {
pic.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%236f6f78'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z'/%3E%3C/svg%3E`;
pic.style.border = '3px solid var(--border-color)';
}
// Toggle selfie embedding warning
const embeddingWarning = document.getElementById('student-selfie-embedding-warning');
if (embeddingWarning) {
if (student.selfie && (!student.faceEmbedding || !Array.isArray(student.faceEmbedding) || student.faceEmbedding.length === 0)) {
embeddingWarning.style.display = 'block';
} else {
embeddingWarning.style.display = 'none';
}
}
// Set Belt badge
const badge = document.getElementById('student-profile-belt-badge');
const sanitizedBelt = student.belt.toLowerCase().replace(/á/g, 'a').replace(/ê/g, 'e').replace(/\s+/g, '-');
badge.className = `belt-badge belt-${sanitizedBelt}`;
badge.textContent = `Faixa ${student.belt}`;
document.getElementById('student-profile-degrees').textContent = `${student.degrees} ${student.degrees === 1 ? 'grau' : 'graus'}`;
// Update Belt Roadmap timeline dynamically
const roadmapContainer = document.getElementById('student-belt-roadmap');
if (roadmapContainer) {
roadmapContainer.innerHTML = '';
const steps = (student.age !== null && student.age < 16) ? KIDS_BELTS : ADULT_BELTS;
const currentIdx = steps.indexOf(student.belt);
steps.forEach((step, idx) => {
const stepEl = document.createElement('div');
stepEl.className = `roadmap-step ${idx <= currentIdx ? 'active' : ''}`;
let initial = step.charAt(0);
if (step.includes('Cinza')) initial = 'G';
else if (step.includes('Amarela')) initial = 'Y';
else if (step.includes('Laranja')) initial = 'O';
else if (step.includes('Verde')) initial = 'GR';
const sanitized = step.toLowerCase().replace(/á/g, 'a').replace(/ê/g, 'e').replace(/\s+/g, '-');
stepEl.innerHTML = `
<div class="roadmap-circle belt-${sanitized}">${initial}</div>
<span class="roadmap-label" style="font-size: 8px; white-space: nowrap;">${step}</span>
`;
roadmapContainer.appendChild(stepEl);
});
}
// Show/hide Kids 3 Pillars Evaluation Status in profile
const kidsStatusPanel = document.getElementById('student-kids-evaluation-status');
if (kidsStatusPanel) {
if (student.age !== null && student.age < 16) {
kidsStatusPanel.style.display = 'block';
const dojoEl = document.getElementById('stud-status-dojo');
const isEligible = student.attendanceCount >= 100;
dojoEl.textContent = isEligible ? 'Elegível (100+)' : `Pendente (${student.attendanceCount}/100)`;
dojoEl.style.color = isEligible ? 'var(--success-color)' : 'var(--text-muted)';
const parentsEl = document.getElementById('stud-status-parents');
const pStatus = student.evaluationParents || 'Pendente';
parentsEl.textContent = pStatus;
parentsEl.style.color = pStatus === 'Aprovado' ? 'var(--success-color)' : (pStatus === 'Reprovado' ? '#dc3545' : 'var(--text-muted)');
const schoolEl = document.getElementById('stud-status-school');
const sStatus = student.evaluationSchool || 'Pendente';
schoolEl.textContent = sStatus;
schoolEl.style.color = sStatus === 'Aprovado' ? 'var(--success-color)' : (sStatus === 'Reprovado' ? '#dc3545' : 'var(--text-muted)');
} else {
kidsStatusPanel.style.display = 'none';
}
}
// Populate degrees dots tracker
const degreesContainer = document.getElementById('degrees-tracker');
degreesContainer.innerHTML = '';
for (let i = 1; i <= 4; i++) {
const dot = document.createElement('div');
dot.style.width = '24px';
dot.style.height = '24px';
dot.style.borderRadius = '50%';
dot.style.border = '2px solid rgba(255, 255, 255, 0.1)';
dot.style.display = 'flex';
dot.style.alignItems = 'center';
dot.style.justifyContent = 'center';
dot.style.fontSize = '10px';
dot.style.fontWeight = 'bold';
if (i <= student.degrees) {
dot.style.background = 'var(--accent-color)';
dot.style.borderColor = 'var(--accent-color)';
dot.style.color = '#ffffff';
dot.textContent = 'I';
} else {
dot.style.background = 'rgba(0, 0, 0, 0.2)';
dot.style.color = 'var(--text-muted)';
dot.textContent = '';
}
degreesContainer.appendChild(dot);
}
// Call secondary renderers for details & BJJ History
renderStudentProfileDetails();
renderStudentBJJHistory();
}
let cameraStream = null;
async function openCameraModal() {
openModal('camera-modal');
const video = document.getElementById('camera-video');
try {
cameraStream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'user', width: { ideal: 640 }, height: { ideal: 480 } },
audio: false
});
if (video) {
video.srcObject = cameraStream;
video.play().catch(e => console.warn("Video play failed", e));
}
} catch (err) {
console.error("Camera access failed", err);
alert("Não foi possível acessar a câmera do dispositivo. Verifique as permissões ou envie um arquivo da galeria.");
closeCameraModal();
}
}
function closeCameraModal() {
closeModal('camera-modal');
if (cameraStream) {
cameraStream.getTracks().forEach(track => track.stop());
cameraStream = null;
}
const video = document.getElementById('camera-video');
if (video) video.srcObject = null;
}
function getFaceApiUrl() {
const url = localStorage.getItem('face_api_url') || 'http://localhost:8000';
return url.replace(/\/$/, '');
}
async function extractEmbeddingFromAPI(dataURL) {
const apiUrl = getFaceApiUrl();
try {
const response = await fetch(`${apiUrl}/extract-embedding`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ image_base64: dataURL })
});
if (!response.ok) {
const err = await response.json();
throw new Error(err.detail || 'Falha ao extrair vetor facial.');
}
const data = await response.json();
return data.embedding;
} catch (e) {
console.warn("Failed to extract facial embedding from Cloud API", e);
return null;
}
}
async function backfillMissingEmbeddings() {
updateBackfillCount();
const studentsToFix = db.students.filter(s => s.selfie && s.selfie.startsWith('data:') && (!s.faceEmbedding || s.faceEmbedding.length === 0));
if (studentsToFix.length === 0) return;
console.log(`Starting background backfill of facial embeddings for ${studentsToFix.length} students...`);
for (let student of studentsToFix) {
try {
const embedding = await extractEmbeddingFromAPI(student.selfie);
if (embedding) {
student.faceEmbedding = embedding;
await syncStudentToCloud(student);
console.log(`Successfully backfilled face embedding for student: ${student.name}`);
}
} catch (e) {
console.warn(`Failed to backfill embedding for ${student.name}:`, e);
}
}
saveDB();
updateBackfillCount();
}
function updateBackfillCount() {
const countEl = document.getElementById('ia-backfill-count');
if (countEl) {
const count = db.students.filter(s => s.selfie && s.selfie.startsWith('data:') && (!s.faceEmbedding || s.faceEmbedding.length === 0)).length;
countEl.textContent = count;
}
}
async function runManualBackfill() {
const btn = document.getElementById('btn-ia-backfill');
const countEl = document.getElementById('ia-backfill-count');
// Filter students who have a valid base64 selfie but do NOT have face embeddings
const studentsToFix = db.students.filter(s => s.selfie && s.selfie.startsWith('data:') && (!s.faceEmbedding || s.faceEmbedding.length === 0));
if (studentsToFix.length === 0) {
alert("Todos os alunos com selfie válida já possuem vetor facial (Vetor IA) gerado!");
return;
}
if (btn) {
btn.disabled = true;
btn.textContent = `Processando 0/${studentsToFix.length}...`;
}
let successCount = 0;
let failCount = 0;
for (let i = 0; i < studentsToFix.length; i++) {
const student = studentsToFix[i];
if (btn) btn.textContent = `Sincronizando ${i + 1}/${studentsToFix.length} (${student.name})...`;
try {
const embedding = await extractEmbeddingFromAPI(student.selfie);
if (embedding) {
student.faceEmbedding = embedding;
await syncStudentToCloud(student);
successCount++;
} else {
failCount++;
}
} catch (e) {
console.warn(`Failed to sync embedding for ${student.name}:`, e);
failCount++;
}
// Update count dynamically in UI
if (countEl) {
const currentToFix = db.students.filter(s => s.selfie && s.selfie.startsWith('data:') && (!s.faceEmbedding || s.faceEmbedding.length === 0)).length;
countEl.textContent = currentToFix;
}
}
saveDB();
if (btn) {
btn.disabled = false;
btn.textContent = "Sincronizar Vetores Faltantes";
}
alert(`Sincronização manual concluída!\n\nSucesso: ${successCount} aluno(s)\nFalhas: ${failCount} aluno(s)`);
// Refresh stats if we are on the IA photo page
renderPresenceChecklist();
updateIAStats();
}
async function captureSelfie() {
const video = document.getElementById('camera-video');
const canvas = document.getElementById('camera-canvas');
if (video && canvas) {
const context = canvas.getContext('2d');
canvas.width = video.videoWidth || 640;
canvas.height = video.videoHeight || 480;
// Mirror horizontally to match preview
context.translate(canvas.width, 0);
context.scale(-1, 1);
context.drawImage(video, 0, 0, canvas.width, canvas.height);
const dataURL = canvas.toDataURL('image/jpeg', 0.85);
const captureBtn = document.querySelector('#camera-modal button[onclick="captureSelfie()"]');
const originalText = captureBtn ? captureBtn.innerHTML : '📸 Capturar';
if (captureBtn) {
captureBtn.innerHTML = '⏱️ Processando...';
captureBtn.disabled = true;
}
try {
await saveSelfieData(dataURL);
} finally {
if (captureBtn) {
captureBtn.innerHTML = originalText;
captureBtn.disabled = false;
}
closeCameraModal();
}
}
}
let selfieTarget = 'student';
let tempProfessorPhotoData = null;
function openStudentCamera() {
selfieTarget = 'student';
openCameraModal();
}
function openProfessorCamera() {
selfieTarget = 'professor';
openCameraModal();
}
async function saveSelfieData(dataURL) {
if (selfieTarget === 'professor') {
tempProfessorPhotoData = dataURL;
const previewEl = document.getElementById('prof-photo-modal-preview');
if (previewEl) previewEl.src = dataURL;
const saveBtn = document.getElementById('btn-save-prof-photo');
if (saveBtn) saveBtn.disabled = false;
return;
}
const student = db.students.find(s => s.id === currentSession.user.id);
if (student) {
student.selfie = dataURL;
const embedding = await extractEmbeddingFromAPI(dataURL);
student.faceEmbedding = embedding;
try {
await syncStudentToCloud(student);
} catch (e) {
console.error("Failed to sync selfie to Supabase", e);
}
saveDB();
currentSession.user = student;
saveSessionToLocalStorage();
renderStudentProfile();
renderStudentHome();
if (embedding) {
alert('Selfie de referência cadastrada com sucesso! Agora você poderá usar a computação de presença automática por Foto IA.');
} else {
alert('Selfie salva localmente, mas não foi possível conectar ao servidor de Reconhecimento Facial em nuvem. A presença automática por Foto IA não funcionará para este aluno até que você cadastre novamente com o servidor de IA ativo.');
}
}
}
function uploadStudentSelfie(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = async function(e) {
const dataURL = e.target.result;
await saveSelfieData(dataURL);
};
reader.readAsDataURL(file);
}
}
function uploadProfessorPhoto(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const dataURL = e.target.result;
tempProfessorPhotoData = dataURL;
const previewEl = document.getElementById('prof-photo-modal-preview');
if (previewEl) previewEl.src = dataURL;
const saveBtn = document.getElementById('btn-save-prof-photo');
if (saveBtn) saveBtn.disabled = false;
};
reader.readAsDataURL(file);
}
}
async function saveProfessorPhoto() {
const profId = currentSession.user.id;
const profName = currentSession.user.name;
let studentRecord = db.students.find(s => s.id === profId);
const isSenpai = profId.startsWith('senpai_');
const isSensei = profId.startsWith('sensei_');
// Check if selfie exists or was captured
const hasSelfie = tempProfessorPhotoData || (studentRecord && studentRecord.selfie);
if (!hasSelfie) {
alert("Por favor, tire uma selfie para identificação antes de salvar.");
return;
}
const saveBtn = document.getElementById('btn-save-prof-photo');
const originalText = saveBtn ? saveBtn.textContent : 'Salvar e Continuar';
if (saveBtn) {
saveBtn.textContent = 'Processando...';
saveBtn.disabled = true;
}
const beltSelect = document.getElementById('prof-photo-modal-belt');
let selectedBelt = studentRecord ? studentRecord.belt : (isSensei ? 'Preta' : 'Branca');
if (isSenpai && beltSelect) {
selectedBelt = beltSelect.value;
}
let embedding = null;
if (tempProfessorPhotoData) {
embedding = await extractEmbeddingFromAPI(tempProfessorPhotoData);
} else if (studentRecord && studentRecord.faceEmbedding) {
embedding = studentRecord.faceEmbedding;
}
if (!studentRecord) {
studentRecord = {
id: profId,
name: profName,
password: 'aluno123',
email: '',
whatsapp: '',
belt: selectedBelt,
degrees: 0,
attendanceCount: 0,
selfie: tempProfessorPhotoData || null,
faceEmbedding: embedding,
streak: 100,
address: '',
age: null,
guardian: '',
objective: '',
weeklyGoal: 3,
profession: 'Professor',
schoolName: '',
hasLoan: false,
kimonoBrand: '',
kimonoSize: '',
kimonoDate: '',
classTime: 'Qualquer Horário'
};
db.students.push(studentRecord);
} else {
if (tempProfessorPhotoData) {
studentRecord.selfie = tempProfessorPhotoData;
studentRecord.faceEmbedding = embedding;
}
studentRecord.belt = selectedBelt;
}
try {
await syncStudentToCloud(studentRecord);
alert('Dados cadastrados com sucesso!');
closeModal('professor-photo-modal');
renderStudentsTable();
renderProfessorDashboard();
} catch (e) {
console.error("Failed to save professor onboarding details", e);
alert("Erro ao salvar dados de identificação: " + (e.message || JSON.stringify(e)));
}
if (saveBtn) {
saveBtn.textContent = originalText;
saveBtn.disabled = false;
}
saveDB();
}
// Student Individual History Table
function renderStudentHistoryTable(filteredHistory = null) {
const student = currentSession.user;
const historyList = filteredHistory || db.history.filter(h => h.studentId === student.id);
const tbody = document.getElementById('student-history-tbody');
tbody.innerHTML = '';
if (historyList.length === 0) {
tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: var(--text-muted); padding: 40px;">Você ainda não possui presenças registradas.</td></tr>';
return;
}
historyList.forEach(log => {
const tr = document.createElement('tr');
const methodHTML = log.method === 'ia'
? '<span class="badge badge-success">🤖 Foto IA</span>'
: '<span class="badge badge-orange">👤 Manual</span>';
const formattedDate = formatDateStr(log.date);
tr.innerHTML = `
<td style="font-weight: 600;">${formattedDate} • ${log.time}</td>
<td><span style="font-size: 12px; font-weight: 500; color: var(--text-secondary);">${log.classTime || 'Qualquer Horário'}</span></td>
<td><span class="text-success" style="font-weight: bold;">✓ Presente</span></td>
<td>${methodHTML}</td>
`;
tbody.appendChild(tr);
});
}
function filterStudentHistory() {
const student = currentSession.user;
const dateFilter = document.getElementById('student-filter-history-date').value;
const methodFilter = document.getElementById('student-filter-history-method').value;
const filtered = db.history.filter(log => {
const matchesStudent = log.studentId === student.id;
const matchesDate = !dateFilter || log.date === dateFilter;
const matchesMethod = methodFilter === 'all' || log.method === methodFilter;
return matchesStudent && matchesDate && matchesMethod;
});
renderStudentHistoryTable(filtered);
}
// Student View Events & Announcements
function renderStudentEventsAndAnnouncements() {
// Events
const evContainer = document.getElementById('student-all-events');
if (evContainer) {
evContainer.innerHTML = '';
if (db.events.length === 0) {
evContainer.innerHTML = '<p style="color: var(--text-muted); font-size: 13px; text-align: center; padding: 20px;">Nenhum evento agendado.</p>';
} else {
db.events.forEach(ev => {
const dateObj = new Date(ev.date + 'T00:00:00');
const day = String(dateObj.getDate()).padStart(2, '0');
const month = dateObj.toLocaleDateString('pt-BR', { month: 'short' }).slice(0, 3).toUpperCase();
const div = document.createElement('div');
div.className = 'event-item';
div.innerHTML = `
<div class="event-date-box">
<span class="event-date-day">${day}</span>
<span class="event-date-month">${month}</span>
</div>
<div class="event-details">
<h4>${linkify(ev.title)}</h4>
<p>${ev.type} • Horário: ${ev.time}h</p>
</div>
`;
evContainer.appendChild(div);
});
}
}
// Announcements
const annContainer = document.getElementById('student-all-announcements');
if (annContainer) {
annContainer.innerHTML = '';
if (db.announcements.length === 0) {
annContainer.innerHTML = '<p style="color: var(--text-muted); font-size: 13px; text-align: center; padding: 20px;">Nenhum aviso publicado no mural.</p>';
} else {
db.announcements.forEach(ann => {
const div = document.createElement('div');
div.style.padding = '16px 0';
div.style.borderBottom = '1px solid var(--border-color)';
div.innerHTML = `
<h4 style="font-size: 15px; font-weight: 600; margin-bottom: 4px;">${linkify(ann.title)}</h4>
<span style="font-size: 11px; color: var(--text-muted); display: block; margin-bottom: 8px;">Publicado em: ${formatDateStr(ann.date)}</span>
<p style="font-size: 13px; line-height: 1.5; color: var(--text-secondary);">${linkify(ann.content)}</p>
`;
annContainer.appendChild(div);
});
}
}
// Render schedules
renderStudentSchedules();
}
// ==================== MODAL CONTROLLERS ====================
function openModal(modalId) {
document.getElementById(modalId).classList.add('active');
}
function closeModal(modalId) {
document.getElementById(modalId).classList.remove('active');
}
function openCreateEventModal() {
document.getElementById('edit-event-id').value = '';
document.getElementById('event-title').value = '';
document.getElementById('event-date').value = '';
document.getElementById('event-time').value = '19:00';
document.getElementById('event-type').value = 'Treino';
document.querySelector('#add-event-modal h3').textContent = 'Agendar Novo Evento';
document.querySelector('#add-event-modal button[type="submit"]').textContent = 'Publicar Evento';
openModal('add-event-modal');
}
function openEditEventModal(id) {
const ev = db.events.find(e => e.id === id);
if (ev) {
document.getElementById('edit-event-id').value = ev.id;
document.getElementById('event-title').value = ev.title;
document.getElementById('event-type').value = ev.type;
document.getElementById('event-date').value = ev.date;
document.getElementById('event-time').value = ev.time;
document.querySelector('#add-event-modal h3').textContent = 'Editar Evento';
document.querySelector('#add-event-modal button[type="submit"]').textContent = 'Salvar Alterações';
openModal('add-event-modal');
}
}
function openCreateAnnouncementModal() {
document.getElementById('edit-ann-id').value = '';
document.getElementById('ann-title').value = '';
document.getElementById('ann-content').value = '';
document.querySelector('#add-announcement-modal h3').textContent = 'Novo Aviso no Mural';
document.querySelector('#add-announcement-modal button[type="submit"]').textContent = 'Publicar Comunicado';
openModal('add-announcement-modal');
}
function openEditAnnouncementModal(id) {
const ann = db.announcements.find(a => a.id === id);
if (ann) {
document.getElementById('edit-ann-id').value = ann.id;
document.getElementById('ann-title').value = ann.title;
document.getElementById('ann-content').value = ann.content;
document.querySelector('#add-announcement-modal h3').textContent = 'Editar Aviso';
document.querySelector('#add-announcement-modal button[type="submit"]').textContent = 'Salvar Alterações';
openModal('add-announcement-modal');
}
}
// Close modals clicking outside the content area
window.onclick = function(event) {
if (event.target.classList.contains('modal')) {
event.target.classList.remove('active');
}
};
// Help helper for graduation modal changes
function updateGradModalBeltDisplay() {
const belt = document.getElementById('grad-student-belt').value;
const name = document.getElementById('grad-modal-student-name').textContent;
const degrees = document.getElementById('grad-student-degrees').value;
document.getElementById('grad-modal-student-info').textContent = `Faixa: ${belt} • ${degrees} Graus`;
}
// Student Profile Metadata View Controllers
function renderStudentProfileDetails() {
const student = currentSession.user;
document.getElementById('profile-detail-email').textContent = student.email || 'Não informado';
document.getElementById('profile-detail-whatsapp').textContent = student.whatsapp || 'Não informado';
document.getElementById('profile-detail-address').textContent = student.address || 'Não informado';
document.getElementById('profile-detail-age').textContent = student.age ? `${student.age} anos` : 'Não informado';
const isMinor = student.age !== null && student.age < 18;
document.getElementById('profile-detail-guardian').textContent = (isMinor && student.guardian) ? student.guardian : (isMinor ? 'Pendente' : 'Não aplicável (Maior de idade)');
let profText = 'Não informado';
if (student.profession) {
profText = student.profession;
if (student.profession.toLowerCase().includes('estudante') && student.schoolName) {
profText += ` (${student.schoolName})`;
}
}
document.getElementById('profile-detail-profession').textContent = profText;
document.getElementById('profile-detail-objective').textContent = student.objective || 'Não informado';
document.getElementById('profile-detail-weekly-goal').textContent = student.weeklyGoal ? `${student.weeklyGoal}x por semana` : 'Não informado';
// Kimono Loan render
const inactiveDiv = document.getElementById('kimono-loan-inactive');
const activeDiv = document.getElementById('kimono-loan-active');
if (student.hasLoan) {
inactiveDiv.style.display = 'none';
activeDiv.style.display = 'flex';
document.getElementById('loan-kimono-brand').textContent = student.kimonoBrand || 'Não especificada';
document.getElementById('loan-kimono-size').textContent = student.kimonoSize || 'Não especificado';
document.getElementById('loan-kimono-date').textContent = student.kimonoDate ? formatDateStr(student.kimonoDate) : 'Não informada';
} else {
inactiveDiv.style.display = 'block';
activeDiv.style.display = 'none';
}
}
// Edit Profile Form Handling
function openEditProfileModal() {
const student = currentSession.user;
document.getElementById('edit-profile-name').value = student.name;
document.getElementById('edit-profile-email').value = student.email || '';
document.getElementById('edit-profile-whatsapp').value = student.whatsapp || '';
document.getElementById('edit-profile-password').value = student.password || '';
document.getElementById('edit-profile-address').value = student.address || '';
document.getElementById('edit-profile-age').value = (student.age !== null && student.age !== undefined) ? student.age : '';
document.getElementById('edit-profile-guardian').value = student.guardian || '';
document.getElementById('edit-profile-profession').value = student.profession || '';
document.getElementById('edit-profile-school-name').value = student.schoolName || '';
document.getElementById('edit-profile-objective').value = student.objective || '';
document.getElementById('edit-profile-weekly-goal').value = student.weeklyGoal || 3;
const hasLoanChk = document.getElementById('edit-profile-has-loan');
hasLoanChk.checked = student.hasLoan || false;
document.getElementById('edit-profile-kimono-brand').value = student.kimonoBrand || '';
document.getElementById('edit-profile-kimono-size').value = student.kimonoSize || '';
document.getElementById('edit-profile-kimono-date').value = student.kimonoDate || '';
toggleGuardianInput();
toggleKimonoInputs();
openModal('edit-profile-modal');
}
function toggleGuardianInput() {
const age = parseInt(document.getElementById('edit-profile-age').value);
const guardianGroup = document.getElementById('guardian-group');
if (age && age < 18) {
guardianGroup.style.display = 'block';
} else {
guardianGroup.style.display = 'none';
}
}
function toggleKimonoInputs() {
const hasLoan = document.getElementById('edit-profile-has-loan').checked;
const kimonoInputsDiv = document.getElementById('kimono-loan-inputs');
if (hasLoan) {
kimonoInputsDiv.style.display = 'block';
} else {
kimonoInputsDiv.style.display = 'none';
}
}
async function handleSaveProfile(event) {
try {
event.preventDefault();
const student = db.students.find(s => s.id === currentSession.user.id);
if (student) {
student.name = document.getElementById('edit-profile-name').value.trim();
student.email = document.getElementById('edit-profile-email').value.trim();
student.whatsapp = document.getElementById('edit-profile-whatsapp').value.trim();
student.password = document.getElementById('edit-profile-password').value.trim() || 'aluno123';
student.classTime = 'Qualquer Horário';
student.address = document.getElementById('edit-profile-address').value.trim();
const ageVal = document.getElementById('edit-profile-age').value;
student.age = ageVal !== '' ? parseInt(ageVal) : null;
const isMinor = student.age !== null && student.age < 18;
if (isMinor) {
student.guardian = document.getElementById('edit-profile-guardian').value.trim();
} else {
student.guardian = '';
}
student.profession = document.getElementById('edit-profile-profession').value.trim();
student.schoolName = document.getElementById('edit-profile-school-name').value.trim();
student.objective = document.getElementById('edit-profile-objective').value.trim();
student.weeklyGoal = parseInt(document.getElementById('edit-profile-weekly-goal').value) || 3;
student.hasLoan = document.getElementById('edit-profile-has-loan').checked;
if (student.hasLoan) {
student.kimonoBrand = document.getElementById('edit-profile-kimono-brand').value.trim();
student.kimonoSize = document.getElementById('edit-profile-kimono-size').value.trim();
student.kimonoDate = document.getElementById('edit-profile-kimono-date').value;
} else {
student.kimonoBrand = '';
student.kimonoSize = '';
student.kimonoDate = '';
}
let syncSuccess = true;
try {
await syncStudentToCloud(student);
} catch (e) {
console.error("Failed to sync profile updates to Supabase", e);
syncSuccess = false;
}
saveDB();
// Update session
currentSession.user = student;
saveSessionToLocalStorage();
// Refresh views
renderStudentProfile();
renderStudentHome();
setupUserInterface(); // Refresh headers
closeModal('edit-profile-modal');
if (syncSuccess) {
alert('Dados do seu perfil atualizados com sucesso!');
} else {
alert('Aviso: Perfil atualizado localmente no navegador, mas falhou ao sincronizar com o Supabase.');
}
}
} catch (err) {
console.error("Critical error in handleSaveProfile:", err);
alert("Erro crítico ao salvar seu perfil: " + err.message);
closeModal('edit-profile-modal');
}
}
// BJJ Study History View Controllers
function renderStudentBJJHistory() {
document.getElementById('student-bjj-history-text').textContent = db.bjjHistory.text;
// Render video embeds
const videosContainer = document.getElementById('student-bjj-history-videos');
videosContainer.innerHTML = '';
if (!db.bjjHistory.videos || db.bjjHistory.videos.length === 0) {
videosContainer.innerHTML = '<p style="grid-column: span 2; color: var(--text-muted); font-size: 13px;">Nenhum vídeo recomendado no momento.</p>';
} else {
db.bjjHistory.videos.forEach(vid => {
const card = document.createElement('div');
card.className = 'card';
card.style.padding = '12px';
card.style.background = 'var(--bg-secondary)';
const embedUrl = convertToEmbedUrl(vid.url);
card.innerHTML = `
<h4 class="mb-12" style="font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${vid.title}</h4>
<div style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; border-radius: 4px;">
<iframe style="position: absolute; top:0; left:0; width:100%; height:100%;" src="${embedUrl}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
</div>
`;
videosContainer.appendChild(card);
});
}
}
// Convert standard YouTube links to Embed format
function convertToEmbedUrl(url) {
if (url.includes('embed/')) return url;
let videoId = '';
try {
if (url.includes('youtu.be/')) {
videoId = url.split('youtu.be/')[1].split(/[?#]/)[0];
} else if (url.includes('v=')) {
videoId = url.split('v=')[1].split(/[&?#]/)[0];
} else if (url.includes('youtube.com/shorts/')) {
videoId = url.split('youtube.com/shorts/')[1].split(/[?#]/)[0];
}
} catch (e) {
console.error("Error parsing youtube URL", e);
}
if (videoId) {
return `https://www.youtube.com/embed/${videoId}`;
}
return url; // fallback
}
// Password Recovery Flow
async function handleRecoverPassword(event) {
event.preventDefault();
const email = document.getElementById('recover-email').value.trim();
let student = null;
// Check in database first
if (supabaseClient) {
try {
const { data, error } = await supabaseClient.from('students').select('*').eq('email', email);
if (data && data.length > 0) {
student = data[0];
}
} catch (e) {
console.warn("Failed to query Supabase for recovery", e);
}
}
// Fallback to local memory
if (!student) {
student = db.students.find(s => s.email && s.email.toLowerCase() === email.toLowerCase());
}
if (student) {
// Generate reset link
const currentUrl = window.location.href.split('?')[0];
const resetLink = `${currentUrl}?resetToken=${student.id}_${Date.now()}`;
// Show loading status
const btn = event.submitter || document.querySelector('#recover-password-modal button[type="submit"]');
const originalText = btn ? btn.textContent : "Enviar Link de Recuperação";
if (btn) {
btn.textContent = "Enviando...";
btn.disabled = true;
}
let sentRealEmail = false;
try {
// Request Netlify function
const response = await fetch('/.netlify/functions/send-reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
toEmail: student.email,
studentName: student.name,
resetLink: resetLink
})
});
const result = await response.json();
if (response.ok) {
sentRealEmail = true;
} else {
console.warn("Real email failed (missing env variables or SMTP error):", result.error);
}
} catch (err) {
console.warn("Netlify function call failed, using mock simulator fallback:", err);
}
if (btn) {
btn.textContent = originalText;
btn.disabled = false;
}
closeModal('recover-password-modal');
document.getElementById('recover-email').value = '';
if (sentRealEmail) {
alert(`Link de redefinição de senha enviado para o e-mail: ${student.email}`);
} else {
// Fallback: Open dev email simulator
showMockRecoveryEmail(student);
alert('Um link de recuperação de senha foi simulado e enviado (o simulador de e-mail local foi aberto, pois as credenciais SMTP no Netlify não estão configuradas).');
}
} else {
alert('E-mail não encontrado no cadastro de alunos!');
}
}
function showMockRecoveryEmail(student) {
document.getElementById('simulator-to-email').textContent = student.email || `${student.id}@email.com`;
document.getElementById('simulator-student-name').textContent = student.name;
// Store student ID in simulator button for trigger reference
const btn = document.querySelector('#dev-email-simulator button');
if (btn) btn.setAttribute('data-student-id', student.id);
document.getElementById('dev-email-simulator').style.display = 'block';
}
function triggerResetPasswordFromSimulator() {
// Hide simulator
document.getElementById('dev-email-simulator').style.display = 'none';
// Get student ID
const btn = document.querySelector('#dev-email-simulator button');
const studentId = btn ? btn.getAttribute('data-student-id') : null;
const student = db.students.find(s => s.id === studentId);
if (student) {
// Prepare Reset Modal
document.getElementById('reset-student-id').value = student.id;
document.getElementById('reset-student-name').textContent = student.name;
document.getElementById('reset-new-password').value = '';
document.getElementById('reset-confirm-password').value = '';
openModal('reset-password-modal');
}
}
async function handleResetPassword(event) {
event.preventDefault();
const id = document.getElementById('reset-student-id').value;
const newPassword = document.getElementById('reset-new-password').value;
const confirmPassword = document.getElementById('reset-confirm-password').value;
if (newPassword !== confirmPassword) {
alert('As senhas não coincidem!');
return;
}
const student = db.students.find(s => s.id === id);
if (student) {
student.password = newPassword;
// Update in Supabase
if (supabaseClient) {
try {
await supabaseClient.from('students').update({ senha: newPassword }).eq('id', student.id);
} catch (e) {
console.error("Failed to reset password in Supabase", e);
}
}
saveDB();
closeModal('reset-password-modal');
alert('Sua senha foi redefinida com sucesso! Agora você pode fazer login com a nova senha.');
}
}
// Dojo Weekly Class Schedules Controllers
function renderStudentSchedules() {
const centroTbody = document.getElementById('student-schedule-centro-tbody');
if (centroTbody) {
centroTbody.innerHTML = '';
const centroList = db.dojoSchedules.centro || [];
if (centroList.length === 0) {
centroTbody.innerHTML = '<tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 12px;">Nenhum horário cadastrado.</td></tr>';
} else {
centroList.forEach(item => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td><strong>${item.day}</strong></td>
<td><span class="badge badge-orange" style="font-size: 10px;">${item.type}</span></td>
<td>${item.time}</td>
`;
centroTbody.appendChild(tr);
});
}
}
const quilomboTbody = document.getElementById('student-schedule-quilombo-tbody');
if (quilomboTbody) {
quilomboTbody.innerHTML = '';
const quilomboList = db.dojoSchedules.quilombo || [];
if (quilomboList.length === 0) {
quilomboTbody.innerHTML = '<tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 12px;">Nenhum horário cadastrado.</td></tr>';
} else {
quilomboList.forEach(item => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td><strong>${item.day}</strong></td>
<td><span class="badge badge-secondary" style="font-size: 10px; background: rgba(255,255,255,0.15);">${item.type}</span></td>
<td>${item.time}</td>
`;
quilomboTbody.appendChild(tr);
});
}
}
}
// Helper to populate all training time select inputs dynamically from db.dojoSchedules
function populateClassTimeSelects() {
const selects = [
document.getElementById('presence-class-filter'),
document.getElementById('ia-class-filter')
];
const options = [];
if (db.dojoSchedules) {
if (db.dojoSchedules.centro) {
db.dojoSchedules.centro.forEach(item => {
if (item.day && item.time) {
const label = `Centro - ${item.day} (${item.type || 'Misto'} - ${item.time})`;
options.push(label);
}
});
}
if (db.dojoSchedules.quilombo) {
db.dojoSchedules.quilombo.forEach(item => {
if (item.day && item.time) {
const label = `Quilombo - ${item.day} (${item.type || 'Misto'} - ${item.time})`;
options.push(label);
}
});
}
}
selects.forEach(select => {
if (!select) return;
const currentValue = select.value;
select.innerHTML = '';
if (select.id === 'presence-class-filter') {
const optAll = document.createElement('option');
optAll.value = 'all';
optAll.textContent = 'Todas as Turmas (Montagem Livre)';
select.appendChild(optAll);
}
const optDefault = document.createElement('option');
optDefault.value = 'Qualquer Horário';
optDefault.textContent = 'Qualquer Horário';
select.appendChild(optDefault);
options.forEach(opt => {
const o = document.createElement('option');
o.value = opt;
o.textContent = opt;
select.appendChild(o);
});
if (currentValue) {
const hasValue = Array.from(select.options).some(o => o.value === currentValue);
if (hasValue) {
select.value = currentValue;
} else {
select.value = select.id === 'presence-class-filter' ? 'all' : 'Qualquer Horário';
}
}
});
}
function captureSchedulesFromUI() {
const getDojoData = (containerId) => {
const container = document.getElementById(containerId);
if (!container) return [];
const rows = container.querySelectorAll('.schedule-edit-row');
const list = [];
rows.forEach(row => {
const day = row.querySelector('.schedule-day').value;
const type = row.querySelector('.schedule-type').value.trim();
const time = row.querySelector('.schedule-time').value.trim();
list.push({ day, type, time });
});
return list;
};
if (!db.dojoSchedules) db.dojoSchedules = {};
db.dojoSchedules.centro = getDojoData('prof-schedule-centro-list');
db.dojoSchedules.quilombo = getDojoData('prof-schedule-quilombo-list');
}
function renderProfessorSchedules() {
const renderDojo = (dojoKey, containerId) => {
const container = document.getElementById(containerId);
if (!container) return;
container.innerHTML = '';
const list = db.dojoSchedules[dojoKey] || [];
list.forEach((item, index) => {
const row = document.createElement('div');
row.style.display = 'flex';
row.style.gap = '8px';
row.style.alignItems = 'center';
row.className = 'schedule-edit-row';
row.innerHTML = `
<select class="form-control form-select schedule-day" style="flex: 1.5; font-size: 13px;">
<option value="Segunda" ${item.day === 'Segunda' ? 'selected' : ''}>Segunda</option>
<option value="Terça" ${item.day === 'Terça' ? 'selected' : ''}>Terça</option>
<option value="Quarta" ${item.day === 'Quarta' ? 'selected' : ''}>Quarta</option>
<option value="Quinta" ${item.day === 'Quinta' ? 'selected' : ''}>Quinta</option>
<option value="Sexta" ${item.day === 'Sexta' ? 'selected' : ''}>Sexta</option>
<option value="Sábado" ${item.day === 'Sábado' ? 'selected' : ''}>Sábado</option>
<option value="Domingo" ${item.day === 'Domingo' ? 'selected' : ''}>Domingo</option>
</select>
<input type="text" class="form-control schedule-type" style="flex: 1.5; font-size: 13px;" value="${item.type || ''}" placeholder="Ex: Adulto, Kids">
<input type="text" class="form-control schedule-time" style="flex: 2; font-size: 13px;" value="${item.time || ''}" placeholder="Ex: 10:00h e 18:30h">
<button type="button" class="btn" style="background: #dc3545; color: white; padding: 6px 12px; margin-bottom: 0;" onclick="removeScheduleRow('${dojoKey}', ${index})">×</button>
`;
container.appendChild(row);
});
};
renderDojo('centro', 'prof-schedule-centro-list');
renderDojo('quilombo', 'prof-schedule-quilombo-list');
}
function addScheduleRow(dojo) {
captureSchedulesFromUI();
if (!db.dojoSchedules[dojo]) {
db.dojoSchedules[dojo] = [];
}
db.dojoSchedules[dojo].push({ day: 'Segunda', type: '', time: '' });
renderProfessorSchedules();
}
function removeScheduleRow(dojo, index) {
captureSchedulesFromUI();
if (db.dojoSchedules[dojo]) {
db.dojoSchedules[dojo].splice(index, 1);
renderProfessorSchedules();
}
}
async function saveDojoSchedules() {
captureSchedulesFromUI();
// Filter out rows with empty values on save
const filterEmpty = (list) => list.filter(item => item.type && item.time);
db.dojoSchedules.centro = filterEmpty(db.dojoSchedules.centro);
db.dojoSchedules.quilombo = filterEmpty(db.dojoSchedules.quilombo);
// 1. Sync to Supabase
if (supabaseClient) {
try {
const { error } = await supabaseClient.from('dojo_schedules').upsert({ id: 'schedule', data: db.dojoSchedules });
if (error) throw error;
} catch (e) {
console.error("Failed to save dojo schedules to Supabase", e);
alert("Erro ao salvar no banco de dados na nuvem.");
return;
}
}
saveDB();
alert("Grade de aulas salva com sucesso!");
populateClassTimeSelects();
renderStudentSchedules(); // Refresh student view
renderProfessorSchedules(); // Clean up empty input rows
renderProfessorDashboard(); // Refresh professor dashboard schedules display
}
// ==================== SYSTEM SETTINGS VIEW AND OPERATIONS ====================
function renderProfessorSettings() {
const apiInput = document.getElementById('settings-ia-api-url');
if (apiInput) {
apiInput.value = localStorage.getItem('face_api_url') || 'http://localhost:8000';
}
const thresholdInput = document.getElementById('settings-ia-threshold');
if (thresholdInput) {
const val = localStorage.getItem('face_api_threshold') || '0.40';
thresholdInput.value = val;
const display = document.getElementById('settings-ia-threshold-value');
if (display) display.textContent = parseFloat(val).toFixed(2);
}
// Reset status message
const statusEl = document.getElementById('settings-ia-status-msg');
if (statusEl) {
statusEl.innerHTML = '<span style="color: var(--text-muted);">Clique no botão abaixo para verificar a conectividade do servidor configurado.</span>';
}
// Reset progress container
const progressContainer = document.getElementById('settings-backfill-progress-container');
if (progressContainer) progressContainer.style.display = 'none';
updateSettingsBackfillCount();
}
function updateSettingsBackfillCount() {
const count = db.students.filter(s => s.selfie && s.selfie.startsWith('data:') && (!s.faceEmbedding || s.faceEmbedding.length === 0)).length;
const countEl = document.getElementById('settings-ia-backfill-count');
if (countEl) {
countEl.textContent = count;
}
// Also update collapsible advanced settings count in presence tab if active
const presenceCountEl = document.getElementById('ia-backfill-count');
if (presenceCountEl) {
presenceCountEl.textContent = count;
}
}
async function testFaceApiConnection() {
const inputUrl = document.getElementById('settings-ia-api-url').value.trim();
const statusEl = document.getElementById('settings-ia-status-msg');
if (!statusEl) return;
statusEl.innerHTML = '<span style="color: var(--text-muted);">Testando conexão...</span>';
try {
const cleanedUrl = inputUrl.replace(/\/$/, '');
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 6000); // 6s timeout
const response = await fetch(`${cleanedUrl}/`, {
method: 'GET',
signal: controller.signal
});
clearTimeout(timeoutId);
if (response.ok) {
const data = await response.json();
statusEl.innerHTML = `<span style="color: var(--success-color); font-weight: bold;">✅ Conectado com sucesso! Status do modelo: ${data.status || 'OK'} (${data.model || 'buffalo_l'})</span>`;
} else {
statusEl.innerHTML = `<span style="color: var(--danger-color); font-weight: bold;">❌ Servidor retornou erro HTTP ${response.status}</span>`;
}
} catch (e) {
statusEl.innerHTML = `<span style="color: var(--danger-color); font-weight: bold;">❌ Falha ao conectar: ${e.message || 'Verifique se a URL está correta ou se o servidor de IA está online.'}</span>`;
}
}
async function saveFaceApiConfig() {
const apiInput = document.getElementById('settings-ia-api-url');
const thresholdInput = document.getElementById('settings-ia-threshold');
if (!apiInput || !thresholdInput) return;
const url = apiInput.value.trim().replace(/\/$/, '');
const threshold = parseFloat(thresholdInput.value).toFixed(2);
if (url && !url.startsWith('http://') && !url.startsWith('https://')) {
alert("Por favor, digite um endereço URL válido começando com http:// ou https://");
return;
}
const saveBtn = document.querySelector('button[onclick="saveFaceApiConfig()"]');
if (saveBtn) {
saveBtn.disabled = true;
saveBtn.textContent = 'Salvando...';
}
localStorage.setItem('face_api_url', url);
localStorage.setItem('face_api_threshold', threshold);
// Update presence inputs in other tabs
const presenceApiInput = document.getElementById('ia-api-url');
if (presenceApiInput) presenceApiInput.value = url;
const presenceThresholdInput = document.getElementById('ia-threshold');
if (presenceThresholdInput) {
presenceThresholdInput.value = threshold;
const presenceThresholdValue = document.getElementById('ia-threshold-value');
if (presenceThresholdValue) presenceThresholdValue.textContent = threshold;
}
if (supabaseClient) {
try {
const { error } = await supabaseClient.from('dojo_schedules').upsert({
id: 'config',
data: {
face_api_url: url,
face_api_threshold: threshold
}
});
if (error) throw error;
alert("Configurações salvas e sincronizadas na nuvem com sucesso!");
} catch (e) {
console.warn("Failed to sync configuration to Supabase:", e);
alert("Configurações salvas localmente, mas não foi possível sincronizar na nuvem (Supabase).");
}
} else {
alert("Configurações salvas localmente!");
}
if (saveBtn) {
saveBtn.disabled = false;
saveBtn.textContent = 'Salvar Configurações';
}
}
async function updatePresenceFaceApiUrl(val) {
const url = val.trim();
localStorage.setItem('face_api_url', url);
// Update settings input as well
const settingsApiInput = document.getElementById('settings-ia-api-url');
if (settingsApiInput) settingsApiInput.value = url;
if (supabaseClient) {
try {
await supabaseClient.from('dojo_schedules').upsert({
id: 'config',
data: {
face_api_url: url,
face_api_threshold: localStorage.getItem('face_api_threshold') || '0.40'
}
});
} catch (e) {
console.warn("Failed to sync face api url from quick settings:", e);
}
}
}
async function updatePresenceFaceApiThreshold(val) {
localStorage.setItem('face_api_threshold', val);
// Update settings input as well
const settingsThresholdInput = document.getElementById('settings-ia-threshold');
if (settingsThresholdInput) {
settingsThresholdInput.value = val;
const settingsThresholdVal = document.getElementById('settings-ia-threshold-value');
if (settingsThresholdVal) settingsThresholdVal.textContent = parseFloat(val).toFixed(2);
}
if (supabaseClient) {
try {
await supabaseClient.from('dojo_schedules').upsert({
id: 'config',
data: {
face_api_url: localStorage.getItem('face_api_url') || 'http://localhost:8000',
face_api_threshold: val
}
});
} catch (e) {
console.warn("Failed to sync threshold from quick settings:", e);
}
}
}
async function runSettingsManualBackfill() {
const btn = document.getElementById('btn-settings-ia-backfill');
const progressContainer = document.getElementById('settings-backfill-progress-container');
const progressBar = document.getElementById('settings-backfill-progress-bar');
const progressText = document.getElementById('settings-backfill-progress-text');
const progressPercent = document.getElementById('settings-backfill-progress-percent');
const studentsToFix = db.students.filter(s => s.selfie && s.selfie.startsWith('data:') && (!s.faceEmbedding || s.faceEmbedding.length === 0));
if (studentsToFix.length === 0) {
alert("Todos os alunos com selfie válida já possuem vetor facial (Vetor IA) gerado!");
return;
}
if (btn) btn.disabled = true;
if (progressContainer) progressContainer.style.display = 'block';
let successCount = 0;
let failCount = 0;
for (let i = 0; i < studentsToFix.length; i++) {
const student = studentsToFix[i];
const percent = Math.round((i / studentsToFix.length) * 100);
if (progressText) progressText.textContent = `Sincronizando ${i + 1}/${studentsToFix.length} (${student.name})...`;
if (progressPercent) progressPercent.textContent = `${percent}%`;
if (progressBar) progressBar.style.width = `${percent}%`;
try {
const embedding = await extractEmbeddingFromAPI(student.selfie);
if (embedding) {
student.faceEmbedding = embedding;
await syncStudentToCloud(student);
successCount++;
} else {
failCount++;
}
} catch (e) {
console.warn(`Failed to sync embedding for ${student.name}:`, e);
failCount++;
}
updateSettingsBackfillCount();
}
if (progressText) progressText.textContent = "Concluído!";
if (progressPercent) progressPercent.textContent = "100%";
if (progressBar) progressBar.style.width = "100%";
saveDB();
if (btn) btn.disabled = false;
alert(`Sincronização manual concluída!\n\nSucesso: ${successCount} aluno(s)\nFalhas: ${failCount} aluno(s)`);
setTimeout(() => {
if (progressContainer) progressContainer.style.display = 'none';
if (progressBar) progressBar.style.width = '0%';
}, 4000);
renderPresenceChecklist();
updateIAStats();
}
// Helper to initialize missing student fields
function initializeStudentFields(student) {
if (student.password === undefined) student.password = 'aluno123';
if (student.email === undefined) student.email = '';
if (student.whatsapp === undefined) student.whatsapp = '';
if (student.address === undefined) student.address = '';
if (student.age === undefined) student.age = 18;
if (student.faceEmbedding === undefined) student.faceEmbedding = null;
if (student.guardian === undefined) student.guardian = '';
if (student.objective === undefined) student.objective = '';
if (student.weeklyGoal === undefined) student.weeklyGoal = 3;
if (student.profession === undefined) student.profession = '';
if (student.schoolName === undefined) student.schoolName = '';
if (student.hasLoan === undefined) student.hasLoan = false;
if (student.kimonoBrand === undefined) student.kimonoBrand = '';
if (student.kimonoSize === undefined) student.kimonoSize = '';
if (student.kimonoDate === undefined) student.kimonoDate = '';
if (student.evaluationParents === undefined) student.evaluationParents = 'Pendente';
if (student.evaluationSchool === undefined) student.evaluationSchool = 'Pendente';
}
const ADULT_BELTS = ['Branca', 'Azul', 'Roxa', 'Marrom', 'Preta'];
const KIDS_BELTS = [
'Branca',
'Cinza e Branca',
'Cinza',
'Cinza e Preta',
'Amarela e Branca',
'Amarela',
'Amarela e Preta',
'Laranja e Branca',
'Laranja',
'Laranja e Preta',
'Verde e Branca',
'Verde',
'Verde e Preta'
];
// State Management with LocalStorage persistence
const DEFAULT_STUDENTS = [
{ id: 'lucas', name: 'Lucas Souza', email: 'lucas@email.com', whatsapp: '(35) 99999-0001', belt: 'Branca', degrees: 2, attendanceCount: 24, selfie: null, streak: 80, address: 'Rua das Flores, 123 - Centro', age: 15, guardian: 'Ana Souza', objective: 'Aprender defesa pessoal e ganhar disciplina', weeklyGoal: 3, profession: 'Estudante', schoolName: 'E.E. Pandiá Calógeras', hasLoan: true, kimonoBrand: 'Koral', kimonoSize: 'M2', kimonoDate: '2026-05-15' },
{ id: 'thiago', name: 'Thiago Behring', email: 'thiago@email.com', whatsapp: '(35) 99999-0002', belt: 'Azul', degrees: 1, attendanceCount: 52, selfie: 'preset_thiago', streak: 90, address: 'Av. Tiradentes, 45 - Alto', age: 22, guardian: '', objective: 'Focar em competição e condicionamento', weeklyGoal: 4, profession: 'Educador Físico', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'felipe', name: 'Felipe Santana', email: 'felipe@email.com', whatsapp: '(35) 99999-0003', belt: 'Roxa', degrees: 3, attendanceCount: 112, selfie: 'preset_felipe', streak: 95, address: 'Rua São Bento, 987 - Vista Alegre', age: 28, guardian: '', objective: 'Estilo de vida e evolução na arte marcial', weeklyGoal: 3, profession: 'Desenvolvedor', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'gabriela', name: 'Gabriela Lima', email: 'gabriela@email.com', whatsapp: '(35) 99999-0004', belt: 'Marrom', degrees: 0, attendanceCount: 198, selfie: null, streak: 65, address: 'Serrinha da Aliança, Km 4', age: 32, guardian: '', objective: 'Competir e um dia dar aulas', weeklyGoal: 2, profession: 'Veterinária', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'roberto', name: 'Roberto Alencar', email: 'roberto@email.com', whatsapp: '(35) 99999-0005', belt: 'Preta', degrees: 2, attendanceCount: 342, selfie: 'preset_roberto', streak: 85, address: 'Rua do Cruzeiro, 50 - Centro', age: 45, guardian: '', objective: 'Manter a saúde e passar a tradição adiante', weeklyGoal: 5, profession: 'Empresário', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'senpai_lucas', name: 'Senpai Lucas', email: 'senpai.lucas@email.com', whatsapp: '(35) 99999-0006', belt: 'Azul', degrees: 2, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 25, guardian: '', objective: 'Evolução técnica e auxílio nas aulas', weeklyGoal: 3, profession: 'Professor Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'senpai_marcelo', name: 'Senpai Marcelo', email: 'senpai.marcelo@email.com', whatsapp: '(35) 99999-0007', belt: 'Roxa', degrees: 1, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 27, guardian: '', objective: 'Evolução técnica e competição', weeklyGoal: 3, profession: 'Professor Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'senpai_maju', name: 'Senpai Maju', email: 'senpai.maju@email.com', whatsapp: '(35) 99999-0008', belt: 'Roxa', degrees: 2, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 23, guardian: '', objective: 'Evolução técnica e liderança feminina no tatame', weeklyGoal: 3, profession: 'Professora Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'senpai_rogerio', name: 'Senpai Rogério', email: 'senpai.rogerio@email.com', whatsapp: '(35) 99999-0009', belt: 'Roxa', degrees: 3, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 29, guardian: '', objective: 'Evolução técnica e auxílio nas aulas', weeklyGoal: 3, profession: 'Professor Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'senpai_felicio', name: 'Senpai Felício', email: 'senpai.felicio@email.com', whatsapp: '(35) 99999-0010', belt: 'Roxa', degrees: 2, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 26, guardian: '', objective: 'Evolução técnica e auxílio nas aulas', weeklyGoal: 3, profession: 'Professor Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' },
{ id: 'senpai_isadora', name: 'Senpai Isadora', email: 'senpai.isadora@email.com', whatsapp: '(35) 99999-0011', belt: 'Azul', degrees: 4, attendanceCount: 0, selfie: null, streak: 100, address: '', age: 24, guardian: '', objective: 'Evolução técnica e liderança feminina no tatame', weeklyGoal: 3, profession: 'Professora Auxiliar', schoolName: '', hasLoan: false, kimonoBrand: '', kimonoSize: '', kimonoDate: '' }
];
const DEFAULT_EVENTS = [
{ id: 1, title: 'Treino de Graduação e Defesa Pessoal', type: 'Treino', date: '2026-06-06', time: '10:00' },
{ id: 2, title: 'Seminário de Passagem de Guarda', type: 'Seminário', date: '2026-06-15', time: '19:30' },
{ id: 3, title: 'Exame Geral de Faixas', type: 'Graduação', date: '2026-07-04', time: '19:00' }
];
const DEFAULT_ANNOUNCEMENTS = [
{ id: 1, title: 'Patches da Associação Behring', content: 'Atenção alunos: para o próximo exame geral de faixas em Julho, todos os kimonos devem estar devidamente equipados com o patch oficial da associação Behring. Disponíveis na secretaria.', date: '2026-06-04' },
{ id: 2, title: 'Foco na Assiduidade', content: 'Lembramos a todos que a frequência é monitorada pelo app (check-in manual ou foto IA). A assiduidade é o critério principal para indicação aos graus nas faixas.', date: '2026-06-01' }
];
const DEFAULT_HISTORY = [
{ date: '2026-06-03', time: '19:15', studentId: 'lucas', studentName: 'Lucas Souza', belt: 'Branca', method: 'manual' },
{ date: '2026-06-03', time: '19:10', studentId: 'thiago', studentName: 'Thiago Behring', belt: 'Azul', method: 'ia' },
{ date: '2026-06-03', time: '19:10', studentId: 'felipe', studentName: 'Felipe Santana', belt: 'Roxa', method: 'ia' },
{ date: '2026-06-02', time: '19:05', studentId: 'lucas', studentName: 'Lucas Souza', belt: 'Branca', method: 'manual' },
{ date: '2026-06-02', time: '19:05', studentId: 'gabriela', studentName: 'Gabriela Lima', belt: 'Marrom', method: 'manual' }
];
const DEFAULT_BJJ_HISTORY = {
text: `A história do Jiu-Jitsu no Brasil começou no início do século XX. O mestre japonês Mitsuyo Maeda, conhecido como "Conde Koma", chegou ao Brasil em 1914. Ele viajou demonstrando o Kodokan Judo (então chamado de Jiu-Jitsu Kano ou simplesmente Jiu-Jitsu).
Em Belém do Pará, Maeda conheceu Carlos Gracie. Carlos se interessou pelas demonstrações de Maeda e tornou-se seu aluno. Carlos ensinou a seus irmãos, incluindo Oswaldo, Gastão Jr., Jorge e Hélio Gracie.
Hélio Gracie, sendo mais franzino, adaptou as técnicas para focar no uso da alavanca em vez da força bruta, dando origem ao Jiu-Jitsu Brasileiro (BJJ).
O Jiu-Jitsu da linhagem Behring carrega as tradições técnicas e éticas estabelecidas pelo Grande Mestre Sylvio Behring, focando na defesa pessoal, respeito mútuo e disciplina dentro e fora dos tatames. A escola de São Bento do Sapucaí orgulha-se de manter este legado vivo.`,
videos: [
{ id: 1, title: 'A Origem do Jiu-Jitsu Brasileiro (BJJ)', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ' },
{ id: 2, title: 'Defesa Pessoal Behring BJJ - Fundamentos', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ' }
]
};
const DEFAULT_DOJO_SCHEDULES = {
centro: [
{ day: "Segunda", type: "Adulto", time: "10:00h e 18:30h" },
{ day: "Terça", type: "Kids", time: "18h" },
{ day: "Quarta", type: "Adulto", time: "10:00h e 18:30h" },
{ day: "Quinta", type: "Kids", time: "18h" },
{ day: "Sábado", type: "Misto", time: "10:00h" }
],
quilombo: [
{ day: "Segunda", type: "Misto", time: "18:30h" },
{ day: "Quinta", type: "Misto", time: "18:30h" }
]
};