32 lines
900 B
TypeScript
32 lines
900 B
TypeScript
import { useState, useEffect } from 'react';
|
|
import { db, AttendanceRecord } from '../utils/db';
|
|
import { v4 as uuid } from 'uuid';
|
|
|
|
export function useAttendance() {
|
|
const [todayRecords, setTodayRecords] = useState<AttendanceRecord[]>([]);
|
|
|
|
useEffect(() => {
|
|
const dayStart = new Date();
|
|
dayStart.setHours(0,0,0,0);
|
|
db.records
|
|
.where('timestamp')
|
|
.above(dayStart.getTime())
|
|
.toArray()
|
|
.then(setTodayRecords);
|
|
}, []);
|
|
|
|
const clockToggle = (teacherId: string) => {
|
|
const recs = todayRecords.filter(r => r.teacherId === teacherId);
|
|
const next: 'in' | 'out' = recs.pop()?.type === 'in' ? 'out' : 'in';
|
|
const rec: AttendanceRecord = {
|
|
id: uuid(),
|
|
teacherId,
|
|
timestamp: Date.now(),
|
|
type: next
|
|
};
|
|
db.records.add(rec).then(() => setTodayRecords(prev => [...prev, rec]));
|
|
};
|
|
|
|
return { todayRecords, clockToggle };
|
|
}
|