Fix Delete Employee button

This commit is contained in:
2025-08-27 21:26:12 -04:00
parent 41b10a5a03
commit 18bc24d428
3 changed files with 338 additions and 151 deletions
+25 -6
View File
@@ -5879,10 +5879,15 @@ def edit_employee(employee_index):
@admin_required
@log_database_operations('employee_deletion')
def delete_employee(employee_index):
"""Delete employee (Admin only)"""
"""Delete employee (Admin only) - Enhanced with better logging"""
try:
print(f"🗑️ DELETE REQUEST: Employee index {employee_index}")
print(f"📋 Request method: {request.method}")
print(f"👤 User: {session.get('username', 'Unknown')}")
# Get employee by index (primary key)
employee = Employee.query.get_or_404(employee_index)
print(f"✅ Found employee: {employee.firstName} {employee.lastName} (ID: {employee.id})")
# Store employee data for logging before deletion
employee_data = {
@@ -5897,28 +5902,42 @@ def delete_employee(employee_index):
# Check if employee has attendance records
from models.attendance import AttendanceData
attendance_count = AttendanceData.query.filter_by(employee_id=str(employee.id)).count()
print(f"📊 Attendance records found: {attendance_count}")
if attendance_count > 0:
flash(f'Cannot delete employee "{employee.full_name}". Employee has {attendance_count} attendance records. Please contact system administrator.', 'error')
error_msg = f'Cannot delete employee "{employee.full_name}". Employee has {attendance_count} attendance records. Please contact system administrator.'
print(f"❌ DELETION BLOCKED: {error_msg}")
flash(error_msg, 'error')
return redirect(url_for('employees'))
# Proceed with deletion
print(f"🗑️ Proceeding with deletion of employee: {employee_data['firstName']} {employee_data['lastName']}")
db.session.delete(employee)
db.session.commit()
print("✅ Employee successfully deleted from database")
# Log employee deletion
try:
logger_handler.logger.info(f"Admin user {session['username']} deleted employee: {employee_data['firstName']} {employee_data['lastName']} (ID: {employee_data['id']})")
print(f"📋 Deletion logged successfully")
except Exception as log_error:
print(f"⚠️ Logging error (non-critical): {log_error}")
flash(f'Employee "{employee_data["firstName"]} {employee_data["lastName"]}" deleted successfully.', 'success')
success_msg = f'Employee "{employee_data["firstName"]} {employee_data["lastName"]}" deleted successfully.'
flash(success_msg, 'success')
print(f"✅ SUCCESS: {success_msg}")
return redirect(url_for('employees'))
except Exception as e:
db.session.rollback()
logger_handler.log_database_error('employee_deletion', e)
flash('Error deleting employee. Please try again.', 'error')
return redirect(url_for('employees'))
error_msg = f'Error deleting employee. Please try again.'
print(f"❌ ERROR in delete_employee: {e}")
print(f"❌ Exception type: {type(e)}")
flash(error_msg, 'error')
return redirect(url_for('employees'))
@app.route('/api/employees/search')
@login_required
+111
View File
@@ -710,3 +710,114 @@ mark {
flex-direction: column;
}
}
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.6);
z-index: 9999;
display: none;
justify-content: center;
align-items: center;
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
.modal.show {
opacity: 1;
}
.modal-content {
background: #ffffff;
border-radius: 0.75rem;
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1),
0 10px 10px -5px rgba(0, 0, 0, 0.04);
max-width: 500px;
width: 90%;
max-height: 90vh;
overflow-y: auto;
transform: translateY(-20px);
transition: transform 0.3s ease-in-out;
}
.modal.show .modal-content {
transform: translateY(0);
}
.modal-header {
padding: 1.5rem 1.5rem 1rem;
border-bottom: 1px solid #e5e7eb;
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-header h3 {
margin: 0;
color: #dc2626;
font-size: 1.25rem;
font-weight: 600;
display: flex;
align-items: center;
gap: 0.5rem;
}
.modal-body {
padding: 1.5rem;
}
.modal-footer {
padding: 1rem 1.5rem;
border-top: 1px solid #e5e7eb;
display: flex;
justify-content: flex-end;
gap: 0.75rem;
}
.close-modal {
background: none;
border: none;
color: #6b7280;
cursor: pointer;
padding: 0.25rem;
border-radius: 0.375rem;
transition: all 0.2s ease-in-out;
}
.close-modal:hover {
color: #374151;
background: #f3f4f6;
}
.warning-text {
color: #dc2626;
font-size: 0.875rem;
margin-top: 0.75rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
/* Enhanced button styles for better interaction feedback */
.btn-danger:hover {
background-color: #b91c1c;
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(220, 38, 38, 0.3);
}
.delete-btn:hover {
background-color: #b91c1c !important;
transform: translateY(-1px);
box-shadow: 0 4px 8px rgba(220, 38, 38, 0.3);
}
/* Loading state for delete button */
.btn-danger:disabled {
background-color: #9ca3af;
cursor: not-allowed;
transform: none;
box-shadow: none;
}
+170 -113
View File
@@ -1,13 +1,11 @@
{% extends "base_authenticated.html" %}
{% set page_title = "Employee Management" %}
{% block title %}{{ page_title }}{% endblock %}
{% block extra_head %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/employees.css') }}">
{% endblock %}
{% block content %}
{% extends "base_authenticated.html" %} {% set page_title = "Employee
Management" %} {% block title %}{{ page_title }}{% endblock %} {% block
extra_head %}
<link
rel="stylesheet"
href="{{ url_for('static', filename='css/employees.css') }}"
/>
{% endblock %} {% block content %}
<div class="employees-page">
<!-- Page Header -->
<div class="employees-header">
@@ -91,12 +89,16 @@
placeholder="Search by name, employee ID, or job title..."
class="search-input"
autocomplete="off"
>
/>
<button type="submit" class="search-btn">
<i class="fas fa-search"></i>
</button>
{% if search %}
<a href="{{ url_for('employees') }}" class="clear-search-btn" title="Clear search">
<a
href="{{ url_for('employees') }}"
class="clear-search-btn"
title="Clear search"
>
<i class="fas fa-times"></i>
</a>
{% endif %}
@@ -108,17 +110,13 @@
<div class="employees-table-container">
<div class="table-header">
<h2>
{% if search %}
Search Results for "{{ search }}"
{% else %}
All Employees
{% endif %}
{% if search %} Search Results for "{{ search }}" {% else %} All
Employees {% endif %}
</h2>
<div class="table-info">
Showing {{ employees.items|length }} of {{ employees.total }} employees
{% if employees.pages > 1 %}
(Page {{ employees.page }} of {{ employees.pages }})
{% endif %}
{% if employees.pages > 1 %} (Page {{ employees.page }} of {{
employees.pages }}) {% endif %}
</div>
</div>
@@ -137,7 +135,9 @@
<tbody>
{% for employee in employees.items %}
<tr class="employee-row" data-employee-id="{{ employee.id }}">
<td class="row-number">{{ loop.index + (employees.page - 1) * employees.per_page }}</td>
<td class="row-number">
{{ loop.index + (employees.page - 1) * employees.per_page }}
</td>
<td class="employee-id">
<span class="id-badge">{{ employee.id }}</span>
@@ -157,9 +157,9 @@
<td class="employee-title">
{% if employee.title %}
<span class="title-badge">{{ employee.title }}</span>
<span class="title-badge">{{ employee.title }}</span>
{% else %}
<span class="no-title">No Title</span>
<span class="no-title">No Title</span>
{% endif %}
</td>
@@ -169,23 +169,29 @@
<td class="actions">
<div class="action-buttons">
<a href="{{ url_for('employee_detail', employee_index=employee.index) }}"
class="btn btn-sm btn-info"
title="View Details">
<a
href="{{ url_for('employee_detail', employee_index=employee.index) }}"
class="btn btn-sm btn-info"
title="View Details"
>
<i class="fas fa-eye"></i>
</a>
{% if session.role == 'admin' %}
<a href="{{ url_for('edit_employee', employee_index=employee.index) }}"
class="btn btn-sm btn-warning"
title="Edit Employee">
<a
href="{{ url_for('edit_employee', employee_index=employee.index) }}"
class="btn btn-sm btn-warning"
title="Edit Employee"
>
<i class="fas fa-edit"></i>
</a>
<button class="btn btn-sm btn-danger delete-btn"
data-employee-index="{{ employee.index }}"
data-employee-name="{{ employee.full_name }}"
title="Delete Employee">
<button
class="btn btn-sm btn-danger delete-btn"
data-employee-index="{{ employee.index }}"
data-employee-name="{{ employee.full_name }}"
title="Delete Employee"
>
<i class="fas fa-trash"></i>
</button>
{% endif %}
@@ -205,8 +211,10 @@
<!-- Previous Page -->
{% if employees.has_prev %}
<li>
<a href="{{ url_for('employees', page=employees.prev_num, search=search) }}"
class="pagination-link">
<a
href="{{ url_for('employees', page=employees.prev_num, search=search) }}"
class="pagination-link"
>
<i class="fas fa-chevron-left"></i>
Previous
</a>
@@ -214,32 +222,33 @@
{% endif %}
<!-- Page Numbers -->
{% for page_num in employees.iter_pages() %}
{% if page_num %}
{% if page_num != employees.page %}
<li>
<a href="{{ url_for('employees', page=page_num, search=search) }}"
class="pagination-link">
{{ page_num }}
</a>
</li>
{% else %}
<li>
<span class="pagination-link current">{{ page_num }}</span>
</li>
{% endif %}
{% else %}
<li>
<span class="pagination-link"></span>
</li>
{% endif %}
{% endfor %}
{% for page_num in employees.iter_pages() %} {% if page_num %} {% if
page_num != employees.page %}
<li>
<a
href="{{ url_for('employees', page=page_num, search=search) }}"
class="pagination-link"
>
{{ page_num }}
</a>
</li>
{% else %}
<li>
<span class="pagination-link current">{{ page_num }}</span>
</li>
{% endif %} {% else %}
<li>
<span class="pagination-link"></span>
</li>
{% endif %} {% endfor %}
<!-- Next Page -->
{% if employees.has_next %}
<li>
<a href="{{ url_for('employees', page=employees.next_num, search=search) }}"
class="pagination-link">
<a
href="{{ url_for('employees', page=employees.next_num, search=search) }}"
class="pagination-link"
>
Next
<i class="fas fa-chevron-right"></i>
</a>
@@ -257,18 +266,15 @@
<i class="fas fa-users-slash"></i>
</div>
<h3>
{% if search %}
No employees found for "{{ search }}"
{% else %}
No employees found
{% endif %}
{% if search %} No employees found for "{{ search }}" {% else %} No
employees found {% endif %}
</h3>
<p>
{% if search %}
Try adjusting your search terms or <a href="{{ url_for('employees') }}">view all employees</a>.
{% else %}
Get started by <a href="{{ url_for('create_employee') }}">adding your first employee</a>.
{% endif %}
{% if search %} Try adjusting your search terms or
<a href="{{ url_for('employees') }}">view all employees</a>. {% else %}
Get started by
<a href="{{ url_for('create_employee') }}">adding your first employee</a
>. {% endif %}
</p>
</div>
{% endif %}
@@ -285,15 +291,19 @@
</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete employee <strong id="deleteEmployeeName"></strong>?</p>
<p>
Are you sure you want to delete employee
<strong id="deleteEmployeeName"></strong>?
</p>
<p class="warning-text">
<i class="fas fa-warning"></i>
This action cannot be undone. The employee will be permanently removed from the system.
This action cannot be undone. The employee will be permanently removed
from the system.
</p>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" data-modal="deleteModal">Cancel</button>
<form id="deleteForm" method="POST" style="display: inline;">
<form id="deleteForm" method="POST" style="display: inline">
<button type="submit" class="btn btn-danger">
<i class="fas fa-trash"></i>
Delete Employee
@@ -302,73 +312,120 @@
</div>
</div>
</div>
{% endblock %}
{% block extra_scripts %}
{% endblock %} {% block extra_scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
document.addEventListener("DOMContentLoaded", function () {
console.log("🔄 Employee page JavaScript loaded");
// Delete button functionality
const deleteButtons = document.querySelectorAll('.delete-btn');
const deleteModal = document.getElementById('deleteModal');
const deleteForm = document.getElementById('deleteForm');
const deleteEmployeeName = document.getElementById('deleteEmployeeName');
const deleteButtons = document.querySelectorAll(".delete-btn");
const deleteModal = document.getElementById("deleteModal");
const deleteForm = document.getElementById("deleteForm");
const deleteEmployeeName = document.getElementById("deleteEmployeeName");
deleteButtons.forEach(button => {
button.addEventListener('click', function() {
const employeeIndex = this.getAttribute('data-employee-index');
const employeeName = this.getAttribute('data-employee-name');
console.log(`📊 Found ${deleteButtons.length} delete buttons`);
console.log("🔍 Delete modal:", deleteModal);
console.log("📝 Delete form:", deleteForm);
deleteEmployeeName.textContent = employeeName;
deleteForm.action = `/employees/${employeeIndex}/delete`;
deleteModal.style.display = 'flex';
});
deleteButtons.forEach((button) => {
button.addEventListener("click", function (event) {
event.preventDefault();
event.stopPropagation();
const employeeIndex = this.getAttribute("data-employee-index");
const employeeName = this.getAttribute("data-employee-name");
console.log(
`🗑️ Delete button clicked for employee: ${employeeName} (Index: ${employeeIndex})`
);
if (deleteEmployeeName) {
deleteEmployeeName.textContent = employeeName;
}
if (deleteForm) {
deleteForm.action = `/employees/${employeeIndex}/delete`;
console.log(`📋 Form action set to: ${deleteForm.action}`);
}
if (deleteModal) {
deleteModal.style.display = "flex";
deleteModal.style.visibility = "visible";
deleteModal.style.opacity = "1";
console.log("✅ Modal should be visible now");
}
});
});
// Modal close functionality
document.querySelectorAll('[data-modal]').forEach(element => {
element.addEventListener('click', function() {
const modalId = this.getAttribute('data-modal');
document.getElementById(modalId).style.display = 'none';
});
// Enhanced modal close functionality
document.querySelectorAll("[data-modal]").forEach((element) => {
element.addEventListener("click", function (event) {
event.preventDefault();
const modalId = this.getAttribute("data-modal");
const modal = document.getElementById(modalId);
if (modal) {
modal.style.display = "none";
modal.style.visibility = "hidden";
modal.style.opacity = "0";
console.log(`❌ Modal ${modalId} closed`);
}
});
});
// Close modal when clicking outside
deleteModal.addEventListener('click', function(e) {
if (deleteModal) {
deleteModal.addEventListener("click", function (e) {
if (e.target === this) {
this.style.display = 'none';
this.style.display = "none";
this.style.visibility = "hidden";
this.style.opacity = "0";
console.log("❌ Modal closed by clicking outside");
}
});
});
}
// Search form auto-submit with debouncing
const searchInput = document.querySelector('.search-input');
// Enhanced form submission logging
if (deleteForm) {
deleteForm.addEventListener("submit", function (event) {
console.log(`🚀 Form submitting to: ${this.action}`);
console.log("📊 Form method:", this.method);
});
}
// Search form auto-submit with debouncing (unchanged)
const searchInput = document.querySelector(".search-input");
let searchTimeout;
searchInput.addEventListener('input', function() {
if (searchInput) {
searchInput.addEventListener("input", function () {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
if (this.value.length >= 3 || this.value.length === 0) {
this.form.submit();
}
if (this.value.length >= 3 || this.value.length === 0) {
this.form.submit();
}
}, 500);
});
});
}
// Highlight search terms
// Highlight search terms (unchanged)
const searchTerm = "{{ search }}";
if (searchTerm) {
highlightSearchTerms(searchTerm);
highlightSearchTerms(searchTerm);
}
function highlightSearchTerms(term) {
const elements = document.querySelectorAll('.employee-name h4, .employee-name p, .employee-title .title-badge, .employee-id .id-badge');
const regex = new RegExp(`(${term})`, 'gi');
const elements = document.querySelectorAll(
".employee-name h4, .employee-name p, .employee-title .title-badge, .employee-id .id-badge"
);
const regex = new RegExp(`(${term})`, "gi");
elements.forEach(element => {
const text = element.textContent;
if (text.toLowerCase().includes(term.toLowerCase())) {
element.innerHTML = text.replace(regex, '<mark>$1</mark>');
}
});
elements.forEach((element) => {
const text = element.textContent;
if (text.toLowerCase().includes(term.toLowerCase())) {
element.innerHTML = text.replace(regex, "<mark>$1</mark>");
}
});
}
});
});
</script>
{% endblock %}