Files
LT_QR_Codes_Management/templates/qr_destination.html
T

2256 lines
72 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{ qr_code.location_event }}</title>
<link
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
rel="stylesheet"
/>
<style>
/* Enhanced CSS Variables with Orange Color Scheme */
:root {
--primary-color: #2563eb;
--primary-hover: #1d4ed8;
--orange-color: #ea580c;
--orange-hover: #dc2626;
--success-color: #10b981;
--warning-color: #f59e0b;
--error-color: #ef4444;
--text-primary: #1f2937;
--text-secondary: #6b7280;
--background-light: #f8fafc;
--border-color: #e5e7eb;
--shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
--border-radius: 0.5rem;
--transition: all 0.2s ease-in-out;
/* Language Color Coding - High Contrast Theme */
--english-color: #1e40af;
--english-bg: rgba(59, 130, 246, 0.1);
--spanish-color: #15803d;
--spanish-bg: rgba(34, 197, 94, 0.1);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Language Color Classes - Enhanced Contrast */
.english-text {
color: #1e40af !important;
font-weight: 700;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
.spanish-text {
color: #15803d !important;
font-weight: 700;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
/* Check-out reminder shown under the Type of Work dropdown */
.work-type-hint {
margin-top: 8px;
padding: 10px 12px;
border-radius: 8px;
background: rgba(245, 158, 11, 0.12);
border: 1px solid rgba(245, 158, 11, 0.45);
font-size: 0.9rem;
line-height: 1.45;
}
.work-type-hint i {
color: #b45309;
margin-right: 6px;
}
.bilingual-container {
background: rgba(255, 255, 255, 0.98);
border-radius: 8px;
padding: 16px 20px;
margin: 8px 0;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.8);
}
.language-separator {
color: #64748b;
font-weight: 500;
margin: 0 12px;
font-size: 1.1em;
}
/* Dynamic Background Based on Location Event */
body {
font-family: "Inter", -apple-system, BlinkMacSystemFont, sans-serif;
min-height: 100vh;
padding: 1rem;
color: var(--text-primary);
line-height: 1.6;
transition: var(--transition);
}
/* Check In Event - Blue Background (Default) */
body.check-in {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
/* Check Out Event - Orange Background */
body.check-out {
background: linear-gradient(135deg, #ff7849 0%, #ff4757 100%);
}
.destination-container {
max-width: 500px;
margin: 0 auto;
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.language-selector {
display: flex;
justify-content: flex-end;
margin-bottom: 1rem;
}
.language-toggle {
background: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: var(--border-radius);
color: white;
padding: 0.5rem 1rem;
cursor: pointer;
transition: var(--transition);
backdrop-filter: blur(10px);
font-size: 0.9rem;
font-weight: 600;
display: flex;
align-items: center;
gap: 0.5rem;
outline: none;
}
.language-toggle:hover {
background: rgba(255, 255, 255, 0.3) !important;
border-color: rgba(255, 255, 255, 0.5) !important;
transform: translateY(-1px);
}
.language-toggle:active {
background: rgba(255, 255, 255, 0.4) !important;
transform: translateY(0);
}
.language-toggle:focus {
box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.3) !important;
}
.language-toggle i {
font-size: 1rem;
color: white !important;
}
.destination-header {
background: rgba(255, 255, 255, 0.95);
border-radius: var(--border-radius);
padding: 2rem;
text-align: center;
box-shadow: var(--shadow-lg);
backdrop-filter: blur(10px);
opacity: 0;
transform: translateY(20px);
transition: all 0.6s ease-out;
}
.destination-header.active {
opacity: 1;
transform: translateY(0);
}
/* Dynamic Header Icon Colors */
.header-icon {
width: 80px;
height: 80px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto 1.5rem;
box-shadow: var(--shadow-lg);
transition: var(--transition);
}
/* Check In - Blue Icon */
.check-in .header-icon {
background: linear-gradient(
135deg,
var(--primary-color),
var(--primary-hover)
);
}
/* Check Out - Orange Icon */
.check-out .header-icon {
background: linear-gradient(
135deg,
var(--orange-color),
var(--orange-hover)
);
}
.header-icon i {
font-size: 2.5rem;
color: white;
}
/* Company Logo Styling */
.company-logo {
width: 100%;
height: 100%;
object-fit: contain;
border-radius: 8px;
}
.fallback-icon {
font-size: 2.5rem;
color: white;
}
.destination-header h1 {
font-size: 1.75rem;
font-weight: 700;
color: var(--text-primary);
margin-bottom: 0.5rem;
line-height: 1.2;
}
.location-info {
color: var(--text-secondary);
font-size: 1rem;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
}
/* Dynamic Location Info Icon Colors */
.check-in .location-info i {
color: var(--primary-color);
}
.check-out .location-info i {
color: var(--orange-color);
}
.checkin-card {
background: rgba(255, 255, 255, 0.95);
border-radius: var(--border-radius);
padding: 2rem;
box-shadow: var(--shadow-lg);
backdrop-filter: blur(10px);
opacity: 0;
transform: translateY(20px);
transition: all 0.6s ease-out 0.2s;
}
.checkin-card.active {
opacity: 1;
transform: translateY(0);
}
.checkin-header {
text-align: center;
margin-bottom: 2rem;
}
.checkin-header h2 {
font-size: 1.5rem;
font-weight: 600;
color: var(--text-primary);
margin-bottom: 0.5rem;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
}
/* Dynamic Header Icon Colors */
.check-in .checkin-header h2 i {
color: var(--primary-color);
}
.check-out .checkin-header h2 i {
color: var(--orange-color);
}
.checkin-header p {
color: var(--text-secondary);
font-size: 0.95rem;
line-height: 1.5;
}
.form-group {
margin-bottom: 1.5rem;
}
.form-group label {
display: flex;
align-items: center;
gap: 0.5rem;
font-weight: 500;
color: var(--text-primary);
margin-bottom: 0.5rem;
font-size: 0.95rem;
}
/* Dynamic Label Icon Colors */
.check-in .form-group label i {
color: var(--primary-color);
}
.check-out .form-group label i {
color: var(--orange-color);
}
.form-control {
width: 100%;
padding: 0.875rem 1rem;
border: 2px solid var(--border-color);
border-radius: var(--border-radius);
font-size: 1rem;
transition: var(--transition);
background: white;
}
.form-control:focus {
outline: none;
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}
/* Dynamic Focus Colors */
.check-in .form-control:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}
.check-out .form-control:focus {
border-color: var(--orange-color);
box-shadow: 0 0 0 3px rgba(234, 88, 12, 0.1);
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 1.2rem 2rem;
font-size: 1.2rem;
font-weight: 700;
border: none;
border-radius: var(--border-radius);
cursor: pointer;
transition: var(--transition);
text-decoration: none;
width: 100%;
text-shadow: none;
letter-spacing: 0.5px;
}
/* Dynamic Button Colors - Dark Salmon Theme */
.check-in .btn-primary {
background: #e9967a;
color: #ffffff;
border: 2px solid #e9967a;
}
.check-out .btn-primary {
background: #e9967a;
color: #ffffff;
border: 2px solid #e9967a;
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: var(--shadow-lg);
}
.check-in .btn-primary:hover {
background: #cd853f;
border-color: #cd853f;
}
.check-out .btn-primary:hover {
background: #cd853f;
border-color: #cd853f;
}
.btn-primary:active {
transform: translateY(0);
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none !important;
}
/* Camera Verification Styles */
.verification-modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.9);
z-index: 10000;
justify-content: center;
align-items: center;
}
.verification-modal.active {
display: flex;
}
.verification-content {
background: white;
border-radius: var(--border-radius);
padding: 2rem;
max-width: 600px;
width: 90%;
max-height: 90vh;
overflow-y: auto;
}
.verification-header {
text-align: center;
margin-bottom: 1.5rem;
}
.verification-header h2 {
color: var(--text-primary);
margin-bottom: 0.5rem;
}
.verification-header .distance-warning {
color: #dc2626;
font-weight: 600;
margin-top: 0.5rem;
}
.camera-preview {
position: relative;
width: 100%;
background: #000;
border-radius: var(--border-radius);
overflow: hidden;
margin: 1rem 0;
}
.camera-preview video {
width: 100%;
height: auto;
display: block;
}
.camera-preview canvas {
display: none;
}
.camera-preview img {
width: 100%;
height: auto;
display: block;
}
.camera-controls {
display: flex;
gap: 1rem;
justify-content: center;
margin-top: 1rem;
}
.camera-btn {
padding: 0.75rem 1.5rem;
border: none;
border-radius: var(--border-radius);
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.camera-btn.capture {
background: var(--primary-color);
color: white;
}
.camera-btn.capture:hover {
background: var(--primary-dark);
}
.camera-btn.retake {
background: #f59e0b;
color: white;
}
.camera-btn.retake:hover {
background: #d97706;
}
.camera-btn.submit-verification {
background: #10b981;
color: white;
}
.camera-btn.submit-verification:hover {
background: #059669;
}
.camera-btn.cancel {
background: #6b7280;
color: white;
}
.camera-btn.cancel:hover {
background: #4b5563;
}
.camera-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.verification-instructions {
background: #fef3c7;
border-left: 4px solid #f59e0b;
padding: 1rem;
margin-bottom: 1rem;
border-radius: 4px;
}
.verification-instructions p {
margin: 0.5rem 0;
color: #78350f;
}
.success-card {
background: rgba(255, 255, 255, 0.95);
border-radius: var(--border-radius);
padding: 2rem;
text-align: center;
box-shadow: var(--shadow-lg);
backdrop-filter: blur(10px);
display: none;
}
.success-card.show {
display: block;
animation: slideUp 0.5s ease-out;
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.success-icon {
width: 50px;
height: 50px;
border-radius: 50%;
display: none; /* Change back to 'flex' to display icon */
align-items: center;
justify-content: center;
margin: 0 auto 1.5rem;
font-size: 1.5rem;
color: white;
}
/* Dynamic Success Icon Colors - Green Theme */
.check-in .success-icon {
background: #10b981;
}
.check-out .success-icon {
background: #10b981;
}
.success-card h2 {
font-size: 1.5rem;
font-weight: 700;
color: var(--text-primary);
margin-bottom: 1rem;
}
.success-details {
background: var(--background-light);
border-radius: var(--border-radius);
padding: 1.5rem;
margin-top: 1.5rem;
}
.detail-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem 0;
border-bottom: 1px solid var(--border-color);
}
.detail-row:last-child {
border-bottom: none;
}
.detail-label {
font-weight: 500;
color: var(--text-secondary);
}
.detail-value {
font-weight: 600;
color: var(--text-primary);
text-align: right;
}
.status-message {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
padding: 1rem 1.5rem;
border-radius: var(--border-radius);
font-weight: 500;
z-index: 1000;
display: none;
box-shadow: var(--shadow-lg);
}
.status-message.show {
display: block;
animation: slideDown 0.3s ease-out;
}
.status-message.success {
background: var(--success-color);
color: white;
}
.status-message.warning {
background: var(--error-color);
color: white;
}
.status-message.error {
background: var(--error-color);
color: white;
}
.status-message.processing {
background: var(--warning-color);
color: white;
}
@keyframes slideDown {
from {
opacity: 0;
transform: translateX(-50%) translateY(-10px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
.loading-spinner {
border: 3px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top: 3px solid white;
width: 20px;
height: 20px;
animation: spin 1s linear infinite;
margin-right: 0.5rem;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.fade-transition {
opacity: 0;
transform: translateY(20px);
transition: opacity 0.6s ease-out, transform 0.6s ease-out;
}
.fade-transition.active {
opacity: 1;
transform: translateY(0);
}
/* Language Legend */
.language-legend {
display: flex;
justify-content: center;
gap: 1.5rem;
margin: 1rem 0;
padding: 12px;
background: rgba(255, 255, 255, 0.9);
border-radius: 8px;
backdrop-filter: blur(10px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
font-size: 0.875rem;
font-weight: 500;
}
.legend-color {
width: 16px;
height: 16px;
border-radius: 4px;
}
.english-legend {
background: #1e40af;
}
.spanish-legend {
background: #15803d;
}
/* Camera Verification Styles */
.verification-modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.9);
z-index: 10000;
justify-content: center;
align-items: center;
}
.verification-modal.active {
display: flex;
}
.verification-content {
background: white;
border-radius: var(--border-radius);
padding: 2rem;
max-width: 600px;
width: 90%;
max-height: 90vh;
overflow-y: auto;
}
.verification-header h2 {
color: var(--text-primary);
margin-bottom: 0.5rem;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
}
.verification-header .distance-warning {
color: #dc2626;
font-weight: 600;
margin-top: 0.5rem;
font-size: 1rem;
}
.camera-preview {
position: relative;
width: 100%;
background: #000;
border-radius: var(--border-radius);
overflow: hidden;
margin: 1rem 0;
min-height: 300px;
display: flex;
align-items: center;
justify-content: center;
}
.camera-preview video {
width: 100%;
height: auto;
display: block;
}
.camera-preview canvas {
display: none;
}
.camera-preview img {
width: 100%;
height: auto;
display: block;
}
.camera-controls {
display: flex;
gap: 1rem;
justify-content: center;
margin-top: 1rem;
flex-wrap: wrap;
}
.camera-btn {
padding: 0.75rem 1.5rem;
border: none;
border-radius: var(--border-radius);
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
display: flex;
align-items: center;
gap: 0.5rem;
}
.camera-btn.capture {
background: var(--primary-color);
color: white;
}
.camera-btn.capture:hover {
background: var(--primary-hover);
}
.camera-btn.retake {
background: #f59e0b;
color: white;
}
.camera-btn.retake:hover {
background: #d97706;
}
.camera-btn.submit-verification {
background: #10b981;
color: white;
}
.camera-btn.submit-verification:hover {
background: #059669;
}
.camera-btn.cancel {
background: #6b7280;
color: white;
}
.camera-btn.cancel:hover {
background: #4b5563;
}
.camera-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.verification-instructions {
background: #fef3c7;
border-left: 4px solid #f59e0b;
padding: 1rem;
margin-bottom: 1rem;
border-radius: 4px;
}
.verification-instructions p {
margin: 0.5rem 0;
color: #78350f;
font-size: 0.95rem;
}
.verification-instructions strong {
color: #92400e;
}
/* Responsive Design */
@media (max-width: 640px) {
.destination-container {
padding: 0.5rem;
}
.destination-header,
.checkin-card,
.success-card {
padding: 1.5rem;
}
.destination-header h1 {
font-size: 1.5rem;
}
.checkin-header h2 {
font-size: 1.25rem;
}
.detail-row {
flex-direction: column;
align-items: flex-start;
gap: 0.25rem;
}
.detail-value {
text-align: left;
}
.language-legend {
flex-direction: column;
gap: 0.75rem;
}
}
.location-warning-banner {
background: linear-gradient(135deg, #fef3c7, #fde68a);
border: 2px solid #f59e0b;
border-radius: var(--border-radius);
margin-bottom: 1rem;
padding: 1rem;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
animation: slideInWarning 0.5s ease-out;
}
.warning-content {
display: flex;
align-items: flex-start;
gap: 0.75rem;
}
.warning-icon {
color: #d97706;
font-size: 1.25rem;
margin-top: 0.125rem;
flex-shrink: 0;
}
.warning-text {
flex: 1;
}
.warning-message {
display: block;
color: #92400e;
font-weight: 500;
font-size: 0.95rem;
line-height: 1.5;
margin-bottom: 0.75rem;
}
.warning-actions {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
.warning-retry-btn,
.warning-dismiss-btn {
display: inline-flex;
align-items: center;
gap: 0.375rem;
padding: 0.5rem 0.75rem;
border: none;
border-radius: calc(var(--border-radius) * 0.75);
font-size: 0.85rem;
font-weight: 500;
cursor: pointer;
transition: var(--transition);
text-decoration: none;
}
.warning-retry-btn {
background: #f59e0b;
color: white;
}
.warning-retry-btn:hover {
background: #d97706;
transform: translateY(-1px);
}
.warning-dismiss-btn {
background: rgba(156, 163, 175, 0.2);
color: #6b7280;
border: 1px solid rgba(156, 163, 175, 0.3);
}
.warning-dismiss-btn:hover {
background: rgba(156, 163, 175, 0.3);
color: #4b5563;
}
/* Warning animation */
@keyframes slideInWarning {
from {
opacity: 0;
transform: translateY(-20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Language styling for warning buttons */
.warning-retry-btn .language-separator,
.warning-dismiss-btn .language-separator {
opacity: 0.7;
margin: 0 0.25rem;
}
.warning-retry-btn .spanish-text,
.warning-dismiss-btn .spanish-text {
font-style: italic;
opacity: 0.9;
}
/* Responsive adjustments for warning */
@media (max-width: 640px) {
.warning-content {
flex-direction: column;
gap: 0.5rem;
}
.warning-actions {
justify-content: center;
}
.warning-retry-btn,
.warning-dismiss-btn {
flex: 1;
justify-content: center;
min-width: 120px;
}
}
</style>
</head>
<body
class="{% if qr_code.location_event == 'Check Out' %}check-out{% else %}check-in{% endif %}"
>
<div class="destination-container">
<!-- Header Section with Dynamic Styling and Color-Coded Languages -->
<div class="destination-header fade-transition active">
{% if qr_code.location_event == 'Check In' %}
<h1>
<span class="english-text">{{ qr_code.location_event }}</span>
<span class="language-separator">/</span>
<span class="spanish-text">Entrada</span>
</h1>
{% else %}
<h1>
<span class="english-text">{{ qr_code.location_event }}</span>
<span class="language-separator">/</span>
<span class="spanish-text">Salida</span>
</h1>
{% endif %}
<p class="location-info">
<i class="fas fa-map-marker-alt"></i>
{{ qr_code.location }}
</p>
</div>
<!-- Status Message -->
<div id="statusMessage" class="status-message">
<div class="status-content">
<i class="fas fa-info-circle"></i>
<span>Status message</span>
</div>
</div>
<!-- Check-in Form with Dynamic Styling and Color-Coded Instructions -->
<!-- ===== Step 1 — Location Dropdown Selector (Dynamic QR only) ===== -->
{% if qr_code.qr_type == 'dynamic' %}
<div class="checkin-card fade-transition active" id="locationSelectCard">
<div class="checkin-header">
<div class="bilingual-container">
<p>
<span class="english-text">
<i class="fas fa-map-marker-alt"></i> Please select your work location.
</span>
<span class="language-separator">/</span>
<span class="spanish-text">Por favor seleccione su ubicación de trabajo.</span>
</p>
</div>
</div>
<div class="form-group" style="margin-top:1rem;">
<select id="locationDropdown" class="form-control"
style="font-size:1rem;padding:0.75rem;height:auto;">
<option value="">-- Select a location / Seleccione una ubicación --</option>
{% for loc in locations %}
<option
value="{{ loc.location | e }}"
data-address="{{ (loc.location_address or '') | e }}"
>{{ loc.location }}</option>
{% else %}
<option value="" disabled>No locations configured</option>
{% endfor %}
</select>
</div>
<button type="button" class="btn btn-primary"
id="confirmLocationBtn"
style="width:100%;margin-top:0.75rem;padding:0.9rem;font-size:1rem;"
onclick="confirmLocationSelection()">
<i class="fas fa-check" style="margin-right:0.5rem;"></i>
<span class="english-text">Confirm Location</span>
<span class="language-separator">/</span>
<span class="spanish-text">Confirmar Ubicación</span>
</button>
<div id="locationSelectError" style="display:none;margin-top:0.5rem;">
<div class="bilingual-container" style="background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.3);">
<p style="margin:0;color:#dc2626;">
<i class="fas fa-exclamation-circle"></i>
<span class="english-text">Please select a location before continuing.</span>
<span class="language-separator">/</span>
<span class="spanish-text">Por favor seleccione una ubicación.</span>
</p>
</div>
</div>
</div>
{% endif %}
<!-- ===== END Step 1 ===== -->
<!-- Step 2 (or sole step for Standard QR): Employee ID form -->
<div
class="checkin-card fade-transition {% if qr_code.qr_type != 'dynamic' %}active{% endif %}"
id="checkinFormCard"
{% if qr_code.qr_type == 'dynamic' %}style="display:none;"{% endif %}
>
<div class="checkin-header">
<div class="bilingual-container">
<p>
<span class="english-text">Please enter your Employee ID.</span>
<span class="language-separator">/</span>
<span class="spanish-text"
>Por favor ingrese su ID de empleado.</span
>
</p>
</div>
</div>
<form id="checkinForm" onsubmit="return false;">
<!-- ADDED: carries the employee-selected location to the backend -->
<input type="hidden" id="selected_location_name" name="selected_location_name" value="" />
<input type="hidden" id="selected_location_address" name="selected_location_address" value="" />
<!-- ADDED: selected location confirmation badge (dynamic QR only) -->
{% if qr_code.qr_type == 'dynamic' %}
<div id="selectedLocationBadge"
class="bilingual-container"
style="display:none;margin-bottom:1rem;background:rgba(37,99,235,0.07);border:1px solid rgba(37,99,235,0.28);">
<p style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:0.5rem;margin:0;">
<span>
<i class="fas fa-map-marker-alt" style="color:#2563eb;"></i>
<strong id="selectedLocationDisplay" style="margin-left:0.4rem;"></strong>
</span>
<button
type="button"
onclick="backToLocationSelect()"
style="background:none;border:1px solid #2563eb;color:#2563eb;border-radius:4px;padding:3px 12px;cursor:pointer;font-size:0.85rem;"
>
<i class="fas fa-arrow-left"></i>
<span class="english-text">Change</span>
<span class="language-separator">/</span>
<span class="spanish-text">Cambiar</span>
</button>
</p>
</div>
{% endif %}
<div class="form-group">
<label for="employee_id">
<i class="fas fa-id-card"></i>
<span class="english-text">Employee ID</span>
<span class="language-separator">/</span>
<span class="spanish-text">ID de Empleado</span>
</label>
<input
type="text"
id="employee_id"
name="employee_id"
class="form-control"
placeholder="Enter your employee ID / Ingrese su ID de empleado"
required
autocomplete="off"
inputmode="numeric"
pattern="[0-9]*"
maxlength="4"
/>
</div>
<div class="form-group">
<label for="work_type">
<i class="fas fa-briefcase"></i>
<span class="english-text">Type of Work</span>
<span class="language-separator">/</span>
<span class="spanish-text">Tipo de Trabajo</span>
</label>
<select
id="work_type"
name="work_type"
class="form-control"
autocomplete="off"
>
<!-- <option> cannot hold the coloured english-text/spanish-text
spans used elsewhere, so both languages share one plain label,
separated by "/" like the Employee ID placeholder above. -->
<option value="" selected>Regular / Trabajo Regular</option>
<option value="PW">Periodic Work / Trabajo Periódico (PW)</option>
<option value="SP">Special Project / Proyecto Especial (SP)</option>
<option value="C">Covering / Cobertura (C)</option>
</select>
<!-- Check-out reminder: filled in by loadOpenCheckInWorkType() with
the work type of the employee's still-open check-in. -->
<div id="workTypeHint" class="work-type-hint" style="display: none;">
<i class="fas fa-info-circle"></i>
<span class="english-text" id="workTypeHintEn"></span>
<span class="language-separator">/</span>
<span class="spanish-text" id="workTypeHintEs"></span>
</div>
</div>
<button type="submit" class="btn btn-primary" id="submitButton">
{% if qr_code.location_event == 'Check In' %}
<i class="fas fa-sign-in-alt"></i>
<span class="english-text">Check In</span>
<span class="language-separator">/</span>
<span class="spanish-text">Entrada</span>
{% else %}
<i class="fas fa-sign-out-alt"></i>
<span class="english-text">Check Out</span>
<span class="language-separator">/</span>
<span class="spanish-text">Salida</span>
{% endif %}
</button>
</form>
</div>
<div class="success-card" id="successCard">
<div class="success-icon">
<i class="fas fa-check"></i>
</div>
<h2>
<span class="english-text">Success!</span>
<span class="language-separator">/</span>
<span class="spanish-text">¡Éxito!</span>
</h2>
<div class="bilingual-container">
<p>
<span class="english-text">Your submission has been recorded successfully.</span>
<span class="language-separator">/</span>
<span class="spanish-text">Su registro ha sido guardado exitosamente.</span>
</p>
</div>
<!-- Enhanced Success Details with Employee Information -->
<div class="success-details" id="successDetails">
<div class="detail-row">
<span class="detail-label">
<span class="english-text">Employee ID</span>
<span class="language-separator">/</span>
<span class="spanish-text">ID del Empleado</span>
</span>
<span class="detail-value" id="successEmployeeId">-</span>
</div>
<div class="detail-row">
<span class="detail-label">
<span class="english-text">Type of Work</span>
<span class="language-separator">/</span>
<span class="spanish-text">Tipo de Trabajo</span>
</span>
<span class="detail-value" id="successWorkType">-</span>
</div>
<div class="detail-row">
<span class="detail-label">
<span class="english-text">Date</span>
<span class="language-separator">/</span>
<span class="spanish-text">Fecha</span>
</span>
<span class="detail-value" id="successCheckInDate">-</span>
</div>
<div class="detail-row">
<span class="detail-label">
<span class="english-text">Time</span>
<span class="language-separator">/</span>
<span class="spanish-text">Hora</span>
</span>
<span class="detail-value" id="successCheckInTime">-</span>
</div>
<div class="detail-row">
<span class="detail-label">
<span class="english-text">Action</span>
<span class="language-separator">/</span>
<span class="spanish-text">Acción</span>
</span>
<span class="detail-value" id="successEvent">-</span>
</div>
<div class="detail-row">
<span class="detail-label">
<span class="english-text">Location</span>
<span class="language-separator">/</span>
<span class="spanish-text">Ubicación</span>
</span>
<span class="detail-value" id="successLocation">-</span>
</div>
<!-- Optional Additional Details (hidden by default) -->
<div class="detail-row" style="display: none;" id="successAddressRow">
<span class="detail-label">
<span class="english-text">Address</span>
<span class="language-separator">/</span>
<span class="spanish-text">Dirección</span>
</span>
<span class="detail-value" id="successAddress">-</span>
</div>
<div class="detail-row" style="display: none;" id="successAccuracyRow">
<span class="detail-label">
<span class="english-text">Accuracy</span>
<span class="language-separator">/</span>
<span class="spanish-text">Precisión</span>
</span>
<span class="detail-value" id="successLocationAccuracy">-</span>
</div>
</div>
</div>
<!-- Camera Verification Modal -->
<div id="verificationModal" class="verification-modal">
<div class="verification-content">
<div class="verification-header">
<h2>
<i class="fas fa-camera"></i>
Distance Violation<br>
Violación de distancia
</h2>
<p class="verification-instructions">
<i class="fas fa-exclamation-triangle"></i>
<strong>Please take a selfie with the QR code to verification.</strong><br>
<i class="fas fa-exclamation-triangle"></i>
<strong>Por favor, tome una selfie con el QR en el closet de custodios para verificar su locacion.</strong>
</p>
<p class="distance-warning">
Distance/Distancia: <span id="verificationDistance">--</span> miles
(Threshold/Umbral: <span id="verificationThreshold">0.3</span> miles)
</p>
</div>
<div class="camera-preview" id="cameraPreview">
<video id="cameraVideo" autoplay playsinline></video>
<canvas id="cameraCanvas"></canvas>
<img id="capturedPhoto" style="display: none;" />
</div>
<div class="camera-controls">
<button type="button" class="camera-btn capture" id="captureBtn">
<i class="fas fa-camera"></i> Take Photo/Tomar foto
</button>
<button type="button" class="camera-btn retake" id="retakeBtn" style="display: none;">
<i class="fas fa-redo"></i> Retake/Volver a tomar
</button>
<button type="button" class="camera-btn submit-verification" id="submitVerificationBtn" style="display: none;">
<i class="fas fa-check"></i> Submit with Photo/Entregar
</button>
<button type="button" class="camera-btn cancel" id="cancelVerificationBtn">
<i class="fas fa-times"></i> Cancel/Cancelar
</button>
</div>
</div>
</div>
</div>
<!-- Enhanced JavaScript with preserved functionality -->
<!-- Dynamic QR: expose selected location to qr_destination.js via window globals -->
<script>
window._dynamicQRSelectedName = "";
window._dynamicQRSelectedAddress = "";
</script>
<script src="{{ url_for('static', filename='js/qr_destination.js') }}"></script>
<script src="{{ url_for('static', filename='js/android_location_handler.js') }}"></script>
<script>
// Use different variable name to avoid conflict with external JS
let currentUserLocation = {
latitude: null,
longitude: null,
accuracy: null,
altitude: null,
timestamp: null,
source: "manual",
address: null,
};
let locationCaptureActive = false;
// Initialize the page when DOM is loaded
document.addEventListener("DOMContentLoaded", function () {
// Initialize Employee ID auto-fill FIRST (before other functionality)
initializeEmployeeIdAutoFill();
// Then initialize other functionality
initializeFormHandling();
initializeLocationCapture();
initializeWorkTypeSelector();
// Add fade-in animations
setTimeout(() => {
document.querySelectorAll(".fade-transition").forEach((el) => {
el.classList.add("active");
});
}, 100);
});
// ===== Type of Work: submit-button echo + check-out reminder =====
// Bilingual labels - mirror WORK_TYPE_LABELS in routes/qr_codes.py.
const WORK_TYPE_LABELS = {
"": { en: "Regular", es: "Trabajo Regular" },
PW: { en: "Periodic Work", es: "Trabajo Periódico" },
SP: { en: "Special Project", es: "Proyecto Especial" },
PT: { en: "Project Team", es: "Equipo de Proyecto" },
C: { en: "Covering", es: "Cobertura" },
};
// Set once the employee changes the dropdown by hand - a manual choice is
// never overwritten by the check-out suggestion. Only a change that follows
// a real interaction counts: iOS Safari restores form-control state on its
// own and that restore must not be mistaken for the employee choosing.
let workTypeChosenByEmployee = false;
let workTypeTouchedByEmployee = false;
// Last suggestion received from the server ('' = Regular, null = none).
// Kept so it can be re-applied after Safari restores the <select>.
let suggestedWorkTypeCode = null;
// Employee ID + location the suggestion was last fetched for, so typing
// does not re-request the same lookup repeatedly.
let lastWorkTypeLookupKey = null;
let workTypeLookupTimer = null;
function currentWorkTypeCode() {
const field = document.getElementById("work_type");
return field ? field.value.trim().toUpperCase() : "";
}
function currentWorkTypeLabel() {
return WORK_TYPE_LABELS[currentWorkTypeCode()] || WORK_TYPE_LABELS[""];
}
// Rebuild the submit button label. Single source for the button markup so
// resetEnhancedSubmitButton() does not have to duplicate it.
// The label stays plain "Check In" / "Check Out" - the selected type of
// work is NOT appended here: the extra line broke the button layout.
// The type is confirmed by the amber reminder and the success card instead.
function renderSubmitButton() {
const submitButton = document.getElementById("submitButton");
if (!submitButton || submitButton.disabled) {
return; // mid-submit: leave the processing state alone
}
const isCheckOut = document.body.classList.contains("check-out");
const icon = isCheckOut ? "fa-sign-out-alt" : "fa-sign-in-alt";
const actionEn = isCheckOut ? "Check Out" : "Check In";
// Same wording as the Jinja-rendered button above, so re-rendering on
// load does not visibly change the label.
const actionEs = isCheckOut ? "Salida" : "Entrada";
submitButton.innerHTML =
'<i class="fas ' + icon + '"></i>' +
'<span class="english-text">' + actionEn + '</span>' +
'<span class="language-separator">/</span>' +
'<span class="spanish-text">' + actionEs + '</span>';
}
/**
* Put the suggested work type into the dropdown.
*
* Called more than once on purpose: iOS Safari restores previous form
* values AFTER load - and therefore after our fetch resolves - which
* silently reset the dropdown to Regular on iPhone while desktop browsers
* (which only restore on back/forward) were unaffected.
*/
function applyWorkTypeSuggestion() {
if (suggestedWorkTypeCode === null || workTypeChosenByEmployee) {
return;
}
const field = document.getElementById("work_type");
if (field && field.value !== suggestedWorkTypeCode) {
field.value = suggestedWorkTypeCode;
}
}
function hideWorkTypeHint() {
const hint = document.getElementById("workTypeHint");
if (hint) hint.style.display = "none";
}
function showWorkTypeHint(label, time, location) {
const hint = document.getElementById("workTypeHint");
const hintEn = document.getElementById("workTypeHintEn");
const hintEs = document.getElementById("workTypeHintEs");
if (!hint || !hintEn || !hintEs) return;
const atTimeEn = time ? " at " + time : "";
const atTimeEs = time ? " a las " + time : "";
const atLocation = location ? " (" + location + ")" : "";
hintEn.textContent =
"You checked in as " + label.en + atTimeEn + atLocation +
". Confirm or change the type of work.";
hintEs.textContent =
"Registró entrada como " + label.es + atTimeEs + atLocation +
". Confirme o cambie el tipo de trabajo.";
hint.style.display = "block";
}
/**
* On a CHECK OUT scan, ask the server which type of work this employee's
* still-open check-in used and pre-select it, so an SP check-in is not
* paired with a Regular check-out. The server answers with no suggestion
* for check-in scans and when the last scan was already a check-out.
*/
function loadOpenCheckInWorkType() {
const employeeIdField = document.getElementById("employee_id");
const employeeId = (employeeIdField ? employeeIdField.value : "").replace(
/[^0-9]/g,
""
);
if (employeeId.length < 3) {
hideWorkTypeHint();
lastWorkTypeLookupKey = null;
suggestedWorkTypeCode = null;
return;
}
const hiddenLocation = document.getElementById("selected_location_name");
const selectedLocation =
window._dynamicQRSelectedName ||
(hiddenLocation ? hiddenLocation.value : "") ||
"";
const lookupKey = employeeId + "|" + selectedLocation;
if (lookupKey === lastWorkTypeLookupKey) {
return; // already answered for this ID + location
}
lastWorkTypeLookupKey = lookupKey;
const params = new URLSearchParams({ employee_id: employeeId });
if (selectedLocation) {
params.append("selected_location_name", selectedLocation);
}
// Strip a trailing slash so the path never becomes "//last-work-type"
const basePath = window.location.pathname.replace(/\/+$/, "");
fetch(
basePath + "/last-work-type?" + params.toString(),
{
// iOS Safari caches plain GETs aggressively; a stale "no suggestion"
// answer would look exactly like the bug this endpoint fixes.
cache: "no-store",
headers: { "X-Requested-With": "XMLHttpRequest" },
}
)
.then(function (response) { return response.json(); })
.then(function (data) {
// work_type is "" for an open REGULAR check-in and null when there
// is nothing to suggest - only the latter means "stay quiet".
if (!data || data.work_type === null || data.work_type === undefined) {
suggestedWorkTypeCode = null;
hideWorkTypeHint();
return;
}
const code = String(data.work_type).toUpperCase();
const label =
data.work_type_label || WORK_TYPE_LABELS[code] || WORK_TYPE_LABELS[""];
// Pre-select the open check-in's type, unless the employee already
// picked one by hand.
suggestedWorkTypeCode = code;
applyWorkTypeSuggestion();
// Re-apply twice more: iOS Safari's form-state restore can land after
// this response and would otherwise put the dropdown back to Regular.
setTimeout(applyWorkTypeSuggestion, 250);
setTimeout(applyWorkTypeSuggestion, 900);
// The reminder is shown whether or not the dropdown accepted the
// value, so the employee always sees what they checked in as.
showWorkTypeHint(label, data.checked_in_time, data.checked_in_location);
})
.catch(function (error) {
// A failed hint must never block a check-out.
console.log("Could not load open check-in work type: " + error.message);
hideWorkTypeHint();
});
}
function attachWorkTypeListeners(field) {
if (!field) return;
// A restore-driven change carries no interaction; only mark the choice
// as the employee's once they have actually opened/focused the control.
["pointerdown", "touchstart", "focus", "keydown"].forEach(function (evt) {
field.addEventListener(evt, function () {
workTypeTouchedByEmployee = true;
});
});
field.addEventListener("change", function () {
if (!workTypeTouchedByEmployee) {
// No interaction preceded this change: it is Safari restoring the
// control, not the employee choosing. Re-assert the suggestion.
applyWorkTypeSuggestion();
return;
}
workTypeChosenByEmployee = true;
hideWorkTypeHint();
});
}
function initializeWorkTypeSelector() {
attachWorkTypeListeners(document.getElementById("work_type"));
// qr_destination.js replaces the whole form 1.5 s after load to take over
// the submit handler. The replacement nodes carry none of our listeners,
// so re-bind them and re-assert the suggested work type.
document.addEventListener("checkinFormReplaced", function () {
attachEmployeeIdListeners(document.getElementById("employee_id"));
attachWorkTypeListeners(document.getElementById("work_type"));
applyWorkTypeSuggestion();
});
// Safari fires pageshow after its form-state restore, and again when the
// page comes back from the back/forward cache.
window.addEventListener("pageshow", function (event) {
if (event.persisted) {
// Restored page: the open check-in may have changed since - re-ask.
lastWorkTypeLookupKey = null;
loadOpenCheckInWorkType();
} else {
applyWorkTypeSuggestion();
}
});
// The ID is usually auto-filled from the last scan, so look it up now too
loadOpenCheckInWorkType();
}
// Employee IDs are at most 4 digits. Keep in sync with the maxlength on
// #employee_id, QR_EMPLOYEE_ID_MAX_DIGITS in qr_destination.js and
// CHECKIN_EMPLOYEE_ID_MAX_DIGITS in routes/qr_codes.py. (Distinct names:
// both scripts share the page's global scope.)
const EMPLOYEE_ID_MAX_DIGITS = 4;
// FIXED Employee ID auto-fill functionality
function initializeEmployeeIdAutoFill() {
const employeeIdInput = document.getElementById("employee_id");
if (!employeeIdInput) {
return;
}
// Load and auto-fill last used Employee ID immediately
try {
// Digits only — a value stored before the numeric-only rule may
// still carry a work-type suffix (e.g. "1234SP").
const lastEmployeeId = (
localStorage.getItem("qr_last_employee_id") || ""
).replace(/[^0-9]/g, "");
// A stored ID longer than the limit is not filled in: cutting it
// down would silently check in a different employee.
if (lastEmployeeId !== "" && lastEmployeeId.length <= EMPLOYEE_ID_MAX_DIGITS) {
employeeIdInput.value = lastEmployeeId;
// Visual feedback that it's auto-filled
employeeIdInput.style.backgroundColor = "#f0f9ff";
setTimeout(() => {
employeeIdInput.style.backgroundColor = "";
}, 2000);
}
} catch (error) {
console.log(`❌ Error loading employee ID: ${error.message}`);
}
attachEmployeeIdListeners(employeeIdInput);
}
// Bound here and re-bound after qr_destination.js replaces the form
// (see the checkinFormReplaced handler below).
function attachEmployeeIdListeners(employeeIdInput) {
if (!employeeIdInput) return;
// Employee ID is numeric only, at most 4 digits — strip anything else as
// it is typed (covers paste, autofill and keyboards that ignore
// inputmode; maxlength alone does not limit values set by script).
employeeIdInput.addEventListener("input", function () {
const digitsOnly = this.value.replace(/[^0-9]/g, "").slice(0, EMPLOYEE_ID_MAX_DIGITS);
if (this.value !== digitsOnly) {
this.value = digitsOnly;
}
});
// Save Employee ID when it's entered successfully
employeeIdInput.addEventListener("input", function () {
const currentId = this.value.trim();
if (currentId.length >= 2) {
// Save if at least 2 characters
try {
localStorage.setItem("qr_last_employee_id", currentId);
} catch (error) {
console.log(`❌ Error saving employee ID: ${error.message}`);
}
}
});
// A different ID means a different open check-in — re-ask the server
employeeIdInput.addEventListener("input", function () {
clearTimeout(workTypeLookupTimer);
workTypeLookupTimer = setTimeout(loadOpenCheckInWorkType, 500);
});
}
// Initialize location services (renamed to avoid conflicts)
function initializeLocationCapture() {
requestUserLocationData();
}
// Request location data from device (renamed to avoid conflicts)
function requestUserLocationData() {
if (
typeof AndroidLocationHandler !== "undefined" &&
AndroidLocationHandler.isAndroidDevice()
) {
AndroidLocationHandler.initializeAndroidLocation();
return;
}
if (locationCaptureActive) {
return;
}
if (!navigator.geolocation) {
currentUserLocation.source = "manual";
return;
}
locationCaptureActive = true;
const options = {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 300000,
};
navigator.geolocation.getCurrentPosition(
handleEnhancedLocationSuccess,
(error) => {
// Simple fallback with low accuracy
const lowAccuracyOptions = {
enableHighAccuracy: false,
timeout: 15000,
maximumAge: 600000,
};
navigator.geolocation.getCurrentPosition(
handleEnhancedLocationSuccess,
handleEnhancedLocationError,
lowAccuracyOptions
);
},
options
);
}
// Handle successful location capture (renamed to avoid conflicts)
function handleEnhancedLocationSuccess(position) {
currentUserLocation = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracy: position.coords.accuracy,
altitude: position.coords.altitude,
timestamp: new Date(),
source: "gps",
address: null,
};
// Reverse geocode to get address
reverseGeocodeEnhanced(
currentUserLocation.latitude,
currentUserLocation.longitude
);
locationCaptureActive = false;
}
// Handle location capture errors (renamed to avoid conflicts)
function handleEnhancedLocationError(error) {
currentUserLocation.source = "manual";
locationCaptureActive = false;
}
// Reverse geocode coordinates to address (renamed to avoid conflicts)
function reverseGeocodeEnhanced(lat, lng) {
// Using Nominatim (OpenStreetMap) reverse geocoding service
const url = `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json&addressdetails=1&zoom=18`;
fetch(url, {
method: "GET",
headers: {
"User-Agent": "QR-Attendance-System/1.0",
},
})
.then((response) => response.json())
.then((data) => {
if (data && data.display_name) {
currentUserLocation.address = data.display_name;
} else {
currentUserLocation.address = `${lat.toFixed(10)}, ${lng.toFixed(
10
)}`;
}
})
.catch((error) => {
console.error(`❌ Enhanced reverse geocoding error:`, error);
// Fallback to coordinates if reverse geocoding fails
currentUserLocation.address = `${lat.toFixed(10)}, ${lng.toFixed(
10
)}`;
});
}
// Enhanced form handling with bilingual status messages
function initializeFormHandling() {
const form = document.getElementById("checkinForm");
const submitButton = document.getElementById("submitButton");
if (form && submitButton) {
// Remove any existing event listeners
form.removeEventListener("submit", handleEnhancedFormSubmission);
submitButton.removeEventListener(
"click",
handleEnhancedFormSubmission
);
// Add form submit event listener
form.addEventListener("submit", function (e) {
e.preventDefault();
handleEnhancedFormSubmission();
});
// Also add click event listener to button as backup
submitButton.addEventListener("click", function (e) {
e.preventDefault();
handleEnhancedFormSubmission();
});
}
}
// Handle form submission with location data (renamed to avoid conflicts)
function handleEnhancedFormSubmission() {
const employeeIdField = document.getElementById("employee_id");
// Numeric only — mirrors the input filter, in case the value was set
// programmatically (autofill / browser restore) without an input event.
if (employeeIdField) {
employeeIdField.value = employeeIdField.value.replace(/[^0-9]/g, "");
}
const employeeId = employeeIdField ? employeeIdField.value.trim() : "";
const workTypeField = document.getElementById("work_type");
const workType = workTypeField ? workTypeField.value.trim() : "";
const submitButton = document.getElementById("submitButton");
// FIX 2: For dynamic QR codes, block submission if no location was selected
var selLocField = document.getElementById("selected_location_name");
var locationSelectCard = document.getElementById("locationSelectCard");
var _guardDropdown = document.getElementById("locationDropdown");
var _hasLocation = (selLocField && selLocField.value.trim()) ||
(_guardDropdown && _guardDropdown.value.trim());
if (locationSelectCard && !_hasLocation) {
// No location selected — send employee back to Step 1
document.getElementById("checkinFormCard").style.display = "none";
locationSelectCard.style.display = "block";
showStatusMessage(
"Please select a location first / Por favor seleccione una ubicación primero",
"error"
);
return;
}
if (!employeeId) {
showStatusMessage(
"Please enter your Employee ID / Por favor ingrese su ID de empleado",
"error"
);
return;
}
if (!/^[0-9]+$/.test(employeeId)) {
showStatusMessage(
"Employee ID must contain numbers only / El ID de empleado debe contener solo números",
"error"
);
return;
}
// Refuse rather than truncate: a cut-down ID is a different employee
if (employeeId.length > EMPLOYEE_ID_MAX_DIGITS) {
showStatusMessage(
"Employee ID must be 4 digits or fewer / El ID de empleado debe tener 4 dígitos o menos",
"error"
);
return;
}
// Save Employee ID to localStorage for next time
try {
localStorage.setItem("qr_last_employee_id", employeeId);
} catch (error) {
console.log(`❌ Error saving employee ID: ${error.message}`);
}
// Disable button and show processing
if (submitButton) {
submitButton.disabled = true;
submitButton.innerHTML = `
<div class="loading-spinner"></div>
<span class="english-text">Processing</span>
<span class="language-separator">/</span>
<span class="spanish-text">Procesando</span>
`;
}
showStatusMessage(
"Processing check-in... / Procesando registro...",
"processing"
);
// Get current URL to determine QR URL
const pathParts = window.location.pathname.split("/");
const qrUrl = pathParts[pathParts.length - 1];
// Prepare form data with location information
const formData = new FormData();
formData.append("employee_id", employeeId);
// Empty string = Regular; PW / SP / C are appended to the ID server-side
formData.append("work_type", workType);
// Read selected location — window globals (most reliable), then hidden field, then dropdown
var _selLocName = window._dynamicQRSelectedName || "";
var _selLocAddr = window._dynamicQRSelectedAddress || "";
var _hiddenName = document.getElementById("selected_location_name");
var _hiddenAddr = document.getElementById("selected_location_address");
var _dropdown = document.getElementById("locationDropdown");
if (!_selLocName && _hiddenName && _hiddenName.value.trim()) {
_selLocName = _hiddenName.value.trim();
_selLocAddr = (_hiddenAddr && _hiddenAddr.value.trim()) ? _hiddenAddr.value.trim() : "";
}
if (!_selLocName && _dropdown && _dropdown.value.trim()) {
_selLocName = _dropdown.value.trim();
var _opt = _dropdown.options[_dropdown.selectedIndex];
_selLocAddr = _opt ? (_opt.getAttribute("data-address") || "") : "";
}
console.log("📍 [inline] Location — name:", _selLocName, "| addr:", _selLocAddr);
if (_selLocName) {
formData.append("selected_location_name", _selLocName);
}
if (_selLocAddr) {
formData.append("selected_location_address", _selLocAddr);
}
// Add location data to form submission
if (currentUserLocation.latitude !== null) {
formData.append("latitude", currentUserLocation.latitude.toString());
}
if (currentUserLocation.longitude !== null) {
formData.append(
"longitude",
currentUserLocation.longitude.toString()
);
}
if (currentUserLocation.accuracy !== null) {
formData.append("accuracy", currentUserLocation.accuracy.toString());
}
if (currentUserLocation.altitude !== null) {
formData.append("altitude", currentUserLocation.altitude.toString());
}
if (currentUserLocation.address) {
formData.append("address", currentUserLocation.address);
}
formData.append("location_source", currentUserLocation.source);
// Submit to backend
fetch(`/qr/${qrUrl}/checkin`, {
method: "POST",
body: formData,
})
.then((response) => {
return response.json();
})
.then((data) => {
if (data.success) {
showStatusMessage(
"Submission successful! / Envío exitoso",
"success"
);
showEnhancedSuccessCard(data);
} else if (data.requires_verification) {
// Photo verification required
console.log('⚠️ Photo verification required');
verificationAttemptData = formData; // Store for retry with photo
showVerificationModal(
data.distance || 0,
data.threshold || 0.3
);
} else {
showStatusMessage(
data.message || "Submission failed / Envío fallido",
"error"
);
resetEnhancedSubmitButton();
}
})
.catch((error) => {
console.error("❌ Enhanced fetch error:", error);
showStatusMessage("Network error / Error de red", "error");
resetEnhancedSubmitButton();
});
}
// Reset submit button (renamed to avoid conflicts)
function resetEnhancedSubmitButton() {
const submitButton = document.getElementById("submitButton");
submitButton.disabled = false;
// Rebuilds the plain Check In / Check Out label for this QR's event
renderSubmitButton();
}
// Enhanced status message display with color coding
function showStatusMessage(message, type) {
const statusMessage = document.getElementById("statusMessage");
const statusSpan = statusMessage.querySelector("span");
statusSpan.innerHTML = message;
statusMessage.className = `status-message ${type} show`;
setTimeout(() => {
statusMessage.classList.remove("show");
}, 5000);
}
// Enhanced success display with bilingual details (renamed to avoid conflicts)
function showEnhancedSuccessCard(data) {
const successCard = document.getElementById("successCard");
const checkinCard = document.querySelector(".checkin-card");
const successDetails = document.getElementById("successDetails");
// Hide the check-in form card
if (checkinCard) checkinCard.style.display = "none";
// Employee ID — prefer server response, fall back to input field
const employeeIdInput = document.getElementById("employee_id");
const employeeId =
(data.data && data.data.employee_id) ||
(employeeIdInput ? employeeIdInput.value.trim() : "N/A");
// Location name — prefer server response (handles dynamic QR correctly),
// fall back to the .location-info element shown on the page header.
let qrLocationName = (data.data && data.data.location) || null;
if (!qrLocationName) {
const el = document.querySelector(".location-info");
if (el) qrLocationName = el.textContent.trim();
}
if (!qrLocationName) qrLocationName = "Unknown Location";
// Location event — prefer server response (handles dynamic QR correctly),
// fall back to body class set by Jinja for standard QR codes.
const serverEvent = (data.data && data.data.event) || null;
const isCheckOut = document.body.classList.contains("check-out");
const locationEvent = serverEvent || (isCheckOut ? "Check Out" : "Check In");
const locationEventSpanish = (locationEvent === "Check Out") ? "Salida" : "Entrada";
// Type of work — prefer the server's label (authoritative: it reflects
// what was actually stored), fall back to the dropdown selection.
const workTypeLabel =
(data.data && data.data.work_type_label) || currentWorkTypeLabel();
// Build success detail rows
const checkInTime = (data.data && data.data.check_in_time) || new Date().toLocaleTimeString();
const checkInDate = (data.data && data.data.check_in_date) || new Date().toLocaleDateString();
successDetails.innerHTML = `
<div class="detail-row">
<span class="detail-label">
<span class="english-text">Employee ID</span>
<span class="language-separator">/</span>
<span class="spanish-text">ID de Empleado</span>
</span>
<span class="detail-value">${employeeId}</span>
</div>
<div class="detail-row">
<span class="detail-label">
<span class="english-text">Type of Work</span>
<span class="language-separator">/</span>
<span class="spanish-text">Tipo de Trabajo</span>
</span>
<span class="detail-value">
<span class="english-text">${workTypeLabel.en}</span>
<span class="language-separator">/</span>
<span class="spanish-text">${workTypeLabel.es}</span>
</span>
</div>
<div class="detail-row">
<span class="detail-label">
<span class="english-text">Event</span>
<span class="language-separator">/</span>
<span class="spanish-text">Evento</span>
</span>
<span class="detail-value">
<span class="english-text">${locationEvent}</span>
<span class="language-separator">/</span>
<span class="spanish-text">${locationEventSpanish}</span>
</span>
</div>
<div class="detail-row">
<span class="detail-label">
<span class="english-text">Date</span>
<span class="language-separator">/</span>
<span class="spanish-text">Fecha</span>
</span>
<span class="detail-value">${checkInDate}</span>
</div>
<div class="detail-row">
<span class="detail-label">
<span class="english-text">Time</span>
<span class="language-separator">/</span>
<span class="spanish-text">Hora</span>
</span>
<span class="detail-value">${checkInTime}</span>
</div>
<div class="detail-row">
<span class="detail-label">
<span class="english-text">Location</span>
<span class="language-separator">/</span>
<span class="spanish-text">Ubicación</span>
</span>
<span class="detail-value">${qrLocationName}</span>
</div>
`;
// Show success card
successCard.classList.add("show");
}
// ===== Dynamic QR location step handlers =====
function confirmLocationSelection() {
var dropdown = document.getElementById("locationDropdown");
var errorDiv = document.getElementById("locationSelectError");
// Validate a location has been chosen
if (!dropdown || !dropdown.value) {
if (errorDiv) errorDiv.style.display = "block";
return;
}
if (errorDiv) errorDiv.style.display = "none";
var name = dropdown.value;
var selOpt = dropdown.options[dropdown.selectedIndex];
var address = selOpt ? (selOpt.getAttribute("data-address") || "") : "";
// Store selection in hidden fields AND window globals
// (window globals are read by qr_destination.js's submitCheckin)
document.getElementById("selected_location_name").value = name;
document.getElementById("selected_location_address").value = address;
window._dynamicQRSelectedName = name;
window._dynamicQRSelectedAddress = address;
console.log("✅ confirmLocationSelection: stored location =", name);
// FIX 1: Update the page header .location-info to show the selected location
var locationInfoEl = document.querySelector(".location-info");
if (locationInfoEl) {
locationInfoEl.innerHTML = "<i class=\"fas fa-map-marker-alt\"></i> " + name;
}
// Show the selected location badge on the ID form
var display = document.getElementById("selectedLocationDisplay");
var badge = document.getElementById("selectedLocationBadge");
if (display) display.textContent = name;
if (badge) badge.style.display = "block";
// Transition: hide Step 1, show Step 2
document.getElementById("locationSelectCard").style.display = "none";
var formCard = document.getElementById("checkinFormCard");
formCard.style.display = "block";
formCard.classList.add("active");
// Auto-focus Employee ID input for faster mobile entry
var empInput = document.getElementById("employee_id");
if (empInput) { setTimeout(function () { empInput.focus(); }, 120); }
// The selected location decides whether this scan is a check-out, so the
// open-check-in work type can only be resolved now (dynamic QR).
loadOpenCheckInWorkType();
}
function backToLocationSelect() {
// Clear selection from hidden fields and window globals
document.getElementById("selected_location_name").value = "";
document.getElementById("selected_location_address").value = "";
window._dynamicQRSelectedName = "";
window._dynamicQRSelectedAddress = "";
var badge = document.getElementById("selectedLocationBadge");
if (badge) badge.style.display = "none";
// Reset dropdown
var dropdown = document.getElementById("locationDropdown");
if (dropdown) dropdown.value = "";
// Reset header back to blank while no location is selected
var locationInfoEl = document.querySelector(".location-info");
if (locationInfoEl) {
locationInfoEl.innerHTML = "<i class=\"fas fa-map-marker-alt\"></i> ";
}
// Transition: hide Step 2, show Step 1
document.getElementById("checkinFormCard").style.display = "none";
document.getElementById("locationSelectCard").style.display = "block";
}
// ===== END Dynamic QR location step handlers =====
</script>
</body>
</html>