clock system
# Clock-In/Clock-Out System
## Overview
The system tracks employee work hours by recording login (clock-in) and logout (clock-out) times, automatically calculating total hours worked. The system handles both manual logout and automatic logout when the page is closed.
## Database Schema
**`<companyslug>_employees_logs` table:**
- `id` - SERIAL PRIMARY KEY (log entry ID)
- `user_id` - VARCHAR(10) (employee ID)
- `first_name` - VARCHAR(100) (employee first name)
- `last_name` - VARCHAR(100) (employee last name)
- `login_time` - TIMESTAMP (when employee clocked in)
- `logout_time` - TIMESTAMP (when employee clocked out)
- `hours_worked` - VARCHAR(50) (calculated: "X hours Y minutes")
- `overtime_hours` - VARCHAR(50) (overtime duration if enabled)
- `late_reason` - TEXT (reason for late arrival if applicable)
- `late_status` - VARCHAR(10) ('Late' if late, NULL if on time)
- `created_at` - TIMESTAMP (record creation time)
## Workflow
### 1. Clock-In (Login)
1. Employee visits `/<companyslug>/login`
2. Clicks "Start Face Verification"
3. System captures face and matches against all registered employees
4. System:
- Creates new record in `<companyslug>_employees_logs`
- Records employee info and `login_time` (current timestamp)
- **Checks if employee is late** (clock-in time > scheduled start time + grace period)
- Formula: `is_late = clock_in_time > (scheduled_start_time + late_threshold_minutes)`
- Returns `log_id`, `login_time`, and `is_late` status
5. **If Late:**
- Employee redirected to late reason form
- Must select reason from dropdown or provide custom text
- Reason stored in `late_reason` column
- Late status marked as 'Late' in `late_status` column
- Then proceeds to dashboard
6. **If On Time:**
- Employee redirected directly to logged-in page
7. Logged-in page shows:
- Welcome message with employee name
- Login time
- Clock Out button
- Warning about proper logout
**Late Threshold (Grace Period):**
- Admin configures threshold in settings (0, 5, 10, 15, 20, 30 minutes)
- Default: 0 minutes (no grace period)
- Example: Scheduled 9:00 AM + 10 min threshold = Late if after 9:10 AM
- Can be disabled entirely in settings
See `LATE_CLOCKIN_TRACKING.md` and `LATE_CLOCKIN_PHASE3.md` for complete late clock-in documentation.
### 2. Logged-In State
- Employee sees prominent "Clock Out" button
- Page displays current login time
- Warning message explains logout process
- **Link to "View My Work Logs"** (opens in new tab)
- **Colleague visibility section** shows who else is logged in today
- **Automatic logout enabled**: If user closes dashboard tab, logout is recorded automatically
### 3. Employee Views Work Logs (Optional)
1. Employee clicks "View My Work Logs" link (opens in new tab)
2. Completes face verification to access logs
3. Views their clock-in/clock-out history for allowed date range (configured by admin)
4. Can close logs tab and return to dashboard
5. Dashboard tab remains open with Clock Out button available
**Note**: Closing the logs tab does NOT trigger logout. Only closing the dashboard tab triggers automatic logout.
### 4. Colleague Visibility
After logging in, employees can see who else has clocked in today:
**Display:**
- Blue info box: "👥 Colleagues Logged In Today"
- Shows count of colleagues
- Lists first and last names only
- Alphabetically sorted
- Scrollable list (if many employees)
**Purpose:**
- Team awareness - Know who's working today
- Collaboration - See who's available
- Social connection - Feel part of the team
**Privacy:**
- Only shows names (no user IDs)
- Only today's logins (not historical)
- No logout status shown
- Visible only to logged-in employees
### 5. Clock-Out (Two Methods)
#### Method A: Manual Clock-Out (Recommended)
1. Employee clicks "Clock Out" button
2. System:
- Updates `logout_time` to current timestamp
- Calculates time difference between login and logout
- Computes hours and minutes worked
- Updates `hours_worked` field (e.g., "8 hours 30 minutes")
3. Employee sees logout confirmation page with:
- User ID
- Total hours worked
#### Method B: Automatic Clock-Out (Page Close)
1. Employee closes browser tab/window (accidentally or intentionally)
2. Browser triggers `beforeunload` event
3. JavaScript uses `navigator.sendBeacon()` to send logout request
4. System:
- Updates `logout_time` to current timestamp
- Calculates hours worked
- Updates database record
5. No confirmation page shown (page already closed)
6. Admin can still see complete time tracking in database
## Automatic Logout Technology
**`navigator.sendBeacon()` API:**
- Specifically designed for sending data during page unload
- Guaranteed to send even if page closes immediately
- Non-blocking (doesn't delay page closure)
- Works on desktop and mobile browsers
**Implementation:**
```javascript
window.addEventListener('beforeunload', function(e) {
if (!isLoggingOut) {
const formData = new FormData();
formData.append('log_id', logId);
formData.append('user_id', userId);
// Sends logout request even as page closes
navigator.sendBeacon('/' + companySlug + '/logout', formData);
}
});
```
**Backup Mechanism:**
- Also triggers on `visibilitychange` event
- Handles tab switching and mobile app switching
- Ensures logout is recorded even if `beforeunload` fails
## Hours Calculation
**Formula:**
```
time_diff = logout_time - login_time
total_seconds = time_diff.total_seconds()
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
hours_worked = f"{hours} hours {minutes} minutes"
```
**Examples:**
- Login: 09:00:00, Logout: 17:30:00 → "8 hours 30 minutes"
- Login: 08:15:00, Logout: 12:45:00 → "4 hours 30 minutes"
- Login: 13:00:00, Logout: 13:45:00 → "0 hours 45 minutes"
## User Experience
**Manual Logout (Best Practice):**
1. User clicks "Clock Out" button
2. Sees confirmation with hours worked
3. Can return to home page
**Accidental Page Close:**
1. User closes tab/window
2. Logout recorded automatically in background
3. No confirmation shown (page already closed)
4. Admin can still track hours worked
**Benefits:**
- ✅ No lost time tracking data
- ✅ Handles accidental closures
- ✅ Works on all modern browsers
- ✅ Mobile-friendly
- ✅ Admin always has complete records
## Security Features
1. **Automatic Tracking**: Hours recorded even if user forgets to logout
2. **Timestamp Integrity**: Database timestamps ensure accuracy
3. **Log ID Tracking**: Each login session has unique ID
4. **Server-Side Calculation**: Hours computed server-side (cannot be manipulated)
## API Endpoints
**Clock-In:**
- Endpoint: `POST /<companyslug>/login`
- Input: `user_id` + face verification
- Output: Logged-in page with logout button
**Clock-Out (Manual or Automatic):**
- Endpoint: `POST /<companyslug>/logout`
- Input: `log_id`, `user_id`
- Output:
- Manual: Logout confirmation page with hours worked
- Automatic: Background update (no page shown)
## Python Functions
**`log_company_login(company_slug, user_id)`**
- Creates login record
- Returns: `(log_id, login_time)`
**`clock_out(company_slug, log_id)`**
- Updates logout time
- Calculates hours worked
- Returns: `"X hours Y minutes"`
## Admin Tracking
Admins can query `<companyslug>_employees_logs` to see:
- All employee login/logout times
- Hours worked per session
- Whether logout was manual or automatic (both recorded the same way)
- Complete time tracking history
**Example Query:**
```sql
SELECT user_id, login_time, logout_time, hours_worked
FROM acmecorp_employees_logs
WHERE user_id = 'JD1456'
ORDER BY login_time DESC;
```
## Required Work Hours
**Admin Configuration:**
- HR can set expected shift duration in settings (4-12 hours)
- Default: 8 hours
- Applies company-wide to all employees
**Purpose:**
- Define standard work shift length
- Track if employees meet required hours
- Support different shift types (part-time, full-time, extended)
**Configuration Location:**
`/<company>/settings` → "Required Work Hours" section
**Available Options:**
4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8 (default), 8.5, 9, 9.5, 10, 10.5, 11, 11.5, 12 hours
**Use Cases:**
- **Part-Time (4-6 hours)**: Retail, student workers
- **Standard (7.5-8 hours)**: Office workers, 9-to-5 schedules
- **Extended (9-12 hours)**: Healthcare, manufacturing, 24/7 operations
**Future Integration:**
- Compare actual vs required hours in reports
- Flag employees consistently under/over required hours
- Calculate overtime (hours beyond required)
- Display compliance metrics
See `REQUIRED_WORK_HOURS.md` for complete documentation.
## Browser Compatibility
**Supported Browsers:**
- Chrome 39+
- Firefox 31+
- Safari 11.1+
- Edge 14+
- Mobile browsers (iOS Safari, Chrome Mobile)
**`sendBeacon()` Support:**
- Widely supported in all modern browsers
- Fallback: If not supported, manual logout still works
## Future Enhancements
1. **Break Time Tracking**: Pause/resume work sessions
2. **Overtime Calculation**: Flag hours beyond standard workday
3. **Weekly/Monthly Reports**: Aggregate hours worked
4. **Export to CSV**: Download time logs
5. **Admin Dashboard**: Real-time view of who's clocked in
6. **Late/Early Warnings**: Alert if employee clocks in late or leaves early
7. **Geolocation Tracking**: Record location on clock-in/out (optional)
8. **Session Timeout**: Auto-logout after X hours of inactivity
## Related Documentation
- **Employee Self-Service**: See `EMPLOYEE_SELF_SERVICE.md` for employee log viewing
- **Admin Search**: See `SEARCH_SYSTEM.md` for HR/Admin log search features
- **Multi-Tenant System**: See `MULTITENANT_SYSTEM.md` for overall architecture