HRM-10/db/Script/AttendanceLeaveSummaryLM_DB_Changes.sql

390 lines
17 KiB
MySQL
Raw Normal View History

2026-11-03 13:06:00 +06:00
/* ============================================================================
Team Attendance & Leave Summary for a Line Manager
----------------------------------------------------------------------------
Rewrite of dbo.usp_EmployeeAttendanceLeaveSummaryLM.
Returns TWO result sets:
1. One row per active team member -> the "Team Summary" grid
2. One row per calendar month -> the "Absent vs Late" trend chart
Both are built from a single pass over DailyAttnProcess (#AttnDay), so the
two cards on the screen cost one round trip and one read of the big table.
Run order:
1. Indexes (section 1) - these are what actually make it fast on
DailyAttnProcess. Run them first, off-peak.
2. Stored procedure (section 2).
WFMovementTran is deliberately not touched - leave state is read from
LeaveEntry.LeaveStatus, which is the reliable source.
Concurrency: the Team Attendance approve screen inserts/updates
DailyAttnProcess while managers read this summary, so every table is read
WITH (NOLOCK). That is a dirty read - an uncommitted row can be counted and
a rolled-back one can show up. Accepted deliberately here: this is a
reporting summary, not a figure anything is posted from.
============================================================================ */
/* ============================================================================
SECTION 1 - SUPPORTING INDEXES
----------------------------------------------------------------------------
The covering index on DailyAttnProcess is the single biggest win: it turns a
full scan of a very large table into a seek per team member, and every
column the procedure reads is in the index, so there are no key lookups.
Each is guarded, so this script is safe to re-run. Creating an index on a
large table locks it unless you are on Enterprise Edition, where you can add
WITH (ONLINE = ON).
============================================================================ */
IF NOT EXISTS (SELECT 1 FROM sys.indexes
WHERE name = 'IX_DailyAttnProcess_Employee_AttnDate'
AND object_id = OBJECT_ID('dbo.DailyAttnProcess'))
BEGIN
CREATE NONCLUSTERED INDEX IX_DailyAttnProcess_Employee_AttnDate
ON dbo.DailyAttnProcess (EmployeeID, AttnDate)
INCLUDE (AttenType, IsLate, LateHour, EarlyHour);
END;
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes
WHERE name = 'IX_Employee_LineManager_Status'
AND object_id = OBJECT_ID('dbo.Employee'))
BEGIN
CREATE NONCLUSTERED INDEX IX_Employee_LineManager_Status
ON dbo.Employee (LineManagerID, Status)
INCLUDE (EmployeeNo, Name, DepartmentID, DesignationID, GradeID);
END;
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes
WHERE name = 'IX_LeaveEntry_Emp_AprDates'
AND object_id = OBJECT_ID('dbo.LeaveEntry'))
BEGIN
CREATE NONCLUSTERED INDEX IX_LeaveEntry_Emp_AprDates
ON dbo.LeaveEntry (EMPID, APRFROMDATE, APRTODATE)
INCLUDE (LEAVESTATUS, APRTOTALDAYS, ISDRAFTED);
END;
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes
WHERE name = 'IX_EmpLeaveStatus_Emp_LeaveYear'
AND object_id = OBJECT_ID('dbo.EmpLeaveStatus'))
BEGIN
CREATE NONCLUSTERED INDEX IX_EmpLeaveStatus_Emp_LeaveYear
ON dbo.EmpLeaveStatus (EmpId, LeaveYearID)
INCLUDE (YearEndBalance);
END;
GO
/* ============================================================================
SECTION 2 - STORED PROCEDURE
============================================================================ */
IF OBJECT_ID('dbo.usp_EmployeeAttendanceLeaveSummaryLM', 'P') IS NULL
EXEC('CREATE PROCEDURE dbo.usp_EmployeeAttendanceLeaveSummaryLM AS SET NOCOUNT ON;');
GO
ALTER PROCEDURE dbo.usp_EmployeeAttendanceLeaveSummaryLM
(
@FromDate DATE,
@ToDate DATE,
@Empid INT -- line manager EmployeeID
)
AS
BEGIN
SET NOCOUNT ON;
/* ---- validation ---------------------------------------------------- */
IF @FromDate IS NULL OR @ToDate IS NULL
THROW 50001, 'FromDate and ToDate are required.', 1;
IF @FromDate > @ToDate
THROW 50002, 'FromDate cannot be greater than ToDate.', 1;
IF @Empid IS NULL OR @Empid <= 0
THROW 50003, 'A valid line manager EmployeeID is required.', 1;
/* Half-open range: keeps the predicate SARGable even when AttnDate is a
datetime carrying a time component, so the index seek is still used. */
DECLARE @ToDateExclusive DATE = DATEADD(DAY, 1, @ToDate);
/* ---- constants (HRM.BO EnumAttendanceType) -------------------------- */
DECLARE @AttnPresent INT = 1,
@AttnAbsent INT = 2,
@AttnDelay INT = 3,
@AttnLeave INT = 4,
@AttnHoliday INT = 5,
@AttnOutDuty INT = 7,
@AttnWeeklyOff INT = 8;
/* ---- constants (HRM.BO EnumLeaveStatus) ----------------------------- */
DECLARE @LeaveDrafted INT = 0,
@LeaveOnApproval INT = 1,
@LeaveReverted INT = 3,
@LeaveDeclined INT = 4,
@LeaveAvailed INT = 5,
@LeaveApproved INT = 6,
@LeaveCancel INT = 10,
@LeaveCancelledByUser INT = 11;
/* ====================================================================
STEP 1 - the team reporting to this manager
Resolved once into a temp table. Everything downstream joins against
it, so the big tables get probed by employee instead of scanned.
==================================================================== */
CREATE TABLE #Team
(
EmployeeID INT NOT NULL PRIMARY KEY,
EmployeeNo NVARCHAR(50) NULL,
EmployeeName NVARCHAR(200) NULL,
DesignationName NVARCHAR(200) NULL,
DepartmentName NVARCHAR(200) NULL,
GradeName NVARCHAR(200) NULL
);
INSERT INTO #Team
(EmployeeID, EmployeeNo, EmployeeName, DesignationName, DepartmentName, GradeName)
SELECT e.EmployeeID,
e.EmployeeNo,
e.Name,
des.Name,
dept.Description,
g.Description
FROM dbo.Employee AS e WITH (NOLOCK)
LEFT JOIN dbo.Designation AS des WITH (NOLOCK) ON des.DesignationID = e.DesignationID
LEFT JOIN dbo.Department AS dept WITH (NOLOCK) ON dept.DepartmentID = e.DepartmentID
LEFT JOIN dbo.Grades AS g WITH (NOLOCK) ON g.GradeID = e.GradeID
WHERE e.LineManagerID = @Empid
AND e.Status = 1; -- active employees only
/* ====================================================================
STEP 2 - attendance, one row per employee per day
This is the only read of DailyAttnProcess, and both result sets are
built from it. The table should hold one row per employee per day, but
the regularization workflow can leave more than one behind; grouping by
day means a duplicate cannot inflate the counts.
==================================================================== */
CREATE TABLE #AttnDay
(
EmployeeID INT NOT NULL,
AttnDay DATE NOT NULL,
IsPresent INT NOT NULL,
IsAbsent INT NOT NULL,
IsDelay INT NOT NULL,
IsLeave INT NOT NULL,
IsHoliday INT NOT NULL,
IsWeeklyOff INT NOT NULL,
IsOutDuty INT NOT NULL,
IsLateDay INT NOT NULL,
IsEarly INT NOT NULL,
LateHour DECIMAL(10, 2) NOT NULL,
EarlyHour DECIMAL(10, 2) NOT NULL,
PRIMARY KEY (EmployeeID, AttnDay)
);
INSERT INTO #AttnDay
(EmployeeID, AttnDay, IsPresent, IsAbsent, IsDelay, IsLeave, IsHoliday,
IsWeeklyOff, IsOutDuty, IsLateDay, IsEarly, LateHour, EarlyHour)
SELECT dap.EmployeeID,
CAST(dap.AttnDate AS DATE),
MAX(CASE WHEN dap.AttenType = @AttnPresent THEN 1 ELSE 0 END),
MAX(CASE WHEN dap.AttenType = @AttnAbsent THEN 1 ELSE 0 END),
MAX(CASE WHEN dap.AttenType = @AttnDelay THEN 1 ELSE 0 END),
MAX(CASE WHEN dap.AttenType = @AttnLeave THEN 1 ELSE 0 END),
MAX(CASE WHEN dap.AttenType = @AttnHoliday THEN 1 ELSE 0 END),
MAX(CASE WHEN dap.AttenType = @AttnWeeklyOff THEN 1 ELSE 0 END),
MAX(CASE WHEN dap.AttenType = @AttnOutDuty THEN 1 ELSE 0 END),
MAX(CASE WHEN dap.IsLate = 1 THEN 1 ELSE 0 END),
MAX(CASE WHEN ISNULL(dap.EarlyHour, 0) > 0 THEN 1 ELSE 0 END),
MAX(CAST(ISNULL(dap.LateHour, 0) AS DECIMAL(10, 2))),
MAX(CAST(ISNULL(dap.EarlyHour, 0) AS DECIMAL(10, 2)))
FROM dbo.DailyAttnProcess AS dap WITH (NOLOCK)
INNER JOIN #Team AS t ON t.EmployeeID = dap.EmployeeID
WHERE dap.AttnDate >= @FromDate
AND dap.AttnDate < @ToDateExclusive
GROUP BY dap.EmployeeID, CAST(dap.AttnDate AS DATE)
OPTION (RECOMPILE); /* date range and team size vary a lot between calls */
/* ====================================================================
STEP 3 - leave, straight from LeaveEntry in one aggregation
Filtered by the team here, which the original did not do - it read
every LeaveEntry row in the range for the whole company.
Ranged on APRFROMDATE/APRTODATE, matching the original. Safe because
LeaveEntryService seeds ApprovedFromDate from AppliedFromDate on entry
and maps AprFromDate with .Value, so the column is never null. Wrapping
these in COALESCE(APRFROMDATE, APPFROMDATE) would defeat the index seek.
CROSS APPLY computes the day count once and the SUMs reuse it, instead
of repeating that CASE expression in every aggregate.
==================================================================== */
CREATE TABLE #Leave
(
EMPID INT NOT NULL PRIMARY KEY,
LeaveRequests INT NOT NULL,
Applied DECIMAL(10, 2) NOT NULL,
LeaveApproved DECIMAL(10, 2) NOT NULL,
LeavePendingApproval DECIMAL(10, 2) NOT NULL,
LeaveDeclined DECIMAL(10, 2) NOT NULL
);
INSERT INTO #Leave
(EMPID, LeaveRequests, Applied, LeaveApproved, LeavePendingApproval, LeaveDeclined)
SELECT le.EMPID,
COUNT(*),
SUM(d.Days),
SUM(CASE WHEN le.LEAVESTATUS IN (@LeaveApproved, @LeaveAvailed) THEN d.Days ELSE 0 END),
SUM(CASE WHEN le.LEAVESTATUS IN (@LeaveOnApproval, @LeaveReverted) THEN d.Days ELSE 0 END),
SUM(CASE WHEN le.LEAVESTATUS = @LeaveDeclined THEN d.Days ELSE 0 END)
FROM dbo.LeaveEntry AS le WITH (NOLOCK)
INNER JOIN #Team AS t ON t.EmployeeID = le.EMPID
CROSS APPLY
(
SELECT Days =
/* Whole leave inside the range -> use APRTOTALDAYS, which
already accounts for half-days. Partly outside -> fall back
to clipped calendar days, which does not. */
CASE
WHEN CAST(le.APRFROMDATE AS DATE) >= @FromDate
AND CAST(le.APRTODATE AS DATE) <= @ToDate
AND ISNULL(le.APRTOTALDAYS, 0) > 0
THEN CAST(le.APRTOTALDAYS AS DECIMAL(10, 2))
ELSE CAST(DATEDIFF
(
DAY,
CASE WHEN CAST(le.APRFROMDATE AS DATE) < @FromDate
THEN @FromDate ELSE CAST(le.APRFROMDATE AS DATE) END,
CASE WHEN CAST(le.APRTODATE AS DATE) > @ToDate
THEN @ToDate ELSE CAST(le.APRTODATE AS DATE) END
) + 1 AS DECIMAL(10, 2))
END
) AS d
WHERE le.APRFROMDATE < @ToDateExclusive
AND le.APRTODATE >= @FromDate
AND ISNULL(le.ISDRAFTED, 0) = 0
AND ISNULL(le.LEAVESTATUS, @LeaveOnApproval)
NOT IN (@LeaveDrafted, @LeaveCancel, @LeaveCancelledByUser)
GROUP BY le.EMPID
OPTION (RECOMPILE);
/* ====================================================================
STEP 4 - remaining leave balance ("Rem" on the grid)
EmpLeaveStatus.YearEndBalance is what the Leave Balance screen shows as
"Closing Balance" (EmpLeaveStatus.ClosingBalance just returns it), so
the number here matches what the employee sees there. Summed across
leave types for the current leave year.
==================================================================== */
CREATE TABLE #Balance
(
EmpId INT NOT NULL PRIMARY KEY,
RemainingLeave DECIMAL(10, 2) NOT NULL
);
INSERT INTO #Balance (EmpId, RemainingLeave)
SELECT els.EmpId,
CAST(SUM(ISNULL(els.YearEndBalance, 0)) AS DECIMAL(10, 2))
FROM dbo.EmpLeaveStatus AS els WITH (NOLOCK)
INNER JOIN #Team AS t ON t.EmployeeID = els.EmpId
INNER JOIN dbo.LeaveYear AS ly WITH (NOLOCK)
ON ly.LeaveYearID = els.LeaveYearID
AND ly.IsCurrent = 1
GROUP BY els.EmpId;
/* ====================================================================
RESULT SET 1 - one row per team member (Team Summary grid)
Driven from #Team, so a team member with leave but no absence still
appears. The original started from Employee and then filtered on
"Absent > 0", which silently dropped those people - and was also the
only thing restricting the result to this manager team.
==================================================================== */
SELECT t.EmployeeID,
t.EmployeeNo AS CIF,
t.EmployeeName,
t.DesignationName,
t.DepartmentName,
t.GradeName,
/* attendance */
ISNULL(a.PresentDays, 0) AS PresentDays,
ISNULL(a.AbsentDays, 0) AS Absent,
ISNULL(a.LateDays, 0) AS LateDays,
ISNULL(a.DelayDays, 0) AS DelayDays,
ISNULL(a.TotalLateHours, 0) AS TotalLateHours,
ISNULL(a.EarlyDays, 0) AS EarlyDays,
ISNULL(a.TotalEarlyHours, 0) AS TotalEarlyHours,
ISNULL(a.LeaveDaysInAttendance, 0) AS LeaveDaysInAttendance,
ISNULL(a.HolidayDays, 0) AS HolidayDays,
ISNULL(a.WeeklyOffDays, 0) AS WeeklyOffDays,
ISNULL(a.OutsideDutyDays, 0) AS OutsideDutyDays,
ISNULL(a.RecordedDays, 0) AS AttendanceRecordedDays,
/* leave */
ISNULL(l.LeaveRequests, 0) AS LeaveRequests,
ISNULL(l.Applied, 0) AS Applied,
ISNULL(l.LeaveApproved, 0) AS LeaveApproved,
ISNULL(l.LeavePendingApproval, 0) AS LeavePendingApproval,
ISNULL(l.LeaveDeclined, 0) AS LeaveDeclined,
ISNULL(b.RemainingLeave, 0) AS RemainingLeave,
/* absences not applied for yet - floored at 0, the original could
report a negative number here */
CASE WHEN ISNULL(a.AbsentDays, 0) > ISNULL(l.Applied, 0)
THEN ISNULL(a.AbsentDays, 0) - ISNULL(l.Applied, 0)
ELSE 0
END AS PendingApplicationbyEmployee
FROM #Team AS t
LEFT JOIN
(
SELECT ad.EmployeeID,
SUM(ad.IsPresent) AS PresentDays,
SUM(ad.IsAbsent) AS AbsentDays,
SUM(ad.IsLateDay) AS LateDays,
SUM(ad.IsDelay) AS DelayDays,
SUM(ad.IsEarly) AS EarlyDays,
SUM(ad.IsLeave) AS LeaveDaysInAttendance,
SUM(ad.IsHoliday) AS HolidayDays,
SUM(ad.IsWeeklyOff) AS WeeklyOffDays,
SUM(ad.IsOutDuty) AS OutsideDutyDays,
COUNT(*) AS RecordedDays,
CAST(SUM(ad.LateHour) AS DECIMAL(10, 2)) AS TotalLateHours,
CAST(SUM(ad.EarlyHour) AS DECIMAL(10, 2)) AS TotalEarlyHours
FROM #AttnDay AS ad
GROUP BY ad.EmployeeID
) AS a ON a.EmployeeID = t.EmployeeID
LEFT JOIN #Leave AS l ON l.EMPID = t.EmployeeID
LEFT JOIN #Balance AS b ON b.EmpId = t.EmployeeID
ORDER BY t.DepartmentName, t.EmployeeName;
/* ====================================================================
RESULT SET 2 - one row per calendar month (Absent vs Late chart)
Team-wide totals, read off the same #AttnDay pass. Months with no
attendance rows at all simply do not appear; the chart plots what it
is given.
==================================================================== */
SELECT DATEFROMPARTS(YEAR(ad.AttnDay), MONTH(ad.AttnDay), 1) AS MonthStart,
DATENAME(MONTH, DATEFROMPARTS(YEAR(ad.AttnDay), MONTH(ad.AttnDay), 1)) AS MonthName,
YEAR(ad.AttnDay) AS MonthYear,
SUM(ad.IsAbsent) AS AbsentDays,
SUM(ad.IsLateDay) AS LateDays
FROM #AttnDay AS ad
GROUP BY YEAR(ad.AttnDay), MONTH(ad.AttnDay)
ORDER BY MonthStart;
DROP TABLE #Balance;
DROP TABLE #Leave;
DROP TABLE #AttnDay;
DROP TABLE #Team;
END;
GO