users.js

10.12 KB
06/11/2025 15:25
JS
users.js
// User Management Functions

let currentPage = 1;
let currentSearch = '';
let currentRole = '';
const usersPerPage = 10;

// Load users
async function loadUsers(page = 1, search = '', role = '') {
  try {
    showLoading();

    const response = await mockApi.getUsers(page, usersPerPage, search, role);
    const usersTableBody = document.getElementById('usersTableBody');

    if (!usersTableBody) return;

    usersTableBody.innerHTML = response.users.map(user => `
            <tr>
                <td><input type="checkbox" data-user-id="${user.id}"></td>
                <td>
                    <div class="user-cell">
                        <img src="${user.avatar}" alt="${user.name}">
                        <div class="user-cell-info">
                            <div class="user-name-cell">${user.name}</div>
                            <div class="user-email-cell">${user.email}</div>
                        </div>
                    </div>
                </td>
                <td>${user.email}</td>
                <td><span class="status-badge ${user.role}">${user.role}</span></td>
                <td><span class="status-badge ${user.status}">${user.status}</span></td>
                <td>${formatDate(user.joinedDate)}</td>
                <td class="table-actions-cell">
                    <button class="action-btn edit" onclick="editUser(${user.id})" title="Edit">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="action-btn delete" onclick="deleteUser(${user.id})" title="Delete">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `).join('');

    renderPagination(response.page, response.totalPages);

    currentPage = page;
    currentSearch = search;
    currentRole = role;
  } catch (error) {
    console.error('Error loading users:', error);
    showToast('Failed to load users', 'error');
  } finally {
    hideLoading();
  }
}

// Render pagination
function renderPagination(currentPage, totalPages) {
  const pagination = document.getElementById('usersPagination');
  if (!pagination) return;

  let html = `
        <button ${currentPage === 1 ? 'disabled' : ''} onclick="loadUsers(${currentPage - 1}, currentSearch, currentRole)">
            <i class="fas fa-chevron-left"></i>
        </button>
    `;

  for (let i = 1; i <= totalPages; i++) {
    if (i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
      html += `
                <button class="${i === currentPage ? 'active' : ''}" onclick="loadUsers(${i}, currentSearch, currentRole)">
                    ${i}
                </button>
            `;
    } else if (i === currentPage - 2 || i === currentPage + 2) {
      html += '<button disabled>...</button>';
    }
  }

  html += `
        <button ${currentPage === totalPages ? 'disabled' : ''} onclick="loadUsers(${currentPage + 1}, currentSearch, currentRole)">
            <i class="fas fa-chevron-right"></i>
        </button>
    `;

  pagination.innerHTML = html;
}

// Add user
async function addUser(userData) {
  try {
    showLoading();

    const response = await mockApi.createUser(userData);

    if (response.success) {
      showToast('User added successfully', 'success');
      closeModal('userModal');
      loadUsers(currentPage, currentSearch, currentRole);
    }
  } catch (error) {
    console.error('Error adding user:', error);
    showToast('Failed to add user', 'error');
  } finally {
    hideLoading();
  }
}

// Update user
async function updateUser(userId, userData) {
  try {
    showLoading();

    const response = await mockApi.updateUser(userId, userData);

    if (response.success) {
      showToast('User updated successfully', 'success');
      closeModal('userModal');
      loadUsers(currentPage, currentSearch, currentRole);
    }
  } catch (error) {
    console.error('Error updating user:', error);
    showToast('Failed to update user', 'error');
  } finally {
    hideLoading();
  }
}

// Edit user
async function editUser(userId) {
  try {
    showLoading();

    // Find user from current table
    const userRow = document.querySelector(`input[data-user-id="${userId}"]`)?.closest('tr');
    if (!userRow) {
      showToast('User not found', 'error');
      return;
    }

    // Extract user data from the row
    const userNameCell = userRow.querySelector('.user-name-cell');
    const userEmailCell = userRow.querySelector('.user-email-cell');
    const roleCell = userRow.querySelectorAll('td')[3];
    const statusCell = userRow.querySelectorAll('td')[4];

    const userName = userNameCell?.textContent || '';
    const userEmail = userEmailCell?.textContent || '';
    const userRole = roleCell?.querySelector('.status-badge')?.textContent || 'user';
    const userStatus = statusCell?.querySelector('.status-badge')?.textContent || 'active';

    // Populate the form
    const userForm = document.getElementById('userForm');
    const modalTitle = document.getElementById('userModalTitle');

    if (userForm && modalTitle) {
      modalTitle.textContent = 'Edit User';
      userForm.querySelector('input[name="name"]').value = userName;
      userForm.querySelector('input[name="email"]').value = userEmail;
      userForm.querySelector('select[name="role"]').value = userRole;

      // Hide password field for editing
      const passwordField = userForm.querySelector('input[name="password"]');
      const passwordGroup = passwordField?.closest('.form-group');
      if (passwordGroup) {
        passwordGroup.style.display = 'none';
        passwordField.removeAttribute('required');
      }

      // Store user ID in form for update
      userForm.dataset.editUserId = userId;
      userForm.dataset.editMode = 'true';

      openModal('userModal');
    }
  } catch (error) {
    console.error('Error editing user:', error);
    showToast('Failed to load user data', 'error');
  } finally {
    hideLoading();
  }
}

// Delete user
async function deleteUser(userId) {
  if (!confirm('Are you sure you want to delete this user?')) return;

  try {
    showLoading();

    const response = await mockApi.deleteUser(userId);

    if (response.success) {
      showToast('User deleted successfully', 'success');
      loadUsers(currentPage, currentSearch, currentRole);
    }
  } catch (error) {
    console.error('Error deleting user:', error);
    showToast('Failed to delete user', 'error');
  } finally {
    hideLoading();
  }
}

// Export users
function exportUsers() {
  // In a real app, fetch all users and export
  showToast('Exporting users...', 'info');

  setTimeout(() => {
    const mockUsers = mockData.generateUsers(20);
    exportToCSV(mockUsers, 'users.csv');
    showToast('Users exported successfully', 'success');
  }, 1000);
}

// Initialize user management
function initUserManagement() {
  // Load users
  loadUsers();

  // Search functionality
  const userSearch = document.getElementById('userSearch');
  if (userSearch) {
    userSearch.addEventListener('input', debounce((e) => {
      loadUsers(1, e.target.value, currentRole);
    }, 500));
  }

  // Role filter
  const roleFilter = document.getElementById('roleFilter');
  if (roleFilter) {
    roleFilter.addEventListener('change', (e) => {
      loadUsers(1, currentSearch, e.target.value);
    });
  }

  // Add user button
  const addUserBtn = document.getElementById('addUserBtn');
  if (addUserBtn) {
    addUserBtn.addEventListener('click', () => {
      // Reset form to add mode
      const userForm = document.getElementById('userForm');
      const modalTitle = document.getElementById('userModalTitle');

      if (userForm) {
        userForm.reset();
        delete userForm.dataset.editUserId;
        delete userForm.dataset.editMode;

        // Show password field
        const passwordField = userForm.querySelector('input[name="password"]');
        const passwordGroup = passwordField?.closest('.form-group');
        if (passwordGroup) {
          passwordGroup.style.display = 'block';
          passwordField.setAttribute('required', 'required');
        }
      }

      if (modalTitle) {
        modalTitle.textContent = 'Add User';
      }

      openModal('userModal');
    });
  }

  // Export button
  const exportBtn = document.getElementById('exportUsers');
  if (exportBtn) {
    exportBtn.addEventListener('click', exportUsers);
  }

  // User form submission
  const userForm = document.getElementById('userForm');
  if (userForm) {
    userForm.addEventListener('submit', async (e) => {
      e.preventDefault();

      if (!validateForm(userForm)) {
        showToast('Please fill in all required fields', 'error');
        return;
      }

      const formData = new FormData(userForm);
      const isEditMode = userForm.dataset.editMode === 'true';
      const userId = userForm.dataset.editUserId;

      const userData = {
        name: formData.get('name'),
        email: formData.get('email'),
        role: formData.get('role'),
        status: 'active'
      };

      // Only include password if not in edit mode or if password is provided
      if (!isEditMode && formData.get('password')) {
        userData.password = formData.get('password');
      }

      if (isEditMode && userId) {
        await updateUser(userId, userData);
      } else {
        await addUser(userData);
      }

      // Reset form and edit mode
      userForm.reset();
      delete userForm.dataset.editUserId;
      delete userForm.dataset.editMode;

      // Reset modal title and show password field
      const modalTitle = document.getElementById('userModalTitle');
      if (modalTitle) {
        modalTitle.textContent = 'Add User';
      }

      const passwordField = userForm.querySelector('input[name="password"]');
      const passwordGroup = passwordField?.closest('.form-group');
      if (passwordGroup) {
        passwordGroup.style.display = 'block';
        passwordField.setAttribute('required', 'required');
      }
    });
  }

  // Select all checkbox
  const selectAll = document.getElementById('selectAll');
  if (selectAll) {
    selectAll.addEventListener('change', (e) => {
      const checkboxes = document.querySelectorAll('input[data-user-id]');
      checkboxes.forEach(cb => cb.checked = e.target.checked);
    });
  }
}