Back to Documentation

live feed

# Live Colleague Feed (Phase 5)

## Overview

Phase 5 transforms the colleague visibility feature into a real-time live feed that shows only currently logged-in employees. When someone logs out, they immediately disappear from the list without requiring a page refresh.

## Key Changes from Phase 4

### Before (Phase 4)
- Showed all employees who logged in today
- Static list loaded on page load
- Required page refresh to see updates
- Included logged-out employees

### After (Phase 5)
- Shows only currently logged-in employees
- Live updates every 5 seconds
- No page refresh needed
- Removes employees immediately after logout

## How It Works

### Database Query Logic

**Filter Criteria:**
- `DATE(login_time) = CURRENT_DATE` - Logged in today
- `logout_time IS NULL` - Currently logged in (not logged out)

**Employee View Query:**
```sql
SELECT DISTINCT first_name, last_name
FROM <company>_employees_logs
WHERE DATE(login_time) = CURRENT_DATE
AND logout_time IS NULL
ORDER BY first_name, last_name
```

**Admin View Query:**
```sql
SELECT first_name, last_name, login_time
FROM <company>_employees_logs
WHERE DATE(login_time) = CURRENT_DATE
AND logout_time IS NULL
ORDER BY login_time DESC
```

### Real-Time Updates

**Technology:** JavaScript `fetch()` API with polling

**Update Frequency:** Every 5 seconds

**API Endpoints:**
- `/<company>/api/logged-in-employees` - Employee view (names only)
- `/<company>/api/logged-in-employees-admin` - Admin view (with timestamps)

### User Experience

**Scenario: Employee Logs Out**
1. Employee clicks "Clock Out" button
2. `logout_time` set in database
3. Within 5 seconds, employee disappears from all lists
4. Count updates automatically
5. No page refresh needed

**Scenario: New Employee Logs In**
1. Employee completes face verification
2. Login recorded with `logout_time = NULL`
3. Within 5 seconds, employee appears on all lists
4. Count increments automatically
5. All users see update without refreshing

## Technical Implementation

### Python Functions

**Employee View:**
```python
def get_employees_logged_in_today(company_slug):
    """Get list of employees currently logged in"""
    # Query with logout_time IS NULL filter
    # Returns: FirstName|LastName
```

**Admin View:**
```python
def get_employees_logged_in_today_with_times(company_slug):
    """Get list of employees currently logged in (for admin)"""
    # Query with logout_time IS NULL filter
    # Returns: FirstName|LastName|UserID|LoginTime
```

### Go API Handlers

**Employee API:**
```go
func apiLoggedInEmployeesHandler(w http.ResponseWriter, r *http.Request) {
    // Extract company slug
    // Call Python function
    // Parse results
    // Return JSON array of LoggedInEmployee
}
```

**Admin API:**
```go
func apiLoggedInEmployeesAdminHandler(w http.ResponseWriter, r *http.Request) {
    // Extract company slug
    // Call Python function
    // Parse results
    // Return JSON array of LoggedInEmployeeAdmin
}
```

### Frontend JavaScript

**Employee View (logged_in.html):**
```javascript
function updateColleagues() {
    fetch('/' + companySlug + '/api/logged-in-employees')
        .then(response => response.json())
        .then(data => {
            // Update count
            // Update list HTML
        });
}

setInterval(updateColleagues, 5000); // Every 5 seconds
```

**Admin View (company_admin.html):**
```javascript
function updateEmployees() {
    fetch('/' + companySlug + '/api/logged-in-employees-admin')
        .then(response => response.json())
        .then(data => {
            // Update count
            // Update table HTML
        });
}

setInterval(updateEmployees, 5000); // Every 5 seconds
```

## API Response Format

### Employee API Response
```json
[
  {
    "FirstName": "John",
    "LastName": "Doe"
  },
  {
    "FirstName": "Jane",
    "LastName": "Smith"
  }
]
```

### Admin API Response
```json
[
  {
    "FirstName": "John",
    "LastName": "Doe",
    "UserID": "JD1456",
    "LoginTime": "09:15:23"
  },
  {
    "FirstName": "Jane",
    "LastName": "Smith",
    "UserID": "JS1457",
    "LoginTime": "08:45:12"
  }
]
```

## Benefits

### Real-Time Awareness
- Know exactly who's working right now
- See colleagues join and leave in real-time
- No stale data from earlier in the day

### Improved Accuracy
- Only shows active employees
- Removes confusion about who's still logged in
- Better reflects current workplace status

### Better User Experience
- No manual page refresh needed
- Seamless updates
- Feels modern and responsive

### Admin Oversight
- Real-time attendance monitoring
- Immediate visibility of clock-outs
- Better workforce management

## Performance Considerations

### Polling Interval
- **5 seconds** chosen as balance between:
  - Real-time feel (not too slow)
  - Server load (not too frequent)
  - Network efficiency

### Optimization
- Lightweight JSON responses
- Minimal database queries
- Client-side rendering (no full page reload)
- Only updates when page is visible

### Scalability
- Works well for teams up to 100+ employees
- Database query uses indexed columns (login_time)
- Minimal server overhead per request

## Limitations

### Current Implementation
- 5-second delay before updates appear
- Requires JavaScript enabled
- No WebSocket (uses polling instead)
- Updates only when page is open

### What It Doesn't Do
- No push notifications
- No real-time chat
- No presence indicators (typing, idle, etc.)
- No historical playback

## Future Enhancements

1. **WebSocket Support** - True real-time updates (no polling)
2. **Faster Updates** - Sub-second refresh rates
3. **Push Notifications** - Alert when specific colleagues log in
4. **Presence Status** - Active, idle, away indicators
5. **Activity Feed** - "John logged in 2 minutes ago"
6. **Filtering** - Show only specific departments or teams
7. **Search** - Find specific colleagues in large lists

## Troubleshooting

### List Not Updating

**Possible Causes:**
- JavaScript disabled in browser
- Network connectivity issues
- API endpoint not responding

**Solution:**
- Check browser console for errors
- Verify API endpoints are accessible
- Refresh page manually

### Wrong Count Showing

**Possible Causes:**
- Database sync delay
- Multiple login sessions for same employee
- Logout not recorded properly

**Solution:**
- Wait 5 seconds for next update
- Check database for duplicate entries
- Verify logout functionality working

### Employee Not Disappearing After Logout

**Possible Causes:**
- Logout not recorded in database
- API returning cached data
- JavaScript error preventing update

**Solution:**
- Verify `logout_time` set in database
- Check browser console for errors
- Manually refresh page

## Testing

### Test Scenario 1: Single Employee
1. Employee logs in
2. Verify they appear in list within 5 seconds
3. Employee logs out
4. Verify they disappear within 5 seconds

### Test Scenario 2: Multiple Employees
1. Employee A logs in
2. Employee B logs in
3. Both appear in each other's lists
4. Employee A logs out
5. Employee A disappears from B's list
6. Employee B still sees themselves

### Test Scenario 3: Admin View
1. Admin authenticates
2. Sees empty list (no one logged in)
3. Employee logs in
4. Employee appears with timestamp within 5 seconds
5. Employee logs out
6. Employee disappears within 5 seconds

## Related Documentation

- **ADMIN_COLLEAGUE_VISIBILITY.md** - Phase 4 implementation
- **COLLEAGUE_VISIBILITY.md** - Phase 3 implementation
- **CLOCK_SYSTEM.md** - Clock-in/out workflow
- **README.md** - Overall system architecture