Updated attendance report page, new button to add record manually

This commit is contained in:
2025-12-31 12:27:10 -05:00
parent bcc8340b69
commit ca06908d14
3 changed files with 696 additions and 0 deletions
+221
View File
@@ -5266,6 +5266,227 @@ def edit_attendance(record_id):
flash('Error updating attendance record. Please try again.', 'error')
return redirect(url_for('attendance_report'))
@app.route('/attendance/add', methods=['GET'])
@login_required
@log_user_activity('manual_attendance_access')
def add_manual_attendance():
"""
Display form to manually add attendance record
Only accessible by admin and accounting roles
"""
try:
user_role = session.get('role')
# Check authorization
if user_role not in ['admin', 'accounting']:
flash('You do not have permission to manually add attendance records.', 'error')
return redirect(url_for('attendance_report'))
# Get all active projects
projects = Project.query.filter_by(active_status=True).order_by(Project.name).all()
# Get today's date for form
today_date = datetime.now().strftime('%Y-%m-%d')
logger_handler.logger.info(
f"User {session.get('username')} ({user_role}) accessed manual attendance entry form"
)
return render_template('add_manual_attendance.html',
projects=projects,
today_date=today_date)
except Exception as e:
logger_handler.logger.error(f"Error loading manual attendance form: {e}")
flash('Error loading form. Please try again.', 'error')
return redirect(url_for('attendance_report'))
@app.route('/attendance/save_manual', methods=['POST'])
@login_required
@log_user_activity('manual_attendance_creation')
@log_database_operations('manual_attendance_insert')
def save_manual_attendance():
"""
Save manually created attendance record
Only accessible by admin and accounting roles
"""
try:
user_role = session.get('role')
# Check authorization
if user_role not in ['admin', 'accounting']:
return jsonify({
'success': False,
'message': 'You do not have permission to manually add attendance records.'
}), 403
# Get form data
employee_id = request.form.get('employee_id', '').strip()
location_id = request.form.get('location_id', '').strip()
check_date = request.form.get('check_date', '').strip()
check_time = request.form.get('check_time', '').strip()
# Validate required fields
if not all([employee_id, location_id, check_date, check_time]):
flash('All fields are required.', 'error')
return redirect(url_for('add_manual_attendance'))
# Validate employee exists
employee = Employee.query.filter_by(id=int(employee_id)).first()
if not employee:
flash(f'Employee with ID {employee_id} not found.', 'error')
return redirect(url_for('add_manual_attendance'))
# Get QR code (location)
qr_code = QRCode.query.get(int(location_id))
if not qr_code:
flash('Selected location not found.', 'error')
return redirect(url_for('add_manual_attendance'))
# Parse date and time
try:
check_date_obj = datetime.strptime(check_date, '%Y-%m-%d').date()
check_time_obj = datetime.strptime(check_time, '%H:%M').time()
except ValueError as e:
flash('Invalid date or time format.', 'error')
logger_handler.logger.error(f"Date/time parsing error: {e}")
return redirect(url_for('add_manual_attendance'))
# Check if record already exists for this employee, location, date, and time
existing_record = AttendanceData.query.filter_by(
employee_id=str(employee_id),
qr_code_id=qr_code.id,
check_in_date=check_date_obj,
check_in_time=check_time_obj
).first()
if existing_record:
flash('An attendance record already exists for this employee at this location, date, and time.', 'warning')
return redirect(url_for('add_manual_attendance'))
# Create new attendance record
# Use QR code's location address for both QR address and check-in address
# Set fixed distance of 0.010 miles
new_attendance = AttendanceData(
qr_code_id=qr_code.id,
employee_id=str(employee_id),
check_in_date=check_date_obj,
check_in_time=check_time_obj,
location_name=qr_code.location,
# Use QR code's coordinates
latitude=qr_code.address_latitude,
longitude=qr_code.address_longitude,
# Use QR code's address for both
address=qr_code.location_address,
# Set fixed distance
location_accuracy=0.010,
accuracy=0.010,
# Mark as manual entry
location_source='manual_entry',
device_info='Manual Entry by Admin/Accounting',
user_agent=f'Manual Entry - User: {session.get("username")}',
ip_address=get_client_ip(),
status='present',
verification_required=False,
verification_status='approved',
created_timestamp=datetime.utcnow(),
updated_timestamp=datetime.utcnow()
)
db.session.add(new_attendance)
db.session.commit()
# Log the manual entry
logger_handler.logger.info(
f"Manual attendance record created by {session.get('username')} ({user_role}): "
f"Employee {employee.firstName} {employee.lastName} (ID: {employee_id}), "
f"Location: {qr_code.location}, Event: {qr_code.location_event}, "
f"Date: {check_date}, Time: {check_time}"
)
flash(f'Attendance record successfully created for {employee.firstName} {employee.lastName}.', 'success')
return redirect(url_for('attendance_report'))
except Exception as e:
db.session.rollback()
logger_handler.logger.error(f"Error saving manual attendance record: {e}")
logger_handler.logger.error(f"Traceback: {traceback.format_exc()}")
flash('Error saving attendance record. Please try again.', 'error')
return redirect(url_for('add_manual_attendance'))
@app.route('/api/search_employees')
@login_required
def search_employees_api():
"""
API endpoint to search employees by name or ID
Returns JSON with employee list
"""
try:
search_query = request.args.get('q', '').strip()
if not search_query or len(search_query) < 2:
return jsonify({'employees': []})
# Search by ID or name
search_pattern = f"%{search_query}%"
employees = Employee.query.filter(
db.or_(
Employee.id.like(search_pattern),
Employee.firstName.like(search_pattern),
Employee.lastName.like(search_pattern),
db.func.concat(Employee.firstName, ' ', Employee.lastName).like(search_pattern)
)
).limit(10).all()
employee_list = [{
'id': emp.id,
'firstName': emp.firstName,
'lastName': emp.lastName,
'full_name': f"{emp.firstName} {emp.lastName}"
} for emp in employees]
return jsonify({'employees': employee_list})
except Exception as e:
logger_handler.logger.error(f"Error searching employees: {e}")
return jsonify({'employees': [], 'error': str(e)}), 500
@app.route('/api/get_project_locations')
@login_required
def get_project_locations_api():
"""
API endpoint to get locations for a specific project
Returns JSON with location list
"""
try:
project_id = request.args.get('project_id', '').strip()
if not project_id:
return jsonify({'success': False, 'locations': [], 'error': 'Project ID required'})
# Get active QR codes for this project
qr_codes = QRCode.query.filter_by(
project_id=int(project_id),
active_status=True
).order_by(QRCode.location).all()
location_list = [{
'id': qr.id,
'location': qr.location,
'location_address': qr.location_address,
'location_event': qr.location_event
} for qr in qr_codes]
return jsonify({'success': True, 'locations': location_list})
except Exception as e:
logger_handler.logger.error(f"Error getting project locations: {e}")
return jsonify({'success': False, 'locations': [], 'error': str(e)}), 500
@app.route('/attendance/<int:record_id>/delete', methods=['POST'])
@login_required
@log_database_operations('attendance_delete')
+466
View File
@@ -0,0 +1,466 @@
{% extends "base_authenticated.html" %}
{% block title %}Add Manual Attendance Record - QR Code Management{% endblock %}
{% block extra_head %}
<style>
.manual-attendance-container {
max-width: 800px;
margin: 2rem auto;
padding: 2rem;
}
.form-card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
padding: 2rem;
}
.form-header {
margin-bottom: 2rem;
padding-bottom: 1rem;
border-bottom: 2px solid #e0e0e0;
}
.form-header h1 {
margin: 0 0 0.5rem 0;
color: #333;
font-size: 1.75rem;
}
.form-header p {
margin: 0;
color: #666;
}
.form-group {
margin-bottom: 1.5rem;
}
.form-group label {
display: block;
margin-bottom: 0.5rem;
font-weight: 600;
color: #333;
}
.form-group label .required {
color: #dc3545;
}
.form-control {
width: 100%;
padding: 0.75rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
transition: border-color 0.3s;
}
.form-control:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
}
.form-control:disabled {
background-color: #f5f5f5;
cursor: not-allowed;
}
.autocomplete-container {
position: relative;
}
.autocomplete-results {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: white;
border: 1px solid #ddd;
border-top: none;
border-radius: 0 0 4px 4px;
max-height: 200px;
overflow-y: auto;
z-index: 1000;
display: none;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.autocomplete-results.show {
display: block;
}
.autocomplete-item {
padding: 0.75rem;
cursor: pointer;
border-bottom: 1px solid #f0f0f0;
}
.autocomplete-item:hover {
background-color: #f8f9fa;
}
.autocomplete-item:last-child {
border-bottom: none;
}
.employee-info {
display: flex;
justify-content: space-between;
}
.employee-name {
font-weight: 600;
color: #333;
}
.employee-id {
color: #666;
font-size: 0.9rem;
}
.form-actions {
display: flex;
gap: 1rem;
justify-content: flex-end;
margin-top: 2rem;
padding-top: 1rem;
border-top: 1px solid #e0e0e0;
}
.btn {
padding: 0.75rem 1.5rem;
border: none;
border-radius: 4px;
font-size: 1rem;
cursor: pointer;
transition: all 0.3s;
text-decoration: none;
display: inline-block;
}
.btn-primary {
background-color: #007bff;
color: white;
}
.btn-primary:hover {
background-color: #0056b3;
}
.btn-secondary {
background-color: #6c757d;
color: white;
}
.btn-secondary:hover {
background-color: #545b62;
}
.btn i {
margin-right: 0.5rem;
}
.loading-spinner {
display: none;
text-align: center;
padding: 1rem;
color: #007bff;
}
.loading-spinner.show {
display: block;
}
.alert {
padding: 1rem;
border-radius: 4px;
margin-bottom: 1rem;
}
.alert-info {
background-color: #d1ecf1;
border: 1px solid #bee5eb;
color: #0c5460;
}
.help-text {
font-size: 0.875rem;
color: #666;
margin-top: 0.25rem;
}
</style>
{% endblock %}
{% block content %}
<div class="manual-attendance-container">
<div class="form-card">
<div class="form-header">
<h1>
<i class="fas fa-user-plus"></i>
Add Manual Attendance Record
</h1>
<p>Create a new attendance record manually for employees who couldn't check in via QR code</p>
</div>
<div class="alert alert-info">
<i class="fas fa-info-circle"></i>
The system will automatically use the QR code's location address for both QR Address and Check-in Address,
with a fixed distance of 0.010 miles.
</div>
<form id="manualAttendanceForm" method="POST" action="{{ url_for('save_manual_attendance') }}">
<!-- Employee Selection with Autocomplete -->
<div class="form-group">
<label for="employee_search">
Employee <span class="required">*</span>
</label>
<div class="autocomplete-container">
<input
type="text"
id="employee_search"
class="form-control"
placeholder="Search by employee name or ID..."
autocomplete="off"
required
>
<input type="hidden" id="employee_id" name="employee_id" required>
<div id="autocomplete_results" class="autocomplete-results"></div>
</div>
<div class="help-text">Start typing to search for employees by name or ID</div>
</div>
<!-- Project Selection -->
<div class="form-group">
<label for="project_id">
Project <span class="required">*</span>
</label>
<select id="project_id" name="project_id" class="form-control" required>
<option value="">-- Select Project --</option>
{% for project in projects %}
<option value="{{ project.id }}">{{ project.name }}</option>
{% endfor %}
</select>
<div class="help-text">Select the project associated with this attendance record</div>
</div>
<!-- Location Selection -->
<div class="form-group">
<label for="location_id">
Location <span class="required">*</span>
</label>
<select id="location_id" name="location_id" class="form-control" required disabled>
<option value="">-- Select Project First --</option>
</select>
<div class="help-text">Locations will be loaded based on the selected project</div>
<div id="location_loading" class="loading-spinner">
<i class="fas fa-spinner fa-spin"></i> Loading locations...
</div>
</div>
<!-- Event Type Selection -->
<div class="form-group">
<label for="event_type">
Event Type <span class="required">*</span>
</label>
<select id="event_type" name="event_type" class="form-control" required disabled>
<option value="">-- Select Location First --</option>
</select>
<div class="help-text">Select whether this is a check-in or check-out event</div>
</div>
<!-- Date and Time -->
<div class="form-group">
<label for="check_date">
Date <span class="required">*</span>
</label>
<input
type="date"
id="check_date"
name="check_date"
class="form-control"
max="{{ today_date }}"
required
>
<div class="help-text">The date of the attendance record</div>
</div>
<div class="form-group">
<label for="check_time">
Time <span class="required">*</span>
</label>
<input
type="time"
id="check_time"
name="check_time"
class="form-control"
required
>
<div class="help-text">The time of the attendance record</div>
</div>
<!-- Form Actions -->
<div class="form-actions">
<a href="{{ url_for('attendance_report') }}" class="btn btn-secondary">
<i class="fas fa-times"></i>
Cancel
</a>
<button type="submit" class="btn btn-primary" id="submitBtn">
<i class="fas fa-save"></i>
Save Record
</button>
</div>
</form>
</div>
</div>
<script>
// Employee autocomplete functionality
const employeeSearch = document.getElementById('employee_search');
const employeeIdHidden = document.getElementById('employee_id');
const autocompleteResults = document.getElementById('autocomplete_results');
let searchTimeout;
employeeSearch.addEventListener('input', function() {
const searchTerm = this.value.trim();
if (searchTerm.length < 2) {
autocompleteResults.classList.remove('show');
return;
}
// Debounce search
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
fetch(`/api/search_employees?q=${encodeURIComponent(searchTerm)}`)
.then(response => response.json())
.then(data => {
displayAutocompleteResults(data.employees);
})
.catch(error => {
console.error('Error searching employees:', error);
});
}, 300);
});
function displayAutocompleteResults(employees) {
if (employees.length === 0) {
autocompleteResults.innerHTML = '<div class="autocomplete-item">No employees found</div>';
autocompleteResults.classList.add('show');
return;
}
const html = employees.map(emp => `
<div class="autocomplete-item" onclick="selectEmployee(${emp.id}, '${emp.firstName} ${emp.lastName}')">
<div class="employee-info">
<span class="employee-name">${emp.lastName}, ${emp.firstName}</span>
<span class="employee-id">ID: ${emp.id}</span>
</div>
</div>
`).join('');
autocompleteResults.innerHTML = html;
autocompleteResults.classList.add('show');
}
function selectEmployee(id, name) {
employeeIdHidden.value = id;
employeeSearch.value = name;
autocompleteResults.classList.remove('show');
}
// Close autocomplete when clicking outside
document.addEventListener('click', function(e) {
if (!e.target.closest('.autocomplete-container')) {
autocompleteResults.classList.remove('show');
}
});
// Project selection - load locations
const projectSelect = document.getElementById('project_id');
const locationSelect = document.getElementById('location_id');
const eventTypeSelect = document.getElementById('event_type');
const locationLoading = document.getElementById('location_loading');
projectSelect.addEventListener('change', function() {
const projectId = this.value;
// Reset location and event type
locationSelect.innerHTML = '<option value="">-- Select Location --</option>';
locationSelect.disabled = true;
eventTypeSelect.innerHTML = '<option value="">-- Select Location First --</option>';
eventTypeSelect.disabled = true;
if (!projectId) {
locationSelect.innerHTML = '<option value="">-- Select Project First --</option>';
return;
}
// Load locations for the selected project
locationLoading.classList.add('show');
fetch(`/api/get_project_locations?project_id=${projectId}`)
.then(response => response.json())
.then(data => {
locationLoading.classList.remove('show');
if (data.success && data.locations.length > 0) {
locationSelect.disabled = false;
data.locations.forEach(loc => {
const option = document.createElement('option');
option.value = loc.id;
option.textContent = `${loc.location} - ${loc.location_address}`;
option.dataset.event = loc.location_event;
locationSelect.appendChild(option);
});
} else {
locationSelect.innerHTML = '<option value="">No active locations found for this project</option>';
}
})
.catch(error => {
locationLoading.classList.remove('show');
console.error('Error loading locations:', error);
alert('Error loading locations. Please try again.');
});
});
// Location selection - set event type
locationSelect.addEventListener('change', function() {
const selectedOption = this.options[this.selectedIndex];
const eventType = selectedOption.dataset.event;
eventTypeSelect.innerHTML = '';
eventTypeSelect.disabled = false;
if (eventType) {
const option = document.createElement('option');
option.value = eventType;
option.textContent = eventType;
option.selected = true;
eventTypeSelect.appendChild(option);
} else {
eventTypeSelect.innerHTML = '<option value="">Event type not available</option>';
}
});
// Set default date to today
document.getElementById('check_date').valueAsDate = new Date();
// Set default time to current time
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
document.getElementById('check_time').value = `${hours}:${minutes}`;
// Form submission
document.getElementById('manualAttendanceForm').addEventListener('submit', function(e) {
const submitBtn = document.getElementById('submitBtn');
submitBtn.disabled = true;
submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
});
</script>
{% endblock %}
+9
View File
@@ -38,6 +38,15 @@
Export Data
</button>
{% endif %}
<!-- NEW: Manual Add Record Button -->
{% if session.role in ['admin', 'accounting'] %}
<button onclick="window.location.href='{{ url_for('add_manual_attendance') }}'" class="btn btn-primary">
<i class="fas fa-plus-circle"></i>
Add Record
</button>
{% endif %}
<button onclick="refreshReport()" class="btn btn-secondary">
<i class="fas fa-sync-alt"></i>
Refresh