# Attendance Backfill Access Fix

## Issue
Training providers could not backfill missing attendance rows - the feature was restricted to admins only.

## Problem
When viewing a submitted attendance day, if some trainees were missing from the original submission, only admins could use the "Submit missing rows" button to backfill those missing entries.

**Before:**
```typescript
const canBackfillMissing = can("admin:settings") && dateAlreadySubmitted;
```
- Required `admin:settings` permission
- Only admins/PMU could backfill
- Training providers locked out

## Solution
Changed permission check to allow anyone who can submit attendance:

**After:**
```typescript
const canBackfillMissing = can("submit:attendance") && dateAlreadySubmitted;
```
- Uses `submit:attendance` permission
- Training providers can now backfill their own attendance
- Same permission required for normal attendance submission

## Benefits

1. **Training Providers Can Self-Correct**
   - Don't need to wait for admin intervention
   - Can fix missing trainees immediately
   - Reduces support burden

2. **Consistent Permissions**
   - If you can submit attendance, you can backfill
   - No special elevated permission needed
   - Logical permission model

3. **Maintains Safety**
   - Still requires date to be already submitted
   - Only fills MISSING rows (never overwrites existing)
   - Audit trail tracks all backfill operations

## Who Can Backfill Now?

✅ **Can Backfill:**
- Project Administrators (have `submit:attendance`)
- M&E Officers (have `submit:attendance`)
- Training Provider Staff (have `submit:attendance`)
- TP Organization Admins (have `submit:attendance`)
- TP Site Leads (have `submit:attendance`)

❌ **Cannot Backfill:**
- Users without `submit:attendance` permission
- World Bank users (read-only)
- EDI users (read-only)

## How It Works

### Normal Attendance Flow:
1. Select training and date
2. Mark trainees present/absent
3. Submit attendance for that date
4. Date becomes "submitted" (locked)

### Backfill Flow (AFTER submission):
1. Select an already-submitted date
2. Notice some trainees are missing from records
3. Set status for missing trainees only
4. Click **"Submit missing rows"**
5. System inserts only missing entries
6. Never overwrites existing records

### Example Scenario:
```
Day 1 submission: 50 trainees marked
New trainee joins Day 2
Go back to Day 1: 1 trainee missing from roster
Use backfill: Add that 1 trainee's status for Day 1
Result: Day 1 now has 51 trainees
```

## UI Changes

**Before:**
```
Admin backfill workflow: set Present/Absent for each missing row...
[Submit missing rows] (only visible to admins)
```

**After:**
```
Backfill workflow: set Present/Absent for each missing row...
[Submit missing rows] (visible to all with submit:attendance)
```

Removed "Admin" from description since it's no longer admin-only.

## Safety Guarantees

✅ **Protected:**
- Cannot backfill dates that haven't been submitted yet
- Cannot overwrite existing attendance records
- All backfills logged in audit trail
- Requires same permission as normal submission

✅ **Validated:**
- Only fills entries for trainees WITHOUT recorded status
- Respects eligibility rules
- Shows clear confirmation: "inserted X, skipped existing Y, skipped ineligible Z"

## Testing

### Test 1: TP User Can Backfill
1. Login as TP staff user
2. Go to Attendance Hub
3. Select training with submitted dates
4. Click on a submitted date
5. **Verify:** "Submit missing rows" button is visible (if any rows missing)
6. Set status for missing trainees
7. Click "Submit missing rows"
8. **Verify:** Success message with counts
9. **Pass:** TP can backfill

### Test 2: Read-Only Users Cannot
1. Login as World Bank user (view-only)
2. Navigate to Attendance Hub
3. Select submitted date
4. **Verify:** "Submit missing rows" button NOT visible
5. **Pass:** Read-only users blocked

### Test 3: Backfill Safety
1. Submit attendance for 10 trainees
2. Add 2 new trainees to roster
3. Go back to that date
4. Set status for 2 missing trainees
5. Click "Submit missing rows"
6. **Verify:** Message shows "inserted 2, skipped existing 10"
7. **Verify:** Original 10 records unchanged
8. **Pass:** Only missing records added

## Files Modified

**Frontend:**
1. `frontend/src/pages/attendance/AttendanceHub.tsx`
   - Line 278: Changed `can("admin:settings")` → `can("submit:attendance")`
   - Line 1441: Removed "Admin" from backfill workflow description
   - Moved backfill button from top to bottom of attendance table (below all missing rows)
   - Added warning icon ⚠️ and counter showing "X missing row(s) to backfill"

**Backend:**
1. `backend/src/routes/attendance.ts`
   - Line 1255: Changed `requirePermission("admin:settings")` → `requirePermission("submit:attendance")`

## Audit Trail

All backfill operations are logged with:
- Action: `attendance_backfill_missing_rows`
- Actor: User who performed backfill
- Source: Training ID and date
- Payload: Number of entries inserted, skipped
- Timestamp: When backfill occurred

**View in:** Admin → Audit Trail → Filter by action type

## Permissions Reference

| Permission | Description | Who Has It | Can Backfill? |
|------------|-------------|------------|---------------|
| `admin:settings` | System admin | Admin, PMU | ✅ Yes (has submit:attendance) |
| `submit:attendance` | Submit attendance | Admin, M&E, TP Staff | ✅ Yes |
| `view:attendance` | View attendance | All roles | ❌ No (needs submit) |

## Use Cases

### Use Case 1: Late Enrollment
- Training started, attendance submitted for Week 1
- New trainee enrolls Week 2
- Need to backfill Week 1 attendance for new trainee
- **Solution:** TP can now backfill without admin help

### Use Case 2: Roster Correction
- Trainee incorrectly marked as ineligible initially
- Eligibility corrected in roster
- Need to add attendance records for past dates
- **Solution:** TP can backfill those dates

### Use Case 3: Batch Merge
- Two batches merged mid-training
- Batch B trainees missing from Batch A's historic attendance
- Need to fill missing records for continuity
- **Solution:** TP can backfill all past dates for Batch B trainees

## Important Notes

⚠️ **Backfill is NOT for corrections**
- Use backfill only for MISSING trainees
- To correct wrong status (present→absent): Submit a correction request to admin
- To change submitted records: Use audit trail, not backfill

⚠️ **Timing Matters**
- Backfill only works on SUBMITTED dates
- Cannot backfill future dates
- Cannot backfill unsubmitted dates
- Must submit first, then backfill if needed

⚠️ **Scope Awareness**
- Backfill respects cohort/batch scope
- Only backfills for selected delivery scope
- If training has multiple batches, backfill each separately

## Troubleshooting

**Q: "Submit missing rows" button not visible**
- Check if date is submitted (grey background on calendar)
- Verify you have `submit:attendance` permission
- Confirm there are actually missing trainees (some rows with no recorded status)

**Q: Backfill says "No missing trainee rows"**
- All trainees already have records for that date
- This is normal if roster hasn't changed since original submission

**Q: Some trainees skipped as "ineligible"**
- Those trainees are marked ineligible in roster
- This is correct behavior
- Only eligible trainees get attendance records

**Q: Can I backfill multiple dates at once?**
- No, backfill is per-date
- Must select each submitted date and backfill separately
- Consider CSV bulk import for many dates

## Summary

| Aspect | Before | After |
|--------|--------|-------|
| Who can backfill | Admins only | All with submit:attendance ✅ |
| TP access | ❌ Blocked | ✅ Allowed |
| Permission check | `admin:settings` | `submit:attendance` ✅ |
| UI text | "Admin backfill..." | "Backfill..." ✅ |
| Safety | ✅ Safe | ✅ Safe (same) |
| Audit logging | ✅ Logged | ✅ Logged (same) |

**Status:** Production Ready ✅  
**Backend Fix Applied:** Backend route now uses `submit:attendance` permission ✅

---

**Last Updated:** August 14, 2026
**Version:** 1.0
**Impact:** Training providers can now self-service attendance corrections
