A couple more fast email buttons
This commit is contained in:
@@ -500,6 +500,12 @@ function showSection(sectionId) {
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
|
||||
// Special handling for shifts section
|
||||
if (sectionId === 'shifts') {
|
||||
console.log('Loading shifts for admin panel...');
|
||||
loadAdminShifts();
|
||||
}
|
||||
}
|
||||
|
||||
// Update map from input fields
|
||||
@@ -1113,17 +1119,31 @@ function debounce(func, wait) {
|
||||
|
||||
// Add shift management functions
|
||||
async function loadAdminShifts() {
|
||||
const list = document.getElementById('admin-shifts-list');
|
||||
if (list) {
|
||||
list.innerHTML = '<p>Loading shifts...</p>';
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('Loading admin shifts...');
|
||||
const response = await fetch('/api/shifts/admin');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
console.log('Successfully loaded', data.shifts.length, 'shifts');
|
||||
displayAdminShifts(data.shifts);
|
||||
} else {
|
||||
console.error('Failed to load shifts:', data.error);
|
||||
if (list) {
|
||||
list.innerHTML = '<p>Failed to load shifts</p>';
|
||||
}
|
||||
showStatus('Failed to load shifts', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading admin shifts:', error);
|
||||
if (list) {
|
||||
list.innerHTML = '<p>Error loading shifts</p>';
|
||||
}
|
||||
showStatus('Failed to load shifts', 'error');
|
||||
}
|
||||
}
|
||||
@@ -1145,6 +1165,8 @@ function displayAdminShifts(shifts) {
|
||||
const shiftDate = new Date(shift.Date);
|
||||
const signupCount = shift.signups ? shift.signups.length : 0;
|
||||
|
||||
console.log(`Shift "${shift.Title}" (ID: ${shift.ID}) has ${signupCount} volunteers:`, shift.signups?.map(s => s['User Email']) || []);
|
||||
|
||||
return `
|
||||
<div class="shift-admin-item">
|
||||
<div>
|
||||
@@ -1155,6 +1177,7 @@ function displayAdminShifts(shifts) {
|
||||
<p class="status-${(shift.Status || 'open').toLowerCase()}">${shift.Status || 'Open'}</p>
|
||||
</div>
|
||||
<div class="shift-actions">
|
||||
<button class="btn btn-primary btn-sm manage-volunteers-btn" data-shift-id="${shift.ID}" data-shift='${JSON.stringify(shift).replace(/'/g, "'")}'>Manage Volunteers</button>
|
||||
<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>
|
||||
@@ -1187,6 +1210,11 @@ function setupShiftActionListeners() {
|
||||
const shiftId = e.target.getAttribute('data-shift-id');
|
||||
console.log('Edit button clicked for shift:', shiftId);
|
||||
editShift(shiftId);
|
||||
} else if (e.target.classList.contains('manage-volunteers-btn')) {
|
||||
const shiftId = e.target.getAttribute('data-shift-id');
|
||||
const shiftData = JSON.parse(e.target.getAttribute('data-shift').replace(/'/g, "'"));
|
||||
console.log('Manage volunteers clicked for shift:', shiftId);
|
||||
showShiftUserModal(shiftId, shiftData);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1207,6 +1235,7 @@ async function deleteShift(shiftId) {
|
||||
if (data.success) {
|
||||
showStatus('Shift deleted successfully', 'success');
|
||||
await loadAdminShifts();
|
||||
console.log('Refreshed shifts list after deleting shift');
|
||||
} else {
|
||||
showStatus(data.error || 'Failed to delete shift', 'error');
|
||||
}
|
||||
@@ -1250,6 +1279,7 @@ async function createShift(e) {
|
||||
showStatus('Shift created successfully', 'success');
|
||||
document.getElementById('shift-form').reset();
|
||||
await loadAdminShifts();
|
||||
console.log('Refreshed shifts list after creating new shift');
|
||||
} else {
|
||||
showStatus(data.error || 'Failed to create shift', 'error');
|
||||
}
|
||||
@@ -1304,13 +1334,29 @@ function displayUsers(users) {
|
||||
const container = document.querySelector('.users-list');
|
||||
if (!container) return;
|
||||
|
||||
// Find or create the users table container, preserving the header
|
||||
let usersTableContainer = container.querySelector('.users-table-container');
|
||||
if (!usersTableContainer) {
|
||||
// If container doesn't exist, create it after the header
|
||||
const header = container.querySelector('.users-list-header');
|
||||
usersTableContainer = document.createElement('div');
|
||||
usersTableContainer.className = 'users-table-container';
|
||||
|
||||
if (header && header.nextSibling) {
|
||||
container.insertBefore(usersTableContainer, header.nextSibling);
|
||||
} else if (header) {
|
||||
container.appendChild(usersTableContainer);
|
||||
} else {
|
||||
container.appendChild(usersTableContainer);
|
||||
}
|
||||
}
|
||||
|
||||
if (!users || users.length === 0) {
|
||||
container.innerHTML = '<h3>Existing Users</h3><p class="empty-message">No users found.</p>';
|
||||
usersTableContainer.innerHTML = '<p class="empty-message">No users found.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
const tableHtml = `
|
||||
<h3>Existing Users</h3>
|
||||
<div class="users-table-wrapper">
|
||||
<table class="users-table">
|
||||
<thead>
|
||||
@@ -1322,7 +1368,7 @@ function displayUsers(users) {
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tbody id="users-table-body">
|
||||
${users.map(user => {
|
||||
const createdDate = user.created_at || user['Created At'] || user.createdAt;
|
||||
const formattedDate = createdDate ? new Date(createdDate).toLocaleDateString() : 'N/A';
|
||||
@@ -1376,7 +1422,7 @@ function displayUsers(users) {
|
||||
<p id="users-loading" class="loading-message" style="display: none;">Loading...</p>
|
||||
`;
|
||||
|
||||
container.innerHTML = tableHtml;
|
||||
usersTableContainer.innerHTML = tableHtml;
|
||||
setupUserActionListeners();
|
||||
}
|
||||
|
||||
@@ -1402,6 +1448,9 @@ function setupUserActionListeners() {
|
||||
const userEmail = e.target.getAttribute('data-user-email');
|
||||
console.log('Send login details button clicked for user:', userId);
|
||||
sendLoginDetailsToUser(userId, userEmail);
|
||||
} else if (e.target.id === 'email-all-users-btn') {
|
||||
console.log('Email All Users button clicked');
|
||||
showEmailUsersModal();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1545,6 +1594,318 @@ function clearUserForm() {
|
||||
}
|
||||
}
|
||||
|
||||
// Email All Users Functions
|
||||
let allUsersData = [];
|
||||
|
||||
async function showEmailUsersModal() {
|
||||
// Load current users data
|
||||
try {
|
||||
const response = await fetch('/api/users');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success && data.users) {
|
||||
allUsersData = data.users;
|
||||
|
||||
// Update recipients count
|
||||
const recipientsCount = document.getElementById('recipients-count');
|
||||
if (recipientsCount) {
|
||||
recipientsCount.textContent = `${allUsersData.length}`;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading users for email:', error);
|
||||
showStatus('Failed to load user data', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Show modal
|
||||
const modal = document.getElementById('email-users-modal');
|
||||
if (modal) {
|
||||
modal.style.display = 'flex';
|
||||
|
||||
// Clear previous content
|
||||
document.getElementById('email-subject').value = '';
|
||||
document.getElementById('email-content').innerHTML = '';
|
||||
document.getElementById('show-preview').checked = false;
|
||||
document.getElementById('email-preview').style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function closeEmailUsersModal() {
|
||||
const modal = document.getElementById('email-users-modal');
|
||||
if (modal) {
|
||||
modal.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function setupRichTextEditor() {
|
||||
const toolbar = document.querySelector('.rich-text-toolbar');
|
||||
const editor = document.getElementById('email-content');
|
||||
|
||||
if (!toolbar || !editor) return;
|
||||
|
||||
// Handle toolbar button clicks
|
||||
toolbar.addEventListener('click', (e) => {
|
||||
if (e.target.classList.contains('toolbar-btn')) {
|
||||
e.preventDefault();
|
||||
const command = e.target.getAttribute('data-command');
|
||||
|
||||
if (command === 'createLink') {
|
||||
const url = prompt('Enter the URL:');
|
||||
if (url) {
|
||||
document.execCommand(command, false, url);
|
||||
}
|
||||
} else {
|
||||
document.execCommand(command, false, null);
|
||||
}
|
||||
|
||||
// Update preview if visible
|
||||
updateEmailPreview();
|
||||
}
|
||||
});
|
||||
|
||||
// Update preview on content change
|
||||
editor.addEventListener('input', updateEmailPreview);
|
||||
|
||||
// Handle preview toggle
|
||||
const showPreviewCheckbox = document.getElementById('show-preview');
|
||||
if (showPreviewCheckbox) {
|
||||
showPreviewCheckbox.addEventListener('change', togglePreview);
|
||||
}
|
||||
|
||||
// Update preview when subject changes
|
||||
const subjectInput = document.getElementById('email-subject');
|
||||
if (subjectInput) {
|
||||
subjectInput.addEventListener('input', updateEmailPreview);
|
||||
}
|
||||
}
|
||||
|
||||
function togglePreview() {
|
||||
const preview = document.getElementById('email-preview');
|
||||
const checkbox = document.getElementById('show-preview');
|
||||
|
||||
if (preview && checkbox) {
|
||||
if (checkbox.checked) {
|
||||
preview.style.display = 'block';
|
||||
updateEmailPreview();
|
||||
} else {
|
||||
preview.style.display = 'none';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateEmailPreview() {
|
||||
const previewSubject = document.getElementById('preview-subject');
|
||||
const previewBody = document.getElementById('preview-body');
|
||||
const subjectInput = document.getElementById('email-subject');
|
||||
const contentEditor = document.getElementById('email-content');
|
||||
|
||||
if (previewSubject && subjectInput) {
|
||||
previewSubject.textContent = subjectInput.value || 'Your subject will appear here';
|
||||
}
|
||||
|
||||
if (previewBody && contentEditor) {
|
||||
const content = contentEditor.innerHTML || 'Your message will appear here';
|
||||
previewBody.innerHTML = content;
|
||||
}
|
||||
}
|
||||
|
||||
async function sendEmailToAllUsers(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const subject = document.getElementById('email-subject').value.trim();
|
||||
const content = document.getElementById('email-content').innerHTML.trim();
|
||||
|
||||
if (!subject) {
|
||||
showStatus('Please enter an email subject', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!content || content === '<br>' || content === '') {
|
||||
showStatus('Please enter email content', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (allUsersData.length === 0) {
|
||||
showStatus('No users found to email', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const confirmMessage = `Send this email to all ${allUsersData.length} users?`;
|
||||
if (!confirm(confirmMessage)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Initialize progress tracking
|
||||
initializeEmailProgress(allUsersData.length);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/users/email-all', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
subject: subject,
|
||||
content: content
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
// Display detailed results
|
||||
updateEmailProgress(data.results);
|
||||
showStatus(data.message, 'success');
|
||||
console.log('Email results:', data.results);
|
||||
} else {
|
||||
showEmailError(data.error || 'Failed to send emails');
|
||||
if (data.details) {
|
||||
console.error('Failed email details:', data.details);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error sending emails to all users:', error);
|
||||
showEmailError('Failed to send emails - Network error');
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize email progress display
|
||||
function initializeEmailProgress(totalCount) {
|
||||
const progressContainer = document.getElementById('email-progress-container');
|
||||
const statusList = document.getElementById('email-status-list');
|
||||
const pendingCountEl = document.getElementById('pending-count');
|
||||
const successCountEl = document.getElementById('success-count');
|
||||
const errorCountEl = document.getElementById('error-count');
|
||||
const progressBar = document.getElementById('email-progress-bar');
|
||||
const progressText = document.getElementById('progress-text');
|
||||
const closeBtn = document.getElementById('close-progress-btn');
|
||||
|
||||
// Show progress container
|
||||
progressContainer.classList.add('show');
|
||||
|
||||
// Reset counters
|
||||
pendingCountEl.textContent = totalCount;
|
||||
successCountEl.textContent = '0';
|
||||
errorCountEl.textContent = '0';
|
||||
|
||||
// Reset progress bar
|
||||
progressBar.style.width = '0%';
|
||||
progressBar.classList.remove('complete', 'error');
|
||||
progressText.textContent = '0%';
|
||||
|
||||
// Clear status list
|
||||
statusList.innerHTML = '';
|
||||
|
||||
// Hide close button initially
|
||||
closeBtn.style.display = 'none';
|
||||
|
||||
// Add status items for each user
|
||||
allUsersData.forEach(user => {
|
||||
const statusItem = document.createElement('div');
|
||||
statusItem.className = 'email-status-item';
|
||||
statusItem.innerHTML = `
|
||||
<div class="email-status-recipient">${user.Name || user.Email}</div>
|
||||
<div class="email-status-result pending">
|
||||
<div class="progress-spinner"></div>
|
||||
<span>Sending...</span>
|
||||
</div>
|
||||
`;
|
||||
statusList.appendChild(statusItem);
|
||||
});
|
||||
}
|
||||
|
||||
// Update progress with results
|
||||
function updateEmailProgress(results) {
|
||||
const statusList = document.getElementById('email-status-list');
|
||||
const pendingCountEl = document.getElementById('pending-count');
|
||||
const successCountEl = document.getElementById('success-count');
|
||||
const errorCountEl = document.getElementById('error-count');
|
||||
const progressBar = document.getElementById('email-progress-bar');
|
||||
const progressText = document.getElementById('progress-text');
|
||||
const closeBtn = document.getElementById('close-progress-btn');
|
||||
|
||||
const successful = results.successful || [];
|
||||
const failed = results.failed || [];
|
||||
const total = results.total || (successful.length + failed.length);
|
||||
|
||||
// Update counters
|
||||
successCountEl.textContent = successful.length;
|
||||
errorCountEl.textContent = failed.length;
|
||||
pendingCountEl.textContent = '0';
|
||||
|
||||
// Update progress bar
|
||||
const percentage = ((successful.length + failed.length) / total * 100).toFixed(1);
|
||||
progressBar.style.width = percentage + '%';
|
||||
progressText.textContent = percentage + '%';
|
||||
|
||||
if (failed.length > 0) {
|
||||
progressBar.classList.add('error');
|
||||
} else {
|
||||
progressBar.classList.add('complete');
|
||||
}
|
||||
|
||||
// Update individual status items
|
||||
const statusItems = statusList.children;
|
||||
|
||||
// Update successful emails
|
||||
successful.forEach(result => {
|
||||
const statusItem = Array.from(statusItems).find(item =>
|
||||
item.querySelector('.email-status-recipient').textContent.includes(result.email) ||
|
||||
item.querySelector('.email-status-recipient').textContent.includes(result.name)
|
||||
);
|
||||
if (statusItem) {
|
||||
statusItem.querySelector('.email-status-result').innerHTML = `
|
||||
<span class="email-status-result success">✓ Sent</span>
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
// Update failed emails
|
||||
failed.forEach(result => {
|
||||
const statusItem = Array.from(statusItems).find(item =>
|
||||
item.querySelector('.email-status-recipient').textContent.includes(result.email) ||
|
||||
item.querySelector('.email-status-recipient').textContent.includes(result.name)
|
||||
);
|
||||
if (statusItem) {
|
||||
statusItem.querySelector('.email-status-result').innerHTML = `
|
||||
<span class="email-status-result error" title="${result.error || 'Unknown error'}">✗ Failed</span>
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
// Show close button
|
||||
closeBtn.style.display = 'block';
|
||||
closeBtn.onclick = () => {
|
||||
document.getElementById('email-progress-container').classList.remove('show');
|
||||
closeEmailUsersModal();
|
||||
};
|
||||
}
|
||||
|
||||
// Show email error
|
||||
function showEmailError(message) {
|
||||
const progressContainer = document.getElementById('email-progress-container');
|
||||
const progressBar = document.getElementById('email-progress-bar');
|
||||
const progressText = document.getElementById('progress-text');
|
||||
const closeBtn = document.getElementById('close-progress-btn');
|
||||
|
||||
// Show progress container if not visible
|
||||
progressContainer.classList.add('show');
|
||||
|
||||
// Update progress bar to show error
|
||||
progressBar.style.width = '100%';
|
||||
progressBar.classList.add('error');
|
||||
progressText.textContent = 'Error';
|
||||
|
||||
// Show close button
|
||||
closeBtn.style.display = 'block';
|
||||
closeBtn.onclick = () => {
|
||||
progressContainer.classList.remove('show');
|
||||
};
|
||||
|
||||
showStatus(message, 'error');
|
||||
}
|
||||
|
||||
// Initialize NocoDB links in admin panel
|
||||
async function initializeNocodbLinks() {
|
||||
console.log('Starting NocoDB links initialization...');
|
||||
@@ -1626,3 +1987,470 @@ function setAdminNocodbLink(elementId, url) {
|
||||
console.error(`✗ Element not found: ${elementId}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Shift User Management Functions
|
||||
let currentShiftData = null;
|
||||
let allUsers = [];
|
||||
|
||||
// Load all users for the dropdown
|
||||
async function loadAllUsers() {
|
||||
try {
|
||||
const response = await fetch('/api/users');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
allUsers = data.users;
|
||||
populateUserSelect();
|
||||
} else {
|
||||
console.error('Failed to load users:', data.error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading users:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Populate user select dropdown
|
||||
function populateUserSelect() {
|
||||
const select = document.getElementById('user-select');
|
||||
if (!select) return;
|
||||
|
||||
// Clear existing options except the first one
|
||||
select.innerHTML = '<option value="">Select a user...</option>';
|
||||
|
||||
allUsers.forEach(user => {
|
||||
const option = document.createElement('option');
|
||||
option.value = user.email || user.Email;
|
||||
option.textContent = `${user.name || user.Name || ''} (${user.email || user.Email})`;
|
||||
select.appendChild(option);
|
||||
});
|
||||
}
|
||||
|
||||
// Show the shift user management modal
|
||||
async function showShiftUserModal(shiftId, shiftData) {
|
||||
currentShiftData = { ...shiftData, ID: shiftId };
|
||||
|
||||
// Update modal title and info
|
||||
document.getElementById('modal-shift-title').textContent = shiftData.Title;
|
||||
const shiftDate = new Date(shiftData.Date);
|
||||
document.getElementById('modal-shift-details').textContent =
|
||||
`${shiftDate.toLocaleDateString()} | ${shiftData['Start Time']} - ${shiftData['End Time']} | ${shiftData.Location || 'TBD'}`;
|
||||
|
||||
// Load users if not already loaded
|
||||
if (allUsers.length === 0) {
|
||||
await loadAllUsers();
|
||||
}
|
||||
|
||||
// Display current volunteers
|
||||
displayCurrentVolunteers(shiftData.signups || []);
|
||||
|
||||
// Show modal
|
||||
document.getElementById('shift-user-modal').style.display = 'flex';
|
||||
}
|
||||
|
||||
// Display current volunteers in the modal
|
||||
function displayCurrentVolunteers(volunteers) {
|
||||
const container = document.getElementById('current-volunteers-list');
|
||||
|
||||
if (!volunteers || volunteers.length === 0) {
|
||||
container.innerHTML = '<div class="no-volunteers">No volunteers signed up yet.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = volunteers.map(volunteer => `
|
||||
<div class="volunteer-item">
|
||||
<div class="volunteer-info">
|
||||
<div class="volunteer-name">${escapeHtml(volunteer['User Name'] || volunteer['User Email'] || 'Unknown')}</div>
|
||||
<div class="volunteer-email">${escapeHtml(volunteer['User Email'])}</div>
|
||||
</div>
|
||||
<div class="volunteer-actions">
|
||||
<button class="btn btn-danger btn-sm remove-volunteer-btn"
|
||||
data-volunteer-id="${volunteer.ID || volunteer.id}"
|
||||
data-volunteer-email="${volunteer['User Email']}">
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
// Add event listeners for remove buttons
|
||||
setupVolunteerActionListeners();
|
||||
}
|
||||
|
||||
// Setup event listeners for volunteer actions
|
||||
function setupVolunteerActionListeners() {
|
||||
const container = document.getElementById('current-volunteers-list');
|
||||
|
||||
container.addEventListener('click', function(e) {
|
||||
if (e.target.classList.contains('remove-volunteer-btn')) {
|
||||
const volunteerId = e.target.getAttribute('data-volunteer-id');
|
||||
const volunteerEmail = e.target.getAttribute('data-volunteer-email');
|
||||
removeVolunteerFromShift(volunteerId, volunteerEmail);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Add user to shift
|
||||
async function addUserToShift() {
|
||||
const userSelect = document.getElementById('user-select');
|
||||
const userEmail = userSelect.value;
|
||||
|
||||
if (!userEmail) {
|
||||
showStatus('Please select a user to add', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!currentShiftData) {
|
||||
showStatus('No shift selected', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/shifts/admin/${currentShiftData.ID}/add-user`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ userEmail })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
showStatus('User successfully added to shift', 'success');
|
||||
userSelect.value = ''; // Clear selection
|
||||
|
||||
// Refresh the shift data and reload volunteers
|
||||
await refreshCurrentShiftData();
|
||||
console.log('Refreshed shift data after adding user');
|
||||
} else {
|
||||
showStatus(data.error || 'Failed to add user to shift', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error adding user to shift:', error);
|
||||
showStatus('Failed to add user to shift', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// Remove volunteer from shift
|
||||
async function removeVolunteerFromShift(volunteerId, volunteerEmail) {
|
||||
if (!confirm(`Are you sure you want to remove ${volunteerEmail} from this shift?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!currentShiftData) {
|
||||
showStatus('No shift selected', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/shifts/admin/${currentShiftData.ID}/remove-user/${volunteerId}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
showStatus('Volunteer successfully removed from shift', 'success');
|
||||
|
||||
// Refresh the shift data and reload volunteers
|
||||
await refreshCurrentShiftData();
|
||||
console.log('Refreshed shift data after removing volunteer');
|
||||
} else {
|
||||
showStatus(data.error || 'Failed to remove volunteer from shift', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error removing volunteer from shift:', error);
|
||||
showStatus('Failed to remove volunteer from shift', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh current shift data
|
||||
async function refreshCurrentShiftData() {
|
||||
if (!currentShiftData) return;
|
||||
|
||||
try {
|
||||
console.log('Refreshing shift data for shift ID:', currentShiftData.ID);
|
||||
|
||||
// Reload admin shifts to get updated data
|
||||
const response = await fetch('/api/shifts/admin');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
const updatedShift = data.shifts.find(s => s.ID === currentShiftData.ID);
|
||||
if (updatedShift) {
|
||||
console.log('Found updated shift with', updatedShift.signups?.length || 0, 'volunteers');
|
||||
currentShiftData = updatedShift;
|
||||
displayCurrentVolunteers(updatedShift.signups || []);
|
||||
|
||||
// Immediately refresh the main shifts list to show updated counts
|
||||
console.log('Refreshing main shifts list with', data.shifts.length, 'shifts');
|
||||
displayAdminShifts(data.shifts);
|
||||
} else {
|
||||
console.warn('Could not find updated shift with ID:', currentShiftData.ID);
|
||||
}
|
||||
} else {
|
||||
console.error('Failed to refresh shift data:', data.error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error refreshing shift data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Close modal
|
||||
function closeShiftUserModal() {
|
||||
document.getElementById('shift-user-modal').style.display = 'none';
|
||||
currentShiftData = null;
|
||||
|
||||
// Refresh the main shifts list one more time when closing the modal
|
||||
// to ensure any changes are reflected
|
||||
console.log('Refreshing shifts list on modal close');
|
||||
loadAdminShifts();
|
||||
}
|
||||
|
||||
// Email shift details to all volunteers
|
||||
async function emailShiftDetails() {
|
||||
if (!currentShiftData) {
|
||||
showStatus('No shift selected', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if there are volunteers to email
|
||||
const volunteers = currentShiftData.signups || [];
|
||||
if (volunteers.length === 0) {
|
||||
showStatus('No volunteers signed up for this shift', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// Confirm action
|
||||
const confirmMessage = `Send shift details email to ${volunteers.length} volunteer${volunteers.length !== 1 ? 's' : ''}?`;
|
||||
if (!confirm(confirmMessage)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Initialize progress tracking for shift emails
|
||||
initializeShiftEmailProgress(volunteers.length);
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/shifts/admin/${currentShiftData.ID}/email-details`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
// Display detailed results
|
||||
updateShiftEmailProgress(data.results);
|
||||
showStatus(data.message, 'success');
|
||||
console.log('Email results:', data.results);
|
||||
} else {
|
||||
showShiftEmailError(data.error || 'Failed to send emails');
|
||||
if (data.details) {
|
||||
console.error('Failed email details:', data.details);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error sending shift details emails:', error);
|
||||
showShiftEmailError('Failed to send emails - Network error');
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize shift email progress display
|
||||
function initializeShiftEmailProgress(totalCount) {
|
||||
const progressContainer = document.getElementById('shift-email-progress-container');
|
||||
const statusList = document.getElementById('shift-email-status-list');
|
||||
const pendingCountEl = document.getElementById('shift-pending-count');
|
||||
const successCountEl = document.getElementById('shift-success-count');
|
||||
const errorCountEl = document.getElementById('shift-error-count');
|
||||
const progressBar = document.getElementById('shift-email-progress-bar');
|
||||
const progressText = document.getElementById('shift-progress-text');
|
||||
const closeBtn = document.getElementById('close-shift-progress-btn');
|
||||
|
||||
// Show progress container
|
||||
progressContainer.classList.add('show');
|
||||
|
||||
// Reset counters
|
||||
pendingCountEl.textContent = totalCount;
|
||||
successCountEl.textContent = '0';
|
||||
errorCountEl.textContent = '0';
|
||||
|
||||
// Reset progress bar
|
||||
progressBar.style.width = '0%';
|
||||
progressBar.classList.remove('complete', 'error');
|
||||
progressText.textContent = '0%';
|
||||
|
||||
// Clear status list
|
||||
statusList.innerHTML = '';
|
||||
|
||||
// Hide close button initially
|
||||
closeBtn.style.display = 'none';
|
||||
|
||||
// Add status items for each volunteer
|
||||
const volunteers = currentShiftData.signups || [];
|
||||
volunteers.forEach(volunteer => {
|
||||
const statusItem = document.createElement('div');
|
||||
statusItem.className = 'email-status-item';
|
||||
statusItem.innerHTML = `
|
||||
<div class="email-status-recipient">${volunteer['User Name'] || volunteer['User Email']}</div>
|
||||
<div class="email-status-result pending">
|
||||
<div class="progress-spinner"></div>
|
||||
<span>Sending...</span>
|
||||
</div>
|
||||
`;
|
||||
statusList.appendChild(statusItem);
|
||||
});
|
||||
}
|
||||
|
||||
// Update shift email progress with results
|
||||
function updateShiftEmailProgress(results) {
|
||||
const statusList = document.getElementById('shift-email-status-list');
|
||||
const pendingCountEl = document.getElementById('shift-pending-count');
|
||||
const successCountEl = document.getElementById('shift-success-count');
|
||||
const errorCountEl = document.getElementById('shift-error-count');
|
||||
const progressBar = document.getElementById('shift-email-progress-bar');
|
||||
const progressText = document.getElementById('shift-progress-text');
|
||||
const closeBtn = document.getElementById('close-shift-progress-btn');
|
||||
|
||||
const successful = results.successful || [];
|
||||
const failed = results.failed || [];
|
||||
const total = results.total || (successful.length + failed.length);
|
||||
|
||||
// Update counters
|
||||
successCountEl.textContent = successful.length;
|
||||
errorCountEl.textContent = failed.length;
|
||||
pendingCountEl.textContent = '0';
|
||||
|
||||
// Update progress bar
|
||||
const percentage = ((successful.length + failed.length) / total * 100).toFixed(1);
|
||||
progressBar.style.width = percentage + '%';
|
||||
progressText.textContent = percentage + '%';
|
||||
|
||||
if (failed.length > 0) {
|
||||
progressBar.classList.add('error');
|
||||
} else {
|
||||
progressBar.classList.add('complete');
|
||||
}
|
||||
|
||||
// Update individual status items
|
||||
const statusItems = statusList.children;
|
||||
|
||||
// Update successful emails
|
||||
successful.forEach(result => {
|
||||
const statusItem = Array.from(statusItems).find(item =>
|
||||
item.querySelector('.email-status-recipient').textContent.includes(result.email) ||
|
||||
item.querySelector('.email-status-recipient').textContent.includes(result.name)
|
||||
);
|
||||
if (statusItem) {
|
||||
statusItem.querySelector('.email-status-result').innerHTML = `
|
||||
<span class="email-status-result success">✓ Sent</span>
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
// Update failed emails
|
||||
failed.forEach(result => {
|
||||
const statusItem = Array.from(statusItems).find(item =>
|
||||
item.querySelector('.email-status-recipient').textContent.includes(result.email) ||
|
||||
item.querySelector('.email-status-recipient').textContent.includes(result.name)
|
||||
);
|
||||
if (statusItem) {
|
||||
statusItem.querySelector('.email-status-result').innerHTML = `
|
||||
<span class="email-status-result error" title="${result.error || 'Unknown error'}">✗ Failed</span>
|
||||
`;
|
||||
}
|
||||
});
|
||||
|
||||
// Show close button
|
||||
closeBtn.style.display = 'block';
|
||||
closeBtn.onclick = () => {
|
||||
document.getElementById('shift-email-progress-container').classList.remove('show');
|
||||
};
|
||||
}
|
||||
|
||||
// Show shift email error
|
||||
function showShiftEmailError(message) {
|
||||
const progressContainer = document.getElementById('shift-email-progress-container');
|
||||
const progressBar = document.getElementById('shift-email-progress-bar');
|
||||
const progressText = document.getElementById('shift-progress-text');
|
||||
const closeBtn = document.getElementById('close-shift-progress-btn');
|
||||
|
||||
// Show progress container if not visible
|
||||
progressContainer.classList.add('show');
|
||||
|
||||
// Update progress bar to show error
|
||||
progressBar.style.width = '100%';
|
||||
progressBar.classList.add('error');
|
||||
progressText.textContent = 'Error';
|
||||
|
||||
// Show close button
|
||||
closeBtn.style.display = 'block';
|
||||
closeBtn.onclick = () => {
|
||||
progressContainer.classList.remove('show');
|
||||
};
|
||||
|
||||
showStatus(message, 'error');
|
||||
}
|
||||
|
||||
// Setup modal event listeners when DOM is loaded
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const closeModalBtn = document.getElementById('close-user-modal');
|
||||
const addUserBtn = document.getElementById('add-user-btn');
|
||||
const emailShiftDetailsBtn = document.getElementById('email-shift-details-btn');
|
||||
const modal = document.getElementById('shift-user-modal');
|
||||
|
||||
if (closeModalBtn) {
|
||||
closeModalBtn.addEventListener('click', closeShiftUserModal);
|
||||
}
|
||||
|
||||
if (addUserBtn) {
|
||||
addUserBtn.addEventListener('click', addUserToShift);
|
||||
}
|
||||
|
||||
if (emailShiftDetailsBtn) {
|
||||
emailShiftDetailsBtn.addEventListener('click', emailShiftDetails);
|
||||
}
|
||||
|
||||
// Close modal when clicking outside
|
||||
if (modal) {
|
||||
modal.addEventListener('click', function(e) {
|
||||
if (e.target === modal) {
|
||||
closeShiftUserModal();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Setup email users modal event listeners when DOM is loaded
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Email all users functionality
|
||||
const closeEmailModalBtn = document.getElementById('close-email-modal');
|
||||
const cancelEmailBtn = document.getElementById('cancel-email-btn');
|
||||
const emailUsersForm = document.getElementById('email-users-form');
|
||||
const emailModal = document.getElementById('email-users-modal');
|
||||
|
||||
if (closeEmailModalBtn) {
|
||||
closeEmailModalBtn.addEventListener('click', closeEmailUsersModal);
|
||||
}
|
||||
|
||||
if (cancelEmailBtn) {
|
||||
cancelEmailBtn.addEventListener('click', closeEmailUsersModal);
|
||||
}
|
||||
|
||||
if (emailUsersForm) {
|
||||
emailUsersForm.addEventListener('submit', sendEmailToAllUsers);
|
||||
}
|
||||
|
||||
// Close modal when clicking outside
|
||||
if (emailModal) {
|
||||
emailModal.addEventListener('click', function(e) {
|
||||
if (e.target === emailModal) {
|
||||
closeEmailUsersModal();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Setup rich text editor functionality
|
||||
setupRichTextEditor();
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user