Shifts manager

This commit is contained in:
2025-07-10 16:07:17 -06:00
parent 728a0bb6a9
commit cee9af7e49
14 changed files with 1707 additions and 40 deletions

View File

@@ -237,14 +237,29 @@ function setupEventListeners() {
let previousUrl = urlInput.value;
urlInput.addEventListener('change', () => {
if (urlInput.value !== previousUrl) {
// URL changed, clear stored QR code
delete storedQRCodes[i];
previousUrl = urlInput.value;
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();
}
});
}
}
// 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);
}
}
// Setup navigation between admin sections
@@ -276,19 +291,31 @@ function setupNavigation() {
});
link.classList.add('active');
// If switching to walk sheet, load config first then generate preview
// 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') {
console.log('Switching to walk sheet section, loading config...');
// Always load the latest config when switching to walk sheet
loadWalkSheetConfig().then((success) => {
if (success) {
console.log('Config loaded, generating preview...');
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();
}
}
}
// Update map from input fields
@@ -872,3 +899,314 @@ function debounce(func, wait) {
timeout = setTimeout(later, wait);
};
}
// Add shift management functions
async function loadAdminShifts() {
try {
const response = await fetch('/api/shifts/admin');
const data = await response.json();
if (data.success) {
displayAdminShifts(data.shifts);
} else {
showStatus('Failed to load shifts', 'error');
}
} catch (error) {
console.error('Error loading admin shifts:', error);
showStatus('Failed to load shifts', 'error');
}
}
function displayAdminShifts(shifts) {
const list = document.getElementById('admin-shifts-list');
if (!list) {
console.error('Admin shifts list element not found');
return;
}
if (shifts.length === 0) {
list.innerHTML = '<p>No shifts created yet.</p>';
return;
}
list.innerHTML = shifts.map(shift => {
const shiftDate = new Date(shift.Date);
const signupCount = shift.signups ? shift.signups.length : 0;
return `
<div class="shift-admin-item">
<div>
<h4>${escapeHtml(shift.Title)}</h4>
<p>📅 ${shiftDate.toLocaleDateString()} | ⏰ ${shift['Start Time']} - ${shift['End Time']}</p>
<p>📍 ${escapeHtml(shift.Location || 'TBD')}</p>
<p>👥 ${signupCount}/${shift['Max Volunteers']} volunteers</p>
<p class="status-${(shift.Status || 'open').toLowerCase()}">${shift.Status || 'Open'}</p>
</div>
<div class="shift-actions">
<button class="btn btn-secondary btn-sm edit-shift-btn" data-shift-id="${shift.ID}">Edit</button>
<button class="btn btn-danger btn-sm delete-shift-btn" data-shift-id="${shift.ID}">Delete</button>
</div>
</div>
`;
}).join('');
// Add event listeners using delegation
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');
if (!list) return;
// Remove any existing listeners to avoid duplicates
const newList = list.cloneNode(true);
list.parentNode.replaceChild(newList, list);
// Get the updated reference
const updatedList = document.getElementById('admin-shifts-list');
updatedList.addEventListener('click', function(e) {
if (e.target.classList.contains('delete-shift-btn')) {
const shiftId = e.target.getAttribute('data-shift-id');
console.log('Delete button clicked for shift:', shiftId);
deleteShift(shiftId);
} else if (e.target.classList.contains('edit-shift-btn')) {
const shiftId = e.target.getAttribute('data-shift-id');
console.log('Edit button clicked for shift:', shiftId);
editShift(shiftId);
}
});
}
// Update the deleteShift function (remove window. prefix)
async function deleteShift(shiftId) {
if (!confirm('Are you sure you want to delete this shift? All signups will be cancelled.')) {
return;
}
try {
const response = await fetch(`/api/shifts/admin/${shiftId}`, {
method: 'DELETE'
});
const data = await response.json();
if (data.success) {
showStatus('Shift deleted successfully', 'success');
await loadAdminShifts();
} else {
showStatus(data.error || 'Failed to delete shift', 'error');
}
} catch (error) {
console.error('Error deleting shift:', error);
showStatus('Failed to delete shift', 'error');
}
}
// Update editShift function (remove window. prefix)
function editShift(shiftId) {
showStatus('Edit functionality coming soon', 'info');
}
// Add function to create shift
async function createShift(e) {
e.preventDefault();
const formData = {
title: document.getElementById('shift-title').value,
description: document.getElementById('shift-description').value,
date: document.getElementById('shift-date').value,
startTime: document.getElementById('shift-start').value,
endTime: document.getElementById('shift-end').value,
location: document.getElementById('shift-location').value,
maxVolunteers: document.getElementById('shift-max-volunteers').value
};
try {
const response = await fetch('/api/shifts/admin', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
});
const data = await response.json();
if (data.success) {
showStatus('Shift created successfully', 'success');
document.getElementById('shift-form').reset();
await loadAdminShifts();
} else {
showStatus(data.error || 'Failed to create shift', 'error');
}
} catch (error) {
console.error('Error creating shift:', error);
showStatus('Failed to create shift', 'error');
}
}
function clearShiftForm() {
const form = document.getElementById('shift-form');
if (form) {
form.reset();
showStatus('Form cleared', 'info');
}
}
// 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');
});
}
// Save button
const saveLocationBtn = document.getElementById('save-start-location');
if (saveLocationBtn) {
saveLocationBtn.addEventListener('click', saveStartLocation);
}
// 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));
}
});
// 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();
}
});
}
}
// 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);
}
}
// Add the missing clearShiftForm function
function clearShiftForm() {
const form = document.getElementById('shift-form');
if (form) {
form.reset();
showStatus('Form cleared', 'info');
}
}

View File

@@ -9,8 +9,8 @@ export let isStartLocationVisible = true;
export async function initializeMap() {
try {
// Get start location from server
const response = await fetch('/api/admin/start-location');
// Get start location from PUBLIC endpoint (not admin endpoint)
const response = await fetch('/api/config/start-location');
const data = await response.json();
let startLat = CONFIG.DEFAULT_LAT;

293
map/app/public/js/shifts.js Normal file
View File

@@ -0,0 +1,293 @@
let currentUser = null;
let allShifts = [];
let mySignups = [];
// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', async () => {
await checkAuth();
await loadShifts();
await loadMySignups();
setupEventListeners();
// Add clear filters button handler
const clearBtn = document.getElementById('clear-filters-btn');
if (clearBtn) {
clearBtn.addEventListener('click', clearFilters);
}
});
async function checkAuth() {
try {
const response = await fetch('/api/auth/check');
const data = await response.json();
if (!data.authenticated) {
window.location.href = '/login.html';
return;
}
currentUser = data.user;
document.getElementById('user-email').textContent = currentUser.email;
// Add admin link if user is admin
if (currentUser.isAdmin) {
const headerActions = document.querySelector('.header-actions');
const adminLink = document.createElement('a');
adminLink.href = '/admin.html#shifts';
adminLink.className = 'btn btn-secondary';
adminLink.textContent = '⚙️ Manage Shifts';
headerActions.insertBefore(adminLink, headerActions.firstChild);
}
} catch (error) {
console.error('Auth check failed:', error);
window.location.href = '/login.html';
}
}
async function loadShifts() {
try {
const response = await fetch('/api/shifts');
const data = await response.json();
if (data.success) {
allShifts = data.shifts;
displayShifts(allShifts);
}
} catch (error) {
showStatus('Failed to load shifts', 'error');
}
}
async function loadMySignups() {
try {
const response = await fetch('/api/shifts/my-signups');
const data = await response.json();
if (data.success) {
mySignups = data.signups;
displayMySignups();
} else {
// Still display empty signups if the endpoint fails
mySignups = [];
displayMySignups();
}
} catch (error) {
console.error('Failed to load signups:', error);
// Don't show error to user, just display empty signups
mySignups = [];
displayMySignups();
}
}
function displayShifts(shifts) {
const grid = document.getElementById('shifts-grid');
if (shifts.length === 0) {
grid.innerHTML = '<p class="no-shifts">No shifts available at this time.</p>';
return;
}
grid.innerHTML = shifts.map(shift => {
const shiftDate = new Date(shift.Date);
const isSignedUp = mySignups.some(s => s.shift_id === shift.ID);
const isFull = shift['Current Volunteers'] >= shift['Max Volunteers'];
return `
<div class="shift-card ${isFull ? 'full' : ''} ${isSignedUp ? 'signed-up' : ''}">
<h3>${escapeHtml(shift.Title)}</h3>
<div class="shift-details">
<p>📅 ${shiftDate.toLocaleDateString()}</p>
<p>⏰ ${shift['Start Time']} - ${shift['End Time']}</p>
<p>📍 ${escapeHtml(shift.Location || 'TBD')}</p>
<p>👥 ${shift['Current Volunteers']}/${shift['Max Volunteers']} volunteers</p>
</div>
${shift.Description ? `<div class="shift-description">${escapeHtml(shift.Description)}</div>` : ''}
<div class="shift-actions">
${isSignedUp
? `<button class="btn btn-danger btn-sm cancel-signup-btn" data-shift-id="${shift.ID}">Cancel Signup</button>`
: isFull
? '<button class="btn btn-secondary btn-sm" disabled>Shift Full</button>'
: `<button class="btn btn-primary btn-sm signup-btn" data-shift-id="${shift.ID}">Sign Up</button>`
}
</div>
</div>
`;
}).join('');
// Add event listeners after rendering
setupShiftCardListeners();
}
function displayMySignups() {
const list = document.getElementById('my-signups-list');
if (mySignups.length === 0) {
list.innerHTML = '<p>You haven\'t signed up for any shifts yet.</p>';
return;
}
// Need to match signups with shift details
const signupsWithDetails = mySignups.map(signup => {
const shift = allShifts.find(s => s.ID === signup.shift_id);
return { ...signup, shift };
}).filter(s => s.shift);
list.innerHTML = signupsWithDetails.map(signup => {
const shiftDate = new Date(signup.shift.Date);
return `
<div class="signup-item">
<div>
<h4>${escapeHtml(signup.shift.Title)}</h4>
<p>📅 ${shiftDate.toLocaleDateString()}${signup.shift['Start Time']} - ${signup.shift['End Time']}</p>
</div>
<button class="btn btn-danger btn-sm cancel-signup-btn" data-shift-id="${signup.shift.ID}">Cancel</button>
</div>
`;
}).join('');
// Add event listeners after rendering
setupMySignupsListeners();
}
// New function to setup listeners for shift cards
function setupShiftCardListeners() {
const grid = document.getElementById('shifts-grid');
if (!grid) return;
// Remove any existing listeners by cloning
const newGrid = grid.cloneNode(true);
grid.parentNode.replaceChild(newGrid, grid);
// Add click listener for signup buttons
newGrid.addEventListener('click', async (e) => {
if (e.target.classList.contains('signup-btn')) {
const shiftId = e.target.getAttribute('data-shift-id');
await signupForShift(shiftId);
} else if (e.target.classList.contains('cancel-signup-btn')) {
const shiftId = e.target.getAttribute('data-shift-id');
await cancelSignup(shiftId);
}
});
}
// New function to setup listeners for my signups
function setupMySignupsListeners() {
const list = document.getElementById('my-signups-list');
if (!list) return;
// Remove any existing listeners by cloning
const newList = list.cloneNode(true);
list.parentNode.replaceChild(newList, list);
// Add click listener for cancel buttons
newList.addEventListener('click', async (e) => {
if (e.target.classList.contains('cancel-signup-btn')) {
const shiftId = e.target.getAttribute('data-shift-id');
await cancelSignup(shiftId);
}
});
}
async function signupForShift(shiftId) {
try {
const response = await fetch(`/api/shifts/${shiftId}/signup`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (data.success) {
showStatus('Successfully signed up for shift!', 'success');
await loadShifts();
await loadMySignups();
} else {
showStatus(data.error || 'Failed to sign up', 'error');
}
} catch (error) {
console.error('Error signing up:', error);
showStatus('Failed to sign up for shift', 'error');
}
}
async function cancelSignup(shiftId) {
if (!confirm('Are you sure you want to cancel your signup for this shift?')) {
return;
}
try {
const response = await fetch(`/api/shifts/${shiftId}/cancel`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (data.success) {
showStatus('Signup cancelled', 'success');
await loadShifts();
await loadMySignups();
} else {
showStatus(data.error || 'Failed to cancel signup', 'error');
}
} catch (error) {
console.error('Error cancelling signup:', error);
showStatus('Failed to cancel signup', 'error');
}
}
function setupEventListeners() {
const dateFilter = document.getElementById('date-filter');
if (dateFilter) {
dateFilter.addEventListener('change', filterShifts);
}
}
function filterShifts() {
const dateFilter = document.getElementById('date-filter').value;
if (!dateFilter) {
displayShifts(allShifts);
return;
}
const filtered = allShifts.filter(shift => {
return shift.Date === dateFilter; // Changed from shift.date to shift.Date
});
displayShifts(filtered);
}
function clearFilters() {
document.getElementById('date-filter').value = '';
loadShifts(); // Reload shifts without filters
}
function showStatus(message, type = 'info') {
const container = document.getElementById('status-container');
if (!container) return;
const messageDiv = document.createElement('div');
messageDiv.className = `status-message ${type}`;
messageDiv.textContent = message;
container.appendChild(messageDiv);
setTimeout(() => {
messageDiv.remove();
}, 5000);
}
function escapeHtml(text) {
if (text === null || text === undefined) {
return '';
}
const div = document.createElement('div');
div.textContent = String(text);
return div.innerHTML;
}