Fix edit employee button functionality

This commit is contained in:
2025-08-27 21:11:24 -04:00
parent 5d1b6abaae
commit 41b10a5a03
2 changed files with 398 additions and 348 deletions
+2 -8
View File
@@ -5820,12 +5820,6 @@ def edit_employee(employee_index):
last_name = request.form['last_name'].strip()
title = request.form.get('title', '').strip()
contract_id = request.form.get('contract_id', '1').strip()
stats = {
'total_employees': 0,
'employees_with_title': 0,
'unique_titles': 0,
'search_results': 0
}
# Validate required fields
if not all([employee_id, first_name, last_name]):
@@ -5844,7 +5838,7 @@ def edit_employee(employee_index):
existing_employee = Employee.query.filter_by(id=employee_id_int).first()
if existing_employee and existing_employee.index != employee.index:
flash(f'Employee with ID {employee_id} already exists.', 'error')
return render_template('edit_employee.html', employee=employee, stats=stats)
return render_template('edit_employee.html', employee=employee)
# Store original values for logging
original_data = {
@@ -5868,7 +5862,7 @@ def edit_employee(employee_index):
try:
logger_handler.logger.info(f"Admin user {session['username']} updated employee: {employee_index} - {first_name} {last_name}")
except Exception as log_error:
print(f"⚠️ Logging error (non-critical): {log_error}")
print(f"Warning: Logging error (non-critical): {log_error}")
flash(f'Employee "{first_name} {last_name}" updated successfully.', 'success')
return redirect(url_for('employees'))
+377 -321
View File
@@ -1,374 +1,430 @@
{% extends "base_authenticated.html" %}
{% set page_title = "Employee Management" %}
{% extends "base_authenticated.html" %} {% set page_title = "Edit Employee" %}
{% block title %}{{ page_title }}{% endblock %} {% block extra_head %}
<link
rel="stylesheet"
href="{{ url_for('static', filename='css/employees.css') }}"
/>
<style>
.form-container {
max-width: 600px;
margin: 0 auto;
background: #ffffff;
border-radius: 0.75rem;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
overflow: hidden;
}
{% block title %}{{ page_title }}{% endblock %}
.form-header {
background: #f8fafc;
padding: 1.5rem;
border-bottom: 1px solid #e2e8f0;
position: relative;
}
{% block extra_head %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/employees.css') }}">
{% endblock %}
.form-header::before {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(90deg, #f59e0b, #d97706);
}
{% block content %}
.form-header h2 {
display: flex;
align-items: center;
gap: 0.75rem;
font-size: 1.5rem;
font-weight: 600;
color: #0f172a;
margin: 0;
}
.form-header h2 i {
color: #f59e0b;
}
.employee-info {
background: #fef3c7;
border: 1px solid #fbbf24;
border-radius: 0.5rem;
padding: 1rem;
margin-top: 1rem;
}
.employee-info h3 {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 1rem;
font-weight: 600;
color: #92400e;
margin: 0 0 0.5rem 0;
}
.employee-info p {
color: #92400e;
font-size: 0.875rem;
margin: 0;
}
.form-body {
padding: 2rem;
}
.form-group {
margin-bottom: 1.5rem;
}
.form-group:last-child {
margin-bottom: 0;
}
.form-label {
display: block;
font-weight: 600;
color: #374151;
margin-bottom: 0.5rem;
font-size: 0.875rem;
}
.form-label.required::after {
content: " *";
color: #dc2626;
}
.form-input {
width: 100%;
padding: 0.75rem 1rem;
border: 2px solid #e2e8f0;
border-radius: 0.5rem;
font-size: 1rem;
transition: border-color 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
background: #ffffff;
}
.form-input:focus {
outline: none;
border-color: #f59e0b;
box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.1);
}
.form-input.error {
border-color: #dc2626;
}
.form-help {
font-size: 0.875rem;
color: #6b7280;
margin-top: 0.25rem;
}
.form-actions {
display: flex;
gap: 1rem;
justify-content: flex-end;
padding-top: 1.5rem;
border-top: 1px solid #e2e8f0;
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
@media (max-width: 640px) {
.form-row {
grid-template-columns: 1fr;
}
.form-actions {
flex-direction: column;
}
}
</style>
{% endblock %} {% block content %}
<div class="employees-page">
<!-- Page Header -->
<div class="employees-header">
<div class="header-content">
<div class="header-navigation">
<a href="{{ url_for('dashboard') }}" class="back-button">
<a href="{{ url_for('employees') }}" class="back-button">
<i class="fas fa-arrow-left"></i>
Back to Dashboard
Back to Employees
</a>
</div>
<h1><i class="fas fa-users"></i> Employee Management</h1>
<h1><i class="fas fa-user-edit"></i> Edit Employee</h1>
<p class="header-description">
Manage employee records and view attendance statistics
Update employee information in the system
</p>
</div>
</div>
<div class="header-actions">
{% if session.user_role == 'admin' %}
<a href="{{ url_for('create_employee') }}" class="btn btn-primary">
<i class="fas fa-plus"></i>
Add Employee
</a>
{% endif %}
<!-- Form Container -->
<div class="form-container">
<div class="form-header">
<h2>
<i class="fas fa-user-edit"></i>
Employee Information
</h2>
<div class="employee-info">
<h3>
<i class="fas fa-info-circle"></i>
Current Employee
</h3>
<p><strong>{{ employee.full_name }}</strong> (ID: {{ employee.id }})</p>
</div>
</div>
<!-- Statistics Cards -->
<div class="stats-grid">
<div class="stat-card">
<div class="stat-icon">
<i class="fas fa-users"></i>
<div class="form-body">
<form method="POST" id="editEmployeeForm">
<!-- Employee ID and Contract ID Row -->
<div class="form-row">
<div class="form-group">
<label for="employee_id" class="form-label required"
>Employee ID</label
>
<input
type="number"
id="employee_id"
name="employee_id"
class="form-input"
required
min="1"
placeholder="Enter unique employee ID"
value="{{ request.form.get('employee_id', employee.id) }}"
/>
<div class="form-help">Must be a unique numeric identifier</div>
</div>
<div class="stat-info">
<h3>{{ stats.total_employees }}</h3>
<p>Total Employees</p>
<div class="form-group">
<label for="contract_id" class="form-label">Contract ID</label>
<input
type="number"
id="contract_id"
name="contract_id"
class="form-input"
min="1"
value="{{ request.form.get('contract_id', employee.contractId) }}"
placeholder="Enter contract ID"
/>
<div class="form-help">Default is 1 if not specified</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon">
<i class="fas fa-id-badge"></i>
</div>
<div class="stat-info">
<h3>{{ stats.employees_with_title }}</h3>
<p>With Job Titles</p>
</div>
</div>
<div class="stat-card">
<div class="stat-icon">
<i class="fas fa-briefcase"></i>
</div>
<div class="stat-info">
<h3>{{ stats.unique_titles }}</h3>
<p>Unique Job Titles</p>
</div>
</div>
{% if search %}
<div class="stat-card search-results">
<div class="stat-icon">
<i class="fas fa-search"></i>
</div>
<div class="stat-info">
<h3>{{ stats.search_results }}</h3>
<p>Search Results</p>
</div>
</div>
{% endif %}
</div>
<!-- Search and Filter Section -->
<div class="search-section">
<form method="GET" class="search-form">
<div class="search-input-group">
<!-- First Name and Last Name Row -->
<div class="form-row">
<div class="form-group">
<label for="first_name" class="form-label required"
>First Name</label
>
<input
type="text"
name="search"
value="{{ search }}"
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">
id="first_name"
name="first_name"
class="form-input"
required
maxlength="50"
placeholder="Enter first name"
value="{{ request.form.get('first_name', employee.firstName) }}"
/>
</div>
<div class="form-group">
<label for="last_name" class="form-label required">Last Name</label>
<input
type="text"
id="last_name"
name="last_name"
class="form-input"
required
maxlength="50"
placeholder="Enter last name"
value="{{ request.form.get('last_name', employee.lastName) }}"
/>
</div>
</div>
<!-- Job Title -->
<div class="form-group">
<label for="title" class="form-label">Job Title</label>
<input
type="text"
id="title"
name="title"
class="form-input"
maxlength="20"
placeholder="Enter job title (optional)"
value="{{ request.form.get('title', employee.title or '') }}"
/>
<div class="form-help">Optional field, maximum 20 characters</div>
</div>
<!-- Form Actions -->
<div class="form-actions">
<a href="{{ url_for('employees') }}" class="btn btn-secondary">
<i class="fas fa-times"></i>
Cancel
</a>
{% endif %}
</div>
</form>
</div>
<!-- Employee Table -->
<div class="employees-table-container">
<div class="table-header">
<h2>
{% 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 %}
</div>
</div>
<div class="table-responsive">
<table class="employees-table">
<thead>
<tr>
<th>#</th>
<th>Employee ID</th>
<th>Name</th>
<th>Job Title</th>
<th>Contract ID</th>
<th>Actions</th>
</tr>
</thead>
<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="employee-id">
<span class="id-badge">{{ employee.id }}</span>
</td>
<td class="employee-name">
<div class="name-container">
<div class="avatar">
<i class="fas fa-user-circle"></i>
</div>
<div class="name-details">
<h4>{{ employee.full_name }}</h4>
<p>{{ employee.firstName }} {{ employee.lastName }}</p>
</div>
</div>
</td>
<td class="employee-title">
{% if employee.title %}
<span class="title-badge">{{ employee.title }}</span>
{% else %}
<span class="no-title">No Title</span>
{% endif %}
</td>
<td class="contract-id">
<span class="contract-badge">{{ employee.contractId }}</span>
</td>
<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">
<i class="fas fa-eye"></i>
</a>
{% if session.user_role == 'admin' %}
<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">
<i class="fas fa-trash"></i>
</button>
{% endif %}
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- Pagination -->
{% if employees.pages > 1 %}
<div class="pagination-container">
<nav class="pagination-nav">
<ul class="pagination">
<!-- Previous Page -->
{% if employees.has_prev %}
<li>
<a href="{{ url_for('employees', page=employees.prev_num, search=search) }}"
class="pagination-link">
<i class="fas fa-chevron-left"></i>
Previous
</a>
</li>
{% 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 %}
<!-- Next Page -->
{% if employees.has_next %}
<li>
<a href="{{ url_for('employees', page=employees.next_num, search=search) }}"
class="pagination-link">
Next
<i class="fas fa-chevron-right"></i>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>
{% endif %}
<!-- Empty State -->
{% if employees.total == 0 %}
<div class="empty-state">
<div class="empty-icon">
<i class="fas fa-users-slash"></i>
</div>
<h3>
{% 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 %}
</p>
</div>
{% endif %}
</div>
</div>
<!-- Delete Confirmation Modal -->
<div id="deleteModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h3><i class="fas fa-exclamation-triangle"></i> Confirm Deletion</h3>
<button class="close-modal" data-modal="deleteModal">
<i class="fas fa-times"></i>
<button type="submit" class="btn btn-warning">
<i class="fas fa-save"></i>
Update Employee
</button>
</div>
<div class="modal-body">
<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.
</p>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" data-modal="deleteModal">Cancel</button>
<form id="deleteForm" method="POST" style="display: inline;">
<button type="submit" class="btn btn-danger">
<i class="fas fa-trash"></i>
Delete Employee
</button>
</form>
</div>
</div>
</div>
{% endblock %}
{% block extra_scripts %}
{% endblock %} {% block extra_scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
// Delete button functionality
const deleteButtons = document.querySelectorAll('.delete-btn');
const deleteModal = document.getElementById('deleteModal');
const deleteForm = document.getElementById('deleteForm');
const deleteEmployeeName = document.getElementById('deleteEmployeeName');
document.addEventListener("DOMContentLoaded", function () {
const form = document.getElementById("editEmployeeForm");
const employeeIdInput = document.getElementById("employee_id");
const firstNameInput = document.getElementById("first_name");
const lastNameInput = document.getElementById("last_name");
deleteButtons.forEach(button => {
button.addEventListener('click', function() {
const employeeIndex = this.getAttribute('data-employee-index');
const employeeName = this.getAttribute('data-employee-name');
// Store original values for change detection
const originalValues = {
employee_id: employeeIdInput.value,
first_name: firstNameInput.value,
last_name: lastNameInput.value,
title: document.getElementById("title").value,
contract_id: document.getElementById("contract_id").value,
};
deleteEmployeeName.textContent = employeeName;
deleteForm.action = `/employees/${employeeIndex}/delete`;
deleteModal.style.display = 'flex';
});
// Form validation
form.addEventListener("submit", function (e) {
let isValid = true;
// Clear previous error states
document.querySelectorAll(".form-input").forEach((input) => {
input.classList.remove("error");
});
// 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';
});
});
// Validate Employee ID
if (!employeeIdInput.value.trim()) {
employeeIdInput.classList.add("error");
isValid = false;
}
// Close modal when clicking outside
deleteModal.addEventListener('click', function(e) {
if (e.target === this) {
this.style.display = 'none';
// Validate First Name
if (!firstNameInput.value.trim()) {
firstNameInput.classList.add("error");
isValid = false;
}
// Validate Last Name
if (!lastNameInput.value.trim()) {
lastNameInput.classList.add("error");
isValid = false;
}
if (!isValid) {
e.preventDefault();
alert("Please fill in all required fields.");
return;
}
// Check if any changes were made
const currentValues = {
employee_id: employeeIdInput.value,
first_name: firstNameInput.value,
last_name: lastNameInput.value,
title: document.getElementById("title").value,
contract_id: document.getElementById("contract_id").value,
};
let hasChanges = false;
for (let key in originalValues) {
if (originalValues[key] !== currentValues[key]) {
hasChanges = true;
break;
}
}
if (!hasChanges) {
e.preventDefault();
alert(
"No changes detected. Please modify at least one field to update the employee."
);
return;
}
// Confirm update if employee ID changed
if (originalValues.employee_id !== currentValues.employee_id) {
if (
!confirm(
`You are changing the Employee ID from ${originalValues.employee_id} to ${currentValues.employee_id}. This may affect attendance records. Are you sure?`
)
) {
e.preventDefault();
return;
}
}
});
// Search form auto-submit with debouncing
const searchInput = document.querySelector('.search-input');
let searchTimeout;
searchInput.addEventListener('input', function() {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
if (this.value.length >= 3 || this.value.length === 0) {
this.form.submit();
// Auto-capitalize names
[firstNameInput, lastNameInput].forEach((input) => {
input.addEventListener("input", function () {
const words = this.value.split(" ");
const capitalizedWords = words.map((word) => {
if (word.length > 0) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}
}, 500);
return word;
});
this.value = capitalizedWords.join(" ");
});
});
// Highlight search terms
const searchTerm = "{{ search }}";
if (searchTerm) {
highlightSearchTerms(searchTerm);
// Employee ID validation
employeeIdInput.addEventListener("input", function () {
// Remove any non-numeric characters
this.value = this.value.replace(/[^0-9]/g, "");
// Remove leading zeros
if (this.value.length > 1) {
this.value = this.value.replace(/^0+/, "");
}
});
// Contract ID validation
const contractIdInput = document.getElementById("contract_id");
contractIdInput.addEventListener("input", function () {
// Remove any non-numeric characters
this.value = this.value.replace(/[^0-9]/g, "");
// Set default value if empty
if (!this.value) {
this.value = "1";
}
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');
// Remove leading zeros
if (this.value.length > 1) {
this.value = this.value.replace(/^0+/, "");
}
});
elements.forEach(element => {
const text = element.textContent;
if (text.toLowerCase().includes(term.toLowerCase())) {
element.innerHTML = text.replace(regex, '<mark>$1</mark>');
// Highlight changed fields
function highlightChanges() {
Object.keys(originalValues).forEach((key) => {
const input = document.getElementById(key);
if (input && input.value !== originalValues[key]) {
input.style.borderLeft = "4px solid #f59e0b";
} else if (input) {
input.style.borderLeft = "";
}
});
}
});
// Add change detection
document.querySelectorAll(".form-input").forEach((input) => {
input.addEventListener("input", highlightChanges);
});
});
</script>
{% endblock %}