using System;
using System.Collections.Generic;
using System.Linq;
namespace HRM.BO
{
#region CalendarItem
///
/// An Event, Task, Schedule Job or Schedule Email on the HRM calendar (table dbo.CalendarItem).
/// A Schedule Email keeps its subject in Title and its body in Description.
/// The organizer is CreatedBy; the organizer is also stored as an attendee with Role = Organizer.
///
public class CalendarItem : AuditTrailBase
{
#region Constructor
public CalendarItem()
{
ItemType = EnumCalendarItemType.Event;
Title = string.Empty;
IsAllDay = false;
Status = EnumCalendarItemStatus.Active;
OutlookSequence = 0;
Attendees = new List();
}
#endregion
#region Properties
public EnumCalendarItemType ItemType { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Location { get; set; }
public string Color { get; set; }
public EnumCalendarPriority? Priority { get; set; }
public DateTime StartDateTime { get; set; }
public DateTime EndDateTime { get; set; }
public bool IsAllDay { get; set; }
public string RecurrenceRule { get; set; }
public DateTime? RecurrenceEndDate { get; set; }
public string ExceptionDates { get; set; }
/// Minutes before the start, comma separated, e.g. "4320,60".
public string ReminderOffsets { get; set; }
public EnumReminderChannel? ReminderChannel { get; set; }
public DateTime? NextTriggerAt { get; set; }
public int? SourceItemID { get; set; }
public DateTime? SourceOccurrence { get; set; }
public int OutlookSequence { get; set; }
public string OutlookEventID { get; set; }
public int PayrollTypeID { get; set; }
public EnumCalendarItemStatus Status { get; set; }
public List Attendees { get; set; }
#endregion
#region Display-only properties (not stored in CalendarItem)
public string OrganizerName { get; set; }
/// Schedule jobs only: the latest tasks the job created (filled when the job is opened).
public List RecentRuns { get; set; }
/// Schedule emails only: the latest runs with their sent / failed counts (filled when it is opened).
public List RecentEmailRuns { get; set; }
/// Schedule emails only: the stored attachment's file name, or null when it has none.
public string AttachmentName { get; set; }
/// Schedule emails only: the stored attachment's size in bytes.
public int? AttachmentSize { get; set; }
/// Request only (schedule email): a new attachment, base64. Replaces the stored one.
public string AttachmentData { get; set; }
/// Request only (schedule email): true drops the stored attachment (ignored when AttachmentData is given).
public bool RemoveAttachment { get; set; }
/// The current user's own attendee row, filled by "my" queries.
public CalendarItemAttendee MyAttendee { get; set; }
///
/// Request only: when saving changes to part of a repeating item, the start of the occurrence that was clicked.
/// With EditScope ThisOccurrence (the default) the series skips that day and the changes become a new one-off item;
/// with ThisAndFollowing the series ends before that day and the changes become a new series from it.
///
public DateTime? OccurrenceStart { get; set; }
/// Request only: which dates of a repeating item the change applies to, together with OccurrenceStart.
public EnumCalendarEditScope? EditScope { get; set; }
#endregion
#region Functions
///
/// Parses ReminderOffsets into minutes. Returns an empty list when there is no reminder.
/// Throws ArgumentException for anything that is not a list of non-negative whole minutes.
///
public List GetReminderOffsetMinutes()
{
List offsets = new List();
if (string.IsNullOrWhiteSpace(ReminderOffsets))
return offsets;
foreach (string part in ReminderOffsets.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
if (!int.TryParse(part.Trim(), out int minutes) || minutes < 0)
throw new ArgumentException("Reminder time is not valid.");
if (!offsets.Contains(minutes))
offsets.Add(minutes);
}
return offsets.OrderByDescending(x => x).ToList();
}
#endregion
}
#endregion
#region CalendarItemAttendee
///
/// One person (or, for Schedule Job targets, one department) on a calendar item
/// (table dbo.CalendarItemAttendee), with that person's own response, task status and remarks.
///
public class CalendarItemAttendee : AuditTrailBase
{
#region Constructor
public CalendarItemAttendee()
{
AttendeeType = EnumAttendeeType.Employee;
Role = EnumAttendeeRole.Required;
ResponseStatus = EnumResponseStatus.Pending;
IsRead = false;
Status = EnumAttendeeStatus.Active;
}
#endregion
#region Properties
public int CalendarItemID { get; set; }
public EnumAttendeeType AttendeeType { get; set; }
public int? EmployeeID { get; set; }
public int? UserID { get; set; }
public int? DepartmentID { get; set; }
public string Email { get; set; }
public EnumAttendeeRole Role { get; set; }
public string TitleOverride { get; set; }
public string SubjectOverride { get; set; }
public DateTime? FromOverride { get; set; }
public DateTime? ToOverride { get; set; }
public EnumResponseStatus ResponseStatus { get; set; }
public EnumCalendarTaskStatus? TaskStatus { get; set; }
public string Remarks { get; set; }
public DateTime? RemarksDate { get; set; }
public bool IsRead { get; set; }
public DateTime? ReadDate { get; set; }
public DateTime? LastReminderAt { get; set; }
public int? InviteSentSequence { get; set; }
public EnumAttendeeStatus Status { get; set; }
#endregion
#region Display-only properties
public string Name { get; set; }
public string EmployeeNo { get; set; }
public string DepartmentName { get; set; }
#endregion
}
#endregion
#region Calendar feed and requests
///
/// One entry the calendar screen draws: an Event/Task occurrence or a read-only
/// holiday / leave / birthday / anniversary entry.
///
public class CalendarFeedItem
{
/// Unique key for the screen, e.g. "item-12", "holiday-2026-10-16".
public string Key { get; set; }
public EnumCalendarLayer Layer { get; set; }
public int? CalendarItemID { get; set; }
public string Title { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public bool IsAllDay { get; set; }
public string Color { get; set; }
public bool CanEdit { get; set; }
public EnumCalendarPriority? Priority { get; set; }
public EnumResponseStatus? ResponseStatus { get; set; }
public EnumCalendarTaskStatus? TaskStatus { get; set; }
/// True when this entry is one occurrence of a repeating item.
public bool IsRecurring { get; set; }
/// Start of this occurrence (needed to change or skip just this one).
public DateTime? OccurrenceStart { get; set; }
}
/// A reminder the dispatcher found due: which item, which occurrence, and the reminder moment.
public class CalendarDueReminder
{
public int CalendarItemID { get; set; }
public DateTime TriggerAt { get; set; }
public DateTime OccurrenceStart { get; set; }
public DateTime OccurrenceEnd { get; set; }
}
/// A schedule-job run the dispatcher found due: which job, and the run moment (the task's start).
public class CalendarDueRun
{
public int CalendarItemID { get; set; }
public DateTime OccurrenceStart { get; set; }
}
/// One person a schedule job would give a task to (employee, or a user account without an employee).
public class CalendarJobTarget
{
public int? EmployeeID { get; set; }
public int? UserID { get; set; }
public string Name { get; set; }
public string EmployeeNo { get; set; }
public int? DepartmentID { get; set; }
/// Schedule emails only: where the e-mail would go (empty = the person would be skipped).
public string Email { get; set; }
}
/// "Test run" of a schedule job or schedule email: who would get it right now, and when it runs next.
public class CalendarJobPreview
{
public List Targets { get; set; } = new List();
/// The next few run moments (empty when the job never runs again).
public List NextRuns { get; set; } = new List();
/// Schedule emails only: the subject and body as the first person would get them (tags filled in).
public string SampleSubject { get; set; }
public string SampleBody { get; set; }
/// Schedule emails only: whose data the sample shows.
public string SampleFor { get; set; }
}
/// What one run of a schedule job did.
public class CalendarJobRunResult
{
/// The task of this run (new, or the one an earlier attempt already created); 0 when none.
public int TaskID { get; set; }
/// True when this call created the task (so its people still have to be told).
public bool Created { get; set; }
public int AssigneeCount { get; set; }
/// Why no task was created, when it was not.
public string Message { get; set; }
}
///
/// What one run of a schedule email did: the e-mail batch it created in the central e-mail log (MasterEmailLog),
/// which Mail Manager's Mail Log History shows and can retry.
///
public class CalendarEmailRunResult
{
/// The e-mail batch of this run (new, or the one an earlier attempt already created); 0 when none.
public int MasterEmailLogID { get; set; }
/// True when this call created the batch.
public bool Created { get; set; }
public int RecipientCount { get; set; }
public DateTime RunAt { get; set; }
/// Why no batch was created, when it was not.
public string Message { get; set; }
/// System use: who set the schedule email up (the batch is logged as theirs).
[Newtonsoft.Json.JsonIgnore]
public int CreatedBy { get; set; }
/// System use: the one file every recipient of the batch gets, or null.
[Newtonsoft.Json.JsonIgnore]
public EmailAttachmentInfo Attachment { get; set; }
}
/// One run of a schedule email, with its e-mail batch's counts (read from the recipient rows).
public class CalendarEmailRun
{
public DateTime RunAt { get; set; }
public int? MasterEmailLogID { get; set; }
public int TotalCount { get; set; }
public int SentCount { get; set; }
public int FailedCount { get; set; }
public int SkippedCount { get; set; }
public int PendingCount { get; set; }
}
/// A task a schedule job created, with its progress.
public class CalendarJobRun
{
public int TaskID { get; set; }
public DateTime RunAt { get; set; }
public EnumCalendarItemStatus Status { get; set; }
public int AssigneeCount { get; set; }
public int DoneCount { get; set; }
}
///
/// An active admin-side user account the organizer can add as a participant.
/// Deliberately small: never carries password or other account details to the browser.
///
public class CalendarUserOption
{
public int UserID { get; set; }
public string LoginID { get; set; }
public string UserName { get; set; }
/// The user's EmailAddress (or the older Email column when that is empty): where their invitations go.
public string EmailAddress { get; set; }
/// Set when the account belongs to an employee; such a pick is stored as that employee.
public int? EmployeeID { get; set; }
/// That employee's number (shown instead of the login for an employee's account).
public string EmployeeNo { get; set; }
}
/// What a save did, so the right people are told about it afterwards.
public class CalendarSaveResult
{
/// The item that was saved (a new item when one occurrence or the following dates were changed).
public int CalendarItemID { get; set; }
/// The repeating item that was changed along the way (skipped day or shortened series), if any.
public int? SeriesID { get; set; }
///
/// True when what everyone sees changed (title, time, place, repeat...) or the item is new; false when only
/// people were added or removed, or someone's own title or dates changed, so only those people need telling.
///
public bool DetailsChanged { get; set; }
}
///
/// The sidebar's look around today: what is still running or coming in the next days (Items, in time order), what
/// already ended in the past days (Recent, newest first), and the open-task count. Every layer is included
/// (events, tasks, leave, attendance, holidays, weekly holidays, birthdays), schedule-job runs aside.
///
public class CalendarUpcoming
{
/// Entries not ended yet that start within the next days (today's included).
public List Items { get; set; } = new List();
/// Entries that ended within the past days (yesterday's attendance, last week's leave...).
public List Recent { get; set; } = new List();
/// Tasks assigned to the user that are not done yet.
public int OpenTaskCount { get; set; }
}
/// What the logged-in user may do, so the screen offers only what the server allows.
public class CalendarOptions
{
/// HR / admin logins, while Calendar:ScheduleJobsEnabled is on.
public bool CanCreateScheduleJobs { get; set; }
/// HR / admin logins, while Calendar:ScheduleEmailsEnabled is on.
public bool CanCreateScheduleEmails { get; set; }
/// The tags a schedule email's subject and body may use, each filled in per recipient.
public List EmailTags { get; set; } = new List();
}
/// A tag of a schedule email's subject or body, e.g. "<EMP-NAME>", and what it is replaced with.
public class CalendarEmailTag
{
public string Tag { get; set; }
public string Description { get; set; }
}
public class CalendarRespondRequest
{
public int CalendarItemID { get; set; }
public EnumResponseStatus ResponseStatus { get; set; }
}
public class CalendarTaskStatusRequest
{
public int CalendarItemID { get; set; }
public EnumCalendarTaskStatus TaskStatus { get; set; }
public string Remarks { get; set; }
}
#endregion
#region ICalendarItemService
///
/// All calendar operations. Every method takes the logged-in user and enforces
/// its own permission checks; callers must not rely on the menu for security.
/// Validation problems surface as ArgumentException and permission problems as
/// UnauthorizedAccessException (both wrapped in ServiceException).
///
public interface ICalendarItemService
{
List GetFeed(CurrentUser user, DateTime fromDate, DateTime toDate, List layers);
/// Everything on the user's calendar in the given number of days before and after now (see CalendarUpcoming).
CalendarUpcoming GetUpcoming(CurrentUser user, int days);
/// What the user may do on the calendar screen.
CalendarOptions GetOptions(CurrentUser user);
CalendarItem Get(CurrentUser user, int id);
CalendarSaveResult Save(CurrentUser user, CalendarItem item);
///
/// Cancels the whole item; with occurrenceStart, only that occurrence (scope ThisOccurrence, the default) or that
/// occurrence and all after it (ThisAndFollowing). Returns Cancelled when the item is gone for everyone,
/// Updated when a repeating item only lost some dates.
///
EnumCalendarChange Cancel(CurrentUser user, int id, DateTime? occurrenceStart, EnumCalendarEditScope? scope);
/// Saves the user's Yes / No / Maybe. Returns the user's attendee row ID.
int Respond(CurrentUser user, int calendarItemID, EnumResponseStatus responseStatus);
/// Saves the user's task status and remarks. Returns the user's attendee row ID.
int UpdateTaskStatus(CurrentUser user, int calendarItemID, EnumCalendarTaskStatus taskStatus, string remarks);
void MarkRead(CurrentUser user, int calendarItemID);
List GetMyTasks(CurrentUser user, EnumCalendarTaskStatus? taskStatus);
List GetActiveUsers(CurrentUser user);
/// HR: who an unsaved (or saved) schedule job would give a task to right now, and its next run moments.
CalendarJobPreview PreviewScheduleJob(CurrentUser user, CalendarItem job);
/// HR: runs a schedule job at once (outside its timetable) and returns the task it created.
CalendarJobRunResult RunScheduleJobNow(CurrentUser user, int id);
///
/// HR: sends a schedule email at once (outside its timetable): creates its e-mail batch, which the caller then
/// has sent (CalendarJobs.SendScheduleEmail with the returned RunAt).
///
CalendarEmailRunResult RunScheduleEmailNow(CurrentUser user, int id);
#region System use (Hangfire jobs) - never exposed through a controller
/// Finds reminders that are due, moves each item's NextTriggerAt on, and returns the ones to send.
List TakeDueReminders(DateTime now, int graceMinutes, int maxItems);
/// The item with all attendee rows (names included), or null when it does not exist.
CalendarItem GetForSystem(int id);
/// Marks a reminder as being sent to one attendee; false when it was already sent.
bool ClaimReminder(int attendeeID, DateTime triggerAt);
/// Undoes ClaimReminder after a failed send, so a retry sends it again.
void ReleaseReminder(int attendeeID, DateTime triggerAt, DateTime? previousReminderAt);
/// Adds an in-app (bell) notification for an employee.
void AddInAppNotification(int employeeID, string header, string description, int calendarItemID, int createdBy);
/// Records the Outlook version last sent to one attendee (NULL after a cancellation).
void MarkInviteSent(int attendeeID, int? outlookSequence);
/// Finds schedule jobs that are due, moves each one's NextTriggerAt to its next run, and returns the runs to do.
List TakeDueScheduleRuns(DateTime now, int maxItems);
///
/// Creates the task of one schedule-job run, at most once per run (a repeat call returns the task already created).
///
CalendarJobRunResult RunScheduleJob(int jobID, DateTime occurrenceStart);
/// Finds schedule emails that are due, moves each one's NextTriggerAt to its next run, and returns the runs to send.
List TakeDueScheduleEmails(DateTime now, int maxItems);
///
/// Creates the e-mail batch of one schedule-email run (one recipient row each, tags filled in), at most once per
/// run: a repeat call returns the batch already created. Sending it is the caller's job (IEmailDispatchService).
/// Every e-mail goes to the recipient's own address, as with Mail Manager's general mail: Calendar:SendMail and
/// Calendar:RedirectAllMailTo (reminders and invitations only) do not apply.
///
CalendarEmailRunResult PrepareScheduleEmailRun(int itemID, DateTime runAt);
#endregion
}
#endregion
}