346 lines
20 KiB
C#
346 lines
20 KiB
C#
using System;
|
|
using System.Data;
|
|
using HRM.BO;
|
|
using Ease.Core.DataAccess;
|
|
|
|
namespace HRM.DA
|
|
{
|
|
internal static class CalendarItemDA
|
|
{
|
|
#region Insert / Update
|
|
|
|
internal static void Insert(TransactionContext tc, CalendarItem item)
|
|
{
|
|
tc.ExecuteNonQuery(@"INSERT INTO CalendarItem (CalendarItemID, ItemType, Title, Description, Location, Color, Priority,
|
|
StartDateTime, EndDateTime, IsAllDay, RecurrenceRule, RecurrenceEndDate, ExceptionDates,
|
|
ReminderOffsets, ReminderChannel, NextTriggerAt, SourceItemID, SourceOccurrence,
|
|
OutlookSequence, OutlookEventID, PayrollTypeID, Status, CreatedBy, CreatedDate)
|
|
VALUES (%n, %n, %u, %u, %u, %s, %n,
|
|
%D, %D, %b, %s, %D, %s,
|
|
%s, %n, %D, %n, %D,
|
|
%n, %s, %n, %n, %n, %D)",
|
|
item.ID, (int)item.ItemType, item.Title, item.Description, item.Location, item.Color, (int?)item.Priority,
|
|
item.StartDateTime, item.EndDateTime, item.IsAllDay, item.RecurrenceRule, item.RecurrenceEndDate, item.ExceptionDates,
|
|
item.ReminderOffsets, (int?)item.ReminderChannel, item.NextTriggerAt, item.SourceItemID, item.SourceOccurrence,
|
|
item.OutlookSequence, item.OutlookEventID, item.PayrollTypeID, (int)item.Status, item.CreatedBy, item.CreatedDate);
|
|
}
|
|
|
|
internal static void Update(TransactionContext tc, CalendarItem item)
|
|
{
|
|
tc.ExecuteNonQuery(@"UPDATE CalendarItem SET Title = %u, Description = %u, Location = %u, Color = %s, Priority = %n,
|
|
StartDateTime = %D, EndDateTime = %D, IsAllDay = %b, RecurrenceRule = %s, RecurrenceEndDate = %D, ExceptionDates = %s,
|
|
ReminderOffsets = %s, ReminderChannel = %n, NextTriggerAt = %D,
|
|
OutlookSequence = %n, ModifiedBy = %n, ModifiedDate = %D
|
|
WHERE CalendarItemID = %n",
|
|
item.Title, item.Description, item.Location, item.Color, (int?)item.Priority,
|
|
item.StartDateTime, item.EndDateTime, item.IsAllDay, item.RecurrenceRule, item.RecurrenceEndDate, item.ExceptionDates,
|
|
item.ReminderOffsets, (int?)item.ReminderChannel, item.NextTriggerAt,
|
|
item.OutlookSequence, item.ModifiedBy, item.ModifiedDate,
|
|
item.ID);
|
|
}
|
|
|
|
internal static void UpdateStatus(TransactionContext tc, int calendarItemID, EnumCalendarItemStatus status,
|
|
int outlookSequence, DateTime? nextTriggerAt, int modifiedBy, DateTime modifiedDate)
|
|
{
|
|
tc.ExecuteNonQuery(@"UPDATE CalendarItem SET Status = %n, OutlookSequence = %n, NextTriggerAt = %D,
|
|
ModifiedBy = %n, ModifiedDate = %D
|
|
WHERE CalendarItemID = %n",
|
|
(int)status, outlookSequence, nextTriggerAt, modifiedBy, modifiedDate, calendarItemID);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Get
|
|
|
|
/// <summary>Organizer's display name: the employee name, or the user name for a non-employee organizer.</summary>
|
|
private const string OrganizerNameApply = @"
|
|
OUTER APPLY (SELECT TOP 1 COALESCE(oe.NAME, ou.USERNAME) AS OrganizerName
|
|
FROM CalendarItemAttendee oa
|
|
LEFT JOIN EMPLOYEE oe ON oe.EMPLOYEEID = oa.EmployeeID
|
|
LEFT JOIN Users ou ON ou.USERID = oa.UserID
|
|
WHERE oa.CalendarItemID = ci.CalendarItemID AND oa.Role = 1) org";
|
|
|
|
/// <summary>
|
|
/// The current user's own active attendee row. employeeID is 0 for a login without an employee,
|
|
/// which never matches a real EMPLOYEEID.
|
|
/// </summary>
|
|
private const string MyAttendeeApply = @"
|
|
CROSS APPLY (SELECT TOP 1 a.AttendeeID AS MyAttendeeID, a.Role AS MyRole, a.ResponseStatus AS MyResponseStatus,
|
|
a.TaskStatus AS MyTaskStatus, a.Remarks AS MyRemarks, a.RemarksDate AS MyRemarksDate,
|
|
a.IsRead AS MyIsRead, a.ReadDate AS MyReadDate,
|
|
a.TitleOverride AS MyTitleOverride, a.FromOverride AS MyFromOverride, a.ToOverride AS MyToOverride
|
|
FROM CalendarItemAttendee a
|
|
WHERE a.CalendarItemID = ci.CalendarItemID AND a.Status = 1
|
|
AND (a.EmployeeID = %n OR a.UserID = %n)
|
|
ORDER BY a.Role) me";
|
|
|
|
internal static IDataReader Get(TransactionContext tc, int calendarItemID)
|
|
{
|
|
return tc.ExecuteReader("SELECT ci.*, org.OrganizerName FROM CalendarItem ci" + OrganizerNameApply +
|
|
" WHERE ci.CalendarItemID = %n", calendarItemID);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Active Events and Tasks on which the user is an active attendee that can show in [fromDate, toDate): one-off
|
|
/// items overlapping the range, and repeating items whose series has started and not ended before it. The
|
|
/// service expands repeating items. Schedule jobs come from GetScheduleJobFeed (HR only, never their targets).
|
|
/// </summary>
|
|
internal static IDataReader GetFeed(TransactionContext tc, int employeeID, int userID, DateTime fromDate, DateTime toDate)
|
|
{
|
|
return tc.ExecuteReader("SELECT ci.*, me.* FROM CalendarItem ci" + MyAttendeeApply +
|
|
@" WHERE ci.Status = 1 AND ci.ItemType IN (1, 2)
|
|
AND ci.StartDateTime < %D
|
|
AND ( (ci.RecurrenceRule IS NULL AND ci.EndDateTime >= %D)
|
|
OR (ci.RecurrenceRule IS NOT NULL AND (ci.RecurrenceEndDate IS NULL OR ci.RecurrenceEndDate >= %D)))",
|
|
employeeID, userID, toDate, fromDate, fromDate);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Active Schedule Jobs (or Schedule Emails) of one payroll type that can run in [fromDate, toDate) (same range
|
|
/// rule as GetFeed), for HR: every HR user sees and manages all of them, not only the ones they set up. With
|
|
/// createdBy (a self-service user), only the ones that user set up.
|
|
/// </summary>
|
|
internal static IDataReader GetScheduleJobFeed(TransactionContext tc, EnumCalendarItemType itemType, int payrollTypeID,
|
|
DateTime fromDate, DateTime toDate, int? createdBy)
|
|
{
|
|
string sql = SQLParser.MakeSQL(@"SELECT ci.* FROM CalendarItem ci
|
|
WHERE ci.Status = 1 AND ci.ItemType = %n AND ci.PayrollTypeID = %n
|
|
AND ci.StartDateTime < %D
|
|
AND ( (ci.RecurrenceRule IS NULL AND ci.EndDateTime >= %D)
|
|
OR (ci.RecurrenceRule IS NOT NULL AND (ci.RecurrenceEndDate IS NULL OR ci.RecurrenceEndDate >= %D)))",
|
|
(int)itemType, payrollTypeID, toDate, fromDate, fromDate);
|
|
if (createdBy.HasValue)
|
|
sql += SQLParser.MakeSQL(" AND ci.CreatedBy = %n", createdBy.Value);
|
|
return tc.ExecuteReader(sql);
|
|
}
|
|
|
|
/// <summary>Active Events / Tasks whose next reminder is due, oldest first.</summary>
|
|
internal static IDataReader GetDueReminders(TransactionContext tc, DateTime now, int maxItems)
|
|
{
|
|
return tc.ExecuteReader(@"SELECT TOP (%n) * FROM CalendarItem
|
|
WHERE Status = 1 AND ItemType IN (1, 2) AND NextTriggerAt IS NOT NULL AND NextTriggerAt <= %D
|
|
ORDER BY NextTriggerAt",
|
|
maxItems, now);
|
|
}
|
|
|
|
/// <summary>Active Schedule Jobs (or Schedule Emails) whose next run is due, oldest first.</summary>
|
|
internal static IDataReader GetDueScheduleRuns(TransactionContext tc, EnumCalendarItemType itemType, DateTime now, int maxItems)
|
|
{
|
|
return tc.ExecuteReader(@"SELECT TOP (%n) * FROM CalendarItem
|
|
WHERE Status = 1 AND ItemType = %n AND NextTriggerAt IS NOT NULL AND NextTriggerAt <= %D
|
|
ORDER BY NextTriggerAt",
|
|
maxItems, (int)itemType, now);
|
|
}
|
|
|
|
/// <summary>The task a schedule job created for one run, or NULL when that run has no task yet.</summary>
|
|
internal static object GetTaskOfRun(TransactionContext tc, int jobID, DateTime occurrenceStart)
|
|
{
|
|
return tc.ExecuteScalar("SELECT CalendarItemID FROM CalendarItem WHERE SourceItemID = %n AND SourceOccurrence = %D",
|
|
jobID, occurrenceStart);
|
|
}
|
|
|
|
/// <summary>The latest tasks a schedule job created, with how many assignees each has and how many are done.</summary>
|
|
internal static IDataReader GetJobRuns(TransactionContext tc, int jobID, int maxRuns)
|
|
{
|
|
return tc.ExecuteReader(@"SELECT TOP (%n) t.CalendarItemID, t.SourceOccurrence, t.Status,
|
|
(SELECT COUNT(*) FROM CalendarItemAttendee a
|
|
WHERE a.CalendarItemID = t.CalendarItemID AND a.Status = 1 AND a.TaskStatus IS NOT NULL) AS AssigneeCount,
|
|
(SELECT COUNT(*) FROM CalendarItemAttendee a
|
|
WHERE a.CalendarItemID = t.CalendarItemID AND a.Status = 1 AND a.TaskStatus = %n) AS DoneCount
|
|
FROM CalendarItem t
|
|
WHERE t.SourceItemID = %n
|
|
ORDER BY t.SourceOccurrence DESC",
|
|
maxRuns, (int)EnumCalendarTaskStatus.Done, jobID);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Moves NextTriggerAt from <paramref name="current"/> to <paramref name="next"/> only if nobody moved it first.
|
|
/// Returns true for the one caller that wins, so two servers can never send the same reminder.
|
|
/// </summary>
|
|
internal static bool AdvanceTrigger(TransactionContext tc, int calendarItemID, DateTime current, DateTime? next)
|
|
{
|
|
object rows = tc.ExecuteScalar(@"UPDATE CalendarItem SET NextTriggerAt = %D
|
|
WHERE CalendarItemID = %n AND NextTriggerAt = %D;
|
|
SELECT @@ROWCOUNT;",
|
|
next, calendarItemID, current);
|
|
return Convert.ToInt32(rows) == 1;
|
|
}
|
|
|
|
/// <summary>Saves the skipped days of a repeating item (one occurrence cancelled or changed on its own).</summary>
|
|
internal static void UpdateExceptionDates(TransactionContext tc, int calendarItemID, string exceptionDates,
|
|
DateTime? nextTriggerAt, int outlookSequence, int modifiedBy, DateTime modifiedDate)
|
|
{
|
|
tc.ExecuteNonQuery(@"UPDATE CalendarItem SET ExceptionDates = %s, NextTriggerAt = %D, OutlookSequence = %n,
|
|
ModifiedBy = %n, ModifiedDate = %D
|
|
WHERE CalendarItemID = %n",
|
|
exceptionDates, nextTriggerAt, outlookSequence, modifiedBy, modifiedDate, calendarItemID);
|
|
}
|
|
|
|
/// <summary>Saves a repeating item's new repeat rule and skipped days (series shortened by "this and following").</summary>
|
|
internal static void UpdateRecurrence(TransactionContext tc, int calendarItemID, string recurrenceRule, DateTime? recurrenceEndDate,
|
|
string exceptionDates, DateTime? nextTriggerAt, int outlookSequence, int modifiedBy, DateTime modifiedDate)
|
|
{
|
|
tc.ExecuteNonQuery(@"UPDATE CalendarItem SET RecurrenceRule = %s, RecurrenceEndDate = %D, ExceptionDates = %s,
|
|
NextTriggerAt = %D, OutlookSequence = %n, ModifiedBy = %n, ModifiedDate = %D
|
|
WHERE CalendarItemID = %n",
|
|
recurrenceRule, recurrenceEndDate, exceptionDates, nextTriggerAt, outlookSequence, modifiedBy, modifiedDate,
|
|
calendarItemID);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Active tasks assigned to the user (rows with a task status: assignees, or an organizer who assigned the task
|
|
/// to themselves), optionally filtered by the user's own task status.
|
|
/// </summary>
|
|
internal static IDataReader GetMyTasks(TransactionContext tc, int employeeID, int userID, int? taskStatus)
|
|
{
|
|
string sql = "SELECT ci.*, me.*, org.OrganizerName FROM CalendarItem ci" + MyAttendeeApply + OrganizerNameApply +
|
|
@" WHERE ci.Status = 1 AND ci.ItemType = 2 AND me.MyTaskStatus IS NOT NULL";
|
|
if (taskStatus.HasValue)
|
|
return tc.ExecuteReader(sql + " AND me.MyTaskStatus = %n ORDER BY ci.EndDateTime",
|
|
employeeID, userID, taskStatus.Value);
|
|
|
|
return tc.ExecuteReader(sql + " ORDER BY ci.EndDateTime", employeeID, userID);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region Calendar layers (read-only data from existing modules)
|
|
|
|
/// <summary>Basic facts about the given employees. employeeIDs is a comma-separated list of ints built by code.</summary>
|
|
internal static IDataReader GetEmployeeBasics(TransactionContext tc, string employeeIDs)
|
|
{
|
|
return tc.ExecuteReader(@"SELECT EMPLOYEEID, NAME, EMPLOYEENO, EMAILADDRESS, LINEMANAGERID, DEPARTMENTID,
|
|
LOCATIONID, STATUS, PAYROLLTYPEID
|
|
FROM EMPLOYEE WHERE EMPLOYEEID IN (%q)", employeeIDs);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Users by ID (for attendees who are not employees). userIDs is a comma-separated list of ints built by code.
|
|
/// Email is the address entered on the user form (EmailAddress), or the older Email column when that is empty.
|
|
/// </summary>
|
|
internal static IDataReader GetUserBasics(TransactionContext tc, string userIDs)
|
|
{
|
|
return tc.ExecuteReader(@"SELECT USERID, LOGINID, USERNAME, USERTYPE, STATUS, EMPLOYEEID,
|
|
%q AS Email
|
|
FROM Users WHERE USERID IN (%q)",
|
|
UserEmailExpression(tc, string.Empty), userIDs);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Usable (Active or Approved) admin-side accounts, i.e. not self-service employee logins, for the participant picker.
|
|
/// Not-yet-approved, deleted, locked, archived and inactive accounts are left out.
|
|
/// </summary>
|
|
internal static IDataReader GetActiveUsers(TransactionContext tc)
|
|
{
|
|
return tc.ExecuteReader(@"SELECT u.USERID, u.LOGINID, u.USERNAME, u.EMPLOYEEID, e.EMPLOYEENO,
|
|
%q AS EmailAddress
|
|
FROM Users u
|
|
LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID = u.EMPLOYEEID
|
|
WHERE u.STATUS IN (%n, %n) AND u.USERTYPE != %n ORDER BY u.USERNAME",
|
|
UserEmailExpression(tc, "u."), (int)EnumAuthStatus.Active, (int)EnumAuthStatus.Approved, (int)EnumUserType.Employee);
|
|
}
|
|
|
|
/// <summary>Which e-mail columns this database's Users table has (read once per process).</summary>
|
|
private static (bool EmailAddress, bool Email)? _userEmailColumns;
|
|
|
|
/// <summary>
|
|
/// The SQL for a user's e-mail: EmailAddress (the user form's column), else the older Email column. Databases differ:
|
|
/// some have only the old Email (UserEmailAddress_DB_Changes.sql not run yet), some only EmailAddress, some both;
|
|
/// naming a missing column would fail the whole query, so only the columns that exist are used. The text is built
|
|
/// here from fixed column names only, so it is safe to splice with %q. prefix is a table alias with its dot, or empty.
|
|
/// </summary>
|
|
private static string UserEmailExpression(TransactionContext tc, string prefix)
|
|
{
|
|
if (!_userEmailColumns.HasValue)
|
|
{
|
|
object addressLength = tc.ExecuteScalar("SELECT COL_LENGTH('Users', 'EmailAddress')");
|
|
object emailLength = tc.ExecuteScalar("SELECT COL_LENGTH('Users', 'Email')");
|
|
_userEmailColumns = (addressLength != null && addressLength != DBNull.Value,
|
|
emailLength != null && emailLength != DBNull.Value);
|
|
}
|
|
|
|
var columns = _userEmailColumns.Value;
|
|
string address = "NULLIF(LTRIM(RTRIM(" + prefix + "EmailAddress)), '')";
|
|
string email = "NULLIF(LTRIM(RTRIM(" + prefix + "Email)), '')";
|
|
if (columns.EmailAddress && columns.Email)
|
|
return "COALESCE(" + address + ", " + email + ")";
|
|
if (columns.EmailAddress)
|
|
return address;
|
|
if (columns.Email)
|
|
return email;
|
|
return "CAST(NULL AS NVARCHAR(500))";
|
|
}
|
|
|
|
/// <summary>Departments by ID (to check a schedule job's targets). departmentIDs is a comma-separated list of ints built by code.</summary>
|
|
internal static IDataReader GetDepartments(TransactionContext tc, string departmentIDs)
|
|
{
|
|
return tc.ExecuteReader("SELECT DEPARTMENTID, DESCRIPTION FROM DEPARTMENT WHERE DEPARTMENTID IN (%q)", departmentIDs);
|
|
}
|
|
|
|
/// <summary>Live employees of the given departments. departmentIDs is a comma-separated list of ints built by code.</summary>
|
|
internal static IDataReader GetLiveEmployeesOfDepartments(TransactionContext tc, string departmentIDs, int payrollTypeID)
|
|
{
|
|
return tc.ExecuteReader(@"SELECT EMPLOYEEID, NAME, EMPLOYEENO, EMAILADDRESS, LINEMANAGERID, DEPARTMENTID,
|
|
LOCATIONID, STATUS, PAYROLLTYPEID
|
|
FROM EMPLOYEE WHERE DEPARTMENTID IN (%q) AND STATUS = %n AND PAYROLLTYPEID = %n",
|
|
departmentIDs, (int)EnumEmployeeStatus.Live, payrollTypeID);
|
|
}
|
|
|
|
/// <summary>
|
|
/// National / other holidays (Leave > National Holiday Setup, table AttnNationalHoliday) of one payroll type that
|
|
/// overlap the range: company-wide ones and, when a location is given, that location's. Read from the setup itself,
|
|
/// so the calendar is right for any year without HR running "Process Calender" first.
|
|
/// </summary>
|
|
internal static IDataReader GetNationalHolidays(TransactionContext tc, DateTime fromDate, DateTime toDate, int payrollTypeID,
|
|
int? locationID)
|
|
{
|
|
return tc.ExecuteReader(@"SELECT Description, FromDate, ToDate FROM AttnNationalHoliday
|
|
WHERE PayrollTypeID = %n AND FromDate <= %d AND ToDate >= %d
|
|
AND (LocationID IS NULL OR LocationID = 0 OR LocationID = %n)",
|
|
payrollTypeID, toDate, fromDate, locationID ?? 0);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The weekdays that are weekly holidays (Leave > Weekly Holiday Setup, table WeeklyHoliday): company-wide ones and,
|
|
/// when a location is given, that location's. DateType is 1 = Sunday ... 7 = Saturday (HolidayDayOfWeek).
|
|
/// </summary>
|
|
internal static IDataReader GetWeeklyHolidays(TransactionContext tc, int? locationID)
|
|
{
|
|
return tc.ExecuteReader(@"SELECT DISTINCT DateType FROM WeeklyHoliday
|
|
WHERE LocationID IS NULL OR LocationID = 0 OR LocationID = %n",
|
|
locationID ?? 0);
|
|
}
|
|
|
|
/// <summary>The employee's own approved or availed leave overlapping the range.</summary>
|
|
internal static IDataReader GetApprovedLeaves(TransactionContext tc, int employeeID, DateTime fromDate, DateTime toDate)
|
|
{
|
|
return tc.ExecuteReader(@"SELECT le.TRANID, l.DESCRIPTION AS LeaveName,
|
|
COALESCE(le.APRFROMDATE, le.APPFROMDATE) AS FromDate,
|
|
COALESCE(le.APRTODATE, le.APPTODATE) AS ToDate
|
|
FROM LEAVEENTRY le
|
|
LEFT JOIN LEAVE l ON l.LEAVEID = le.LEAVEID
|
|
WHERE le.EMPID = %n AND le.LEAVESTATUS IN (%n, %n)
|
|
AND COALESCE(le.APRFROMDATE, le.APPFROMDATE) <= %d
|
|
AND COALESCE(le.APRTODATE, le.APPTODATE) >= %d",
|
|
employeeID, (int)EnumLeaveStatus.Approved, (int)EnumLeaveStatus.Availed, toDate, fromDate);
|
|
}
|
|
|
|
/// <summary>The employee's own processed daily attendance (DAILYATTNPROCESS) for the days in [fromDate, toDate).</summary>
|
|
internal static IDataReader GetAttendance(TransactionContext tc, int employeeID, DateTime fromDate, DateTime toDate)
|
|
{
|
|
return tc.ExecuteReader(@"SELECT AttnDate, AttenType, InTime, OutTime, IsLate FROM DAILYATTNPROCESS
|
|
WHERE EmployeeID = %n AND AttnDate >= %d AND AttnDate < %d",
|
|
employeeID, fromDate, toDate);
|
|
}
|
|
|
|
/// <summary>The employee's own birth and joining dates, for the birthday and work-anniversary layers (everyone sees only their own).</summary>
|
|
internal static IDataReader GetOwnDates(TransactionContext tc, int employeeID)
|
|
{
|
|
return tc.ExecuteReader("SELECT EMPLOYEEID, NAME, BIRTHDATE, JOININGDATE FROM EMPLOYEE WHERE EMPLOYEEID = %n",
|
|
employeeID);
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
}
|