marco.pms.web/src/hooks/useAttendanceStatus.js
2025-06-24 12:07:34 +05:30

133 lines
3.3 KiB
JavaScript

import { useEffect, useState } from 'react';
import { timeElapsed } from '../utils/dateUtils'; // Make sure it calculates in hours
import { THRESH_HOLD } from '../utils/constants';
// THRESH_HOLD in hours (e.g., 12, 48, or 60)
export const ACTIONS = {
CHECK_IN: 0,
CHECK_OUT: 1,
REGULARIZATION: 2,
REQUESTED: 3,
APPROVED: 4,
REJECTED: 5
};
const useAttendanceStatus = (attendanceData) => {
const [status, setStatus] = useState({
status: "Unknown",
action: null,
disabled: true,
text: "Unknown",
color: 'btn-secondary',
});
useEffect(() => {
const { checkInTime, checkOutTime, activity } = attendanceData;
const now = new Date();
const isSameDay = (date1, date2) =>
new Date(date1).toDateString() === new Date(date2).toDateString();
// 1. No check-in/check-out yet → Allow Check-In
if (activity === 0 && !checkInTime && !checkOutTime) {
return setStatus({
status: "Check-In",
action: ACTIONS.CHECK_IN,
disabled: false,
text: "Check In",
color: 'btn-primary',
});
}
// 2. Checked in, no checkout yet
if (checkInTime && !checkOutTime) {
if (timeElapsed(checkInTime, THRESH_HOLD)) {
return setStatus({
status: "Request Regularize",
action: ACTIONS.REGULARIZATION,
disabled: false,
text: "Regularize",
color: 'btn-warning',
});
} else {
return setStatus({
status: "Check-Out",
action: ACTIONS.CHECK_OUT,
disabled: false,
text: "Check Out",
color: 'btn-primary',
});
}
}
// 3. Already checked in and out → Handle activity === 4 (Approved)
if (checkInTime && checkOutTime && activity === 4) {
if (!isSameDay(checkInTime, now) && !timeElapsed(checkInTime, THRESH_HOLD)) {
// Case: Past day, but still within threshold → Approved
return setStatus({
status: "Approved",
action: ACTIONS.APPROVED,
disabled: true,
text: "Approved",
color: 'btn-success',
});
} else if (isSameDay(checkOutTime, now)) {
// Case: same day → allow check-in again
return setStatus({
status: "Check In",
action: ACTIONS.CHECK_IN,
disabled: false,
text: "Check In",
color: 'btn-primary',
});
} else {
// Case: not same day AND over 48 hours → freeze status as Approved
return setStatus({
status: "Approved",
action: ACTIONS.APPROVED,
disabled: true,
text: "Approved",
color: 'btn-success',
});
}
}
// 4. Regularization Requested
if (activity === 2) {
return setStatus({
status: "Requested",
action: ACTIONS.REQUESTED,
disabled: true,
text: "Requested",
color: 'btn-info',
});
}
// 5. Rejected Regularization
if (activity === 5) {
return setStatus({
status: "Rejected",
action: ACTIONS.REJECTED,
disabled: true,
text: "Rejected",
color: 'btn-danger',
});
}
// Default to Approved if none of the above apply
return setStatus({
status: "Approved",
action: ACTIONS.APPROVED,
disabled: true,
text: "Approved",
color: 'btn-success',
});
}, [attendanceData]);
return status;
};
export default useAttendanceStatus;