added in the user managment section. Need to also do some updates to the admin menue and whatnot however itll get figured.

This commit is contained in:
2025-07-17 17:48:50 -06:00
parent af2e6c7516
commit 1c4366e7a9
22 changed files with 1382 additions and 226 deletions

View File

@@ -260,6 +260,18 @@ function setupEventListeners() {
if (clearShiftBtn) {
clearShiftBtn.addEventListener('click', clearShiftForm);
}
// User form submission
const userForm = document.getElementById('user-form');
if (userForm) {
userForm.addEventListener('submit', createUser);
}
// Clear user form button
const clearUserBtn = document.getElementById('clear-user-form');
if (clearUserBtn) {
clearUserBtn.addEventListener('click', clearUserForm);
}
}
// Setup navigation between admin sections
@@ -297,6 +309,12 @@ function setupNavigation() {
loadAdminShifts();
}
// If switching to users section, load users
if (targetId === 'users') {
console.log('Loading users...');
loadUsers();
}
// If switching to walk sheet section, load config
if (targetId === 'walk-sheet') {
loadWalkSheetConfig().then((success) => {
@@ -537,9 +555,9 @@ function generateWalkSheetPreview() {
<div class="ws-form-group">
<label class="ws-form-label">Sign Size</label>
<div class="ws-form-field circles">
<span class="ws-circle-option"><span class="ws-circle">S</span></span>
<span class="ws-circle-option"><span class="ws-circle">M</span></span>
<span class="ws-circle-option"><span class="ws-circle">R</span></span>
<span class="ws-circle-option"><span class="ws-circle">L</span></span>
<span class="ws-circle-option"><span class="ws-circle">U</span></span>
</div>
</div>
<div class="ws-form-group">
@@ -955,62 +973,6 @@ function displayAdminShifts(shifts) {
setupShiftActionListeners();
}
// Fix the setupNavigation function to properly load shifts when switching to shifts section
function setupNavigation() {
const navLinks = document.querySelectorAll('.admin-nav a');
const sections = document.querySelectorAll('.admin-section');
navLinks.forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
// Get target section ID
const targetId = link.getAttribute('href').substring(1);
// Hide all sections
sections.forEach(section => {
section.style.display = 'none';
});
// Show target section
const targetSection = document.getElementById(targetId);
if (targetSection) {
targetSection.style.display = 'block';
}
// Update active nav link
navLinks.forEach(navLink => {
navLink.classList.remove('active');
});
link.classList.add('active');
// If switching to shifts section, load shifts
if (targetId === 'shifts') {
console.log('Loading admin shifts...');
loadAdminShifts();
}
// If switching to walk sheet section, load config
if (targetId === 'walk-sheet') {
loadWalkSheetConfig().then((success) => {
if (success) {
generateWalkSheetPreview();
}
});
}
});
});
// Also check if we're already on the shifts page (via hash)
const hash = window.location.hash;
if (hash === '#shifts') {
const shiftsLink = document.querySelector('.admin-nav a[href="#shifts"]');
if (shiftsLink) {
shiftsLink.click();
}
}
}
// Fix the setupShiftActionListeners function
function setupShiftActionListeners() {
const list = document.getElementById('admin-shifts-list');
@@ -1112,101 +1074,181 @@ function clearShiftForm() {
}
}
// Update setupEventListeners to include shift form and clear button
function setupEventListeners() {
// Use current view button
const useCurrentViewBtn = document.getElementById('use-current-view');
if (useCurrentViewBtn) {
useCurrentViewBtn.addEventListener('click', () => {
const center = adminMap.getCenter();
const zoom = adminMap.getZoom();
document.getElementById('start-lat').value = center.lat.toFixed(6);
document.getElementById('start-lng').value = center.lng.toFixed(6);
document.getElementById('start-zoom').value = zoom;
updateStartMarker(center.lat, center.lng);
showStatus('Captured current map view', 'success');
});
}
// User Management Functions
async function loadUsers() {
const loadingEl = document.getElementById('users-loading');
const emptyEl = document.getElementById('users-empty');
const tableBody = document.getElementById('users-table-body');
// Save button
const saveLocationBtn = document.getElementById('save-start-location');
if (saveLocationBtn) {
saveLocationBtn.addEventListener('click', saveStartLocation);
}
if (loadingEl) loadingEl.style.display = 'block';
if (emptyEl) emptyEl.style.display = 'none';
if (tableBody) tableBody.innerHTML = '';
// Coordinate input changes
const startLatInput = document.getElementById('start-lat');
const startLngInput = document.getElementById('start-lng');
const startZoomInput = document.getElementById('start-zoom');
if (startLatInput) startLatInput.addEventListener('change', updateMapFromInputs);
if (startLngInput) startLngInput.addEventListener('change', updateMapFromInputs);
if (startZoomInput) startZoomInput.addEventListener('change', updateMapFromInputs);
// Walk Sheet buttons
const saveWalkSheetBtn = document.getElementById('save-walk-sheet');
const previewWalkSheetBtn = document.getElementById('preview-walk-sheet');
const printWalkSheetBtn = document.getElementById('print-walk-sheet');
const refreshPreviewBtn = document.getElementById('refresh-preview');
if (saveWalkSheetBtn) saveWalkSheetBtn.addEventListener('click', saveWalkSheetConfig);
if (previewWalkSheetBtn) previewWalkSheetBtn.addEventListener('click', generateWalkSheetPreview);
if (printWalkSheetBtn) printWalkSheetBtn.addEventListener('click', printWalkSheet);
if (refreshPreviewBtn) refreshPreviewBtn.addEventListener('click', generateWalkSheetPreview);
// Auto-update preview on input change
const walkSheetInputs = document.querySelectorAll(
'#walk-sheet-title, #walk-sheet-subtitle, #walk-sheet-footer, ' +
'[id^="qr-code-"][id$="-url"], [id^="qr-code-"][id$="-label"]'
);
walkSheetInputs.forEach(input => {
if (input) {
input.addEventListener('input', debounce(() => {
generateWalkSheetPreview();
}, 500));
try {
const response = await fetch('/api/users');
const data = await response.json();
if (loadingEl) loadingEl.style.display = 'none';
if (data.success && data.users) {
displayUsers(data.users);
} else {
throw new Error(data.error || 'Failed to load users');
}
});
// Add URL change listeners to detect when QR codes need regeneration
for (let i = 1; i <= 3; i++) {
const urlInput = document.getElementById(`qr-code-${i}-url`);
if (urlInput) {
let previousUrl = urlInput.value;
urlInput.addEventListener('change', () => {
const currentUrl = urlInput.value;
if (currentUrl !== previousUrl) {
console.log(`QR Code ${i} URL changed from "${previousUrl}" to "${currentUrl}"`);
// Remove stored QR code so it gets regenerated
delete storedQRCodes[currentUrl];
previousUrl = currentUrl;
generateWalkSheetPreview();
}
});
} catch (error) {
console.error('Error loading users:', error);
if (loadingEl) loadingEl.style.display = 'none';
if (emptyEl) {
emptyEl.textContent = 'Failed to load users';
emptyEl.style.display = 'block';
}
}
// Shift form submission
const shiftForm = document.getElementById('shift-form');
if (shiftForm) {
shiftForm.addEventListener('submit', createShift);
}
// Clear shift form button
const clearShiftBtn = document.getElementById('clear-shift-form');
if (clearShiftBtn) {
clearShiftBtn.addEventListener('click', clearShiftForm);
showStatus('Failed to load users', 'error');
}
}
// Add the missing clearShiftForm function
function clearShiftForm() {
const form = document.getElementById('shift-form');
if (form) {
form.reset();
showStatus('Form cleared', 'info');
function displayUsers(users) {
const tableBody = document.getElementById('users-table-body');
const emptyEl = document.getElementById('users-empty');
if (!tableBody) return;
if (!users || users.length === 0) {
if (emptyEl) emptyEl.style.display = 'block';
return;
}
if (emptyEl) emptyEl.style.display = 'none';
tableBody.innerHTML = users.map(user => {
const createdDate = user.created_at || user['Created At'] || user.createdAt;
const formattedDate = createdDate ? new Date(createdDate).toLocaleDateString() : 'N/A';
const isAdmin = user.admin || user.Admin || false;
const userId = user.Id || user.id || user.ID;
return `
<tr>
<td data-label="Email">${escapeHtml(user.email || user.Email || 'N/A')}</td>
<td data-label="Name">${escapeHtml(user.name || user.Name || 'N/A')}</td>
<td data-label="Role">
<span class="user-role ${isAdmin ? 'admin' : 'user'}">
${isAdmin ? 'Admin' : 'User'}
</span>
</td>
<td data-label="Created">${formattedDate}</td>
<td data-label="Actions">
<div class="user-actions">
<button class="btn btn-danger delete-user-btn" data-user-id="${userId}" data-user-email="${escapeHtml(user.email || user.Email)}">
Delete
</button>
</div>
</td>
</tr>
`;
}).join('');
// Setup event listeners for user actions
setupUserActionListeners();
}
function setupUserActionListeners() {
const tableBody = document.getElementById('users-table-body');
if (!tableBody) return;
// Remove existing listeners by cloning the node
const newTableBody = tableBody.cloneNode(true);
tableBody.parentNode.replaceChild(newTableBody, tableBody);
// Get the updated reference
const updatedTableBody = document.getElementById('users-table-body');
updatedTableBody.addEventListener('click', function(e) {
if (e.target.classList.contains('delete-user-btn')) {
const userId = e.target.getAttribute('data-user-id');
const userEmail = e.target.getAttribute('data-user-email');
console.log('Delete button clicked for user:', userId);
deleteUser(userId, userEmail);
}
});
}
async function deleteUser(userId, userEmail) {
if (!confirm(`Are you sure you want to delete user "${userEmail}"? This action cannot be undone.`)) {
return;
}
try {
const response = await fetch(`/api/users/${userId}`, {
method: 'DELETE'
});
const data = await response.json();
if (data.success) {
showStatus(`User "${userEmail}" deleted successfully`, 'success');
loadUsers(); // Reload the users list
} else {
throw new Error(data.error || 'Failed to delete user');
}
} catch (error) {
console.error('Error deleting user:', error);
showStatus(`Failed to delete user: ${error.message}`, 'error');
}
}
async function createUser(e) {
e.preventDefault();
const email = document.getElementById('user-email').value.trim();
const password = document.getElementById('user-password').value;
const name = document.getElementById('user-name').value.trim();
const admin = document.getElementById('user-admin').checked;
if (!email || !password) {
showStatus('Email and password are required', 'error');
return;
}
if (password.length < 6) {
showStatus('Password must be at least 6 characters long', 'error');
return;
}
try {
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email,
password,
name: name || '',
admin
})
});
const data = await response.json();
if (data.success) {
showStatus('User created successfully', 'success');
clearUserForm();
loadUsers(); // Reload the users list
} else {
throw new Error(data.error || 'Failed to create user');
}
} catch (error) {
console.error('Error creating user:', error);
showStatus(`Failed to create user: ${error.message}`, 'error');
}
}
function clearUserForm() {
const form = document.getElementById('user-form');
if (form) {
form.reset();
showStatus('User form cleared', 'info');
}
}

97
map/app/public/js/user.js Normal file
View File

@@ -0,0 +1,97 @@
// User profile JavaScript
// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
checkUserAuth();
loadUserProfile();
setupEventListeners();
});
// Check if user is authenticated
async function checkUserAuth() {
try {
const response = await fetch('/api/auth/check');
const data = await response.json();
if (!data.authenticated) {
window.location.href = '/login.html';
return;
}
// Update user info in header
const userInfo = document.getElementById('user-info');
if (userInfo && data.user) {
userInfo.textContent = `${data.user.name || data.user.email}`;
}
} catch (error) {
console.error('Auth check failed:', error);
window.location.href = '/login.html';
}
}
// Load user profile information
async function loadUserProfile() {
try {
const response = await fetch('/api/auth/check');
const data = await response.json();
if (data.authenticated && data.user) {
document.getElementById('profile-email').textContent = data.user.email || 'N/A';
document.getElementById('profile-name').textContent = data.user.name || 'N/A';
document.getElementById('profile-role').textContent = data.user.isAdmin ? 'Administrator' : 'User';
}
} catch (error) {
console.error('Failed to load profile:', error);
showStatus('Failed to load profile information', 'error');
}
}
// Setup event listeners
function setupEventListeners() {
// Logout button
const logoutBtn = document.getElementById('logout-btn');
if (logoutBtn) {
logoutBtn.addEventListener('click', handleLogout);
}
}
// Handle logout
async function handleLogout() {
try {
const response = await fetch('/api/auth/logout', {
method: 'POST',
credentials: 'include'
});
if (response.ok) {
window.location.href = '/login.html';
} else {
throw new Error('Logout failed');
}
} catch (error) {
console.error('Logout error:', error);
showStatus('Logout failed', 'error');
}
}
// Show status message
function showStatus(message, type = 'info') {
const container = document.getElementById('status-container');
if (!container) return;
const statusDiv = document.createElement('div');
statusDiv.className = `status-message status-${type}`;
statusDiv.textContent = message;
container.appendChild(statusDiv);
// Auto remove after 5 seconds
setTimeout(() => {
if (statusDiv.parentNode) {
statusDiv.parentNode.removeChild(statusDiv);
}
}, 5000);
}