HRM-10/HRM.BO/Calendar/CalendarItem.cs
Mohaimen Hasan 838b8d4480 first commit
2026-11-03 13:06:00 +06:00

467 lines
22 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
namespace HRM.BO
{
#region CalendarItem
/// <summary>
/// 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.
/// </summary>
public class CalendarItem : AuditTrailBase
{
#region Constructor
public CalendarItem()
{
ItemType = EnumCalendarItemType.Event;
Title = string.Empty;
IsAllDay = false;
Status = EnumCalendarItemStatus.Active;
OutlookSequence = 0;
Attendees = new List<CalendarItemAttendee>();
}
#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; }
/// <summary>Minutes before the start, comma separated, e.g. "4320,60".</summary>
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<CalendarItemAttendee> Attendees { get; set; }
#endregion
#region Display-only properties (not stored in CalendarItem)
public string OrganizerName { get; set; }
/// <summary>Schedule jobs only: the latest tasks the job created (filled when the job is opened).</summary>
public List<CalendarJobRun> RecentRuns { get; set; }
/// <summary>Schedule emails only: the latest runs with their sent / failed counts (filled when it is opened).</summary>
public List<CalendarEmailRun> RecentEmailRuns { get; set; }
/// <summary>Schedule emails only: the stored attachment's file name, or null when it has none.</summary>
public string AttachmentName { get; set; }
/// <summary>Schedule emails only: the stored attachment's size in bytes.</summary>
public int? AttachmentSize { get; set; }
/// <summary>Request only (schedule email): a new attachment, base64. Replaces the stored one.</summary>
public string AttachmentData { get; set; }
/// <summary>Request only (schedule email): true drops the stored attachment (ignored when AttachmentData is given).</summary>
public bool RemoveAttachment { get; set; }
/// <summary>The current user's own attendee row, filled by "my" queries.</summary>
public CalendarItemAttendee MyAttendee { get; set; }
/// <summary>
/// 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.
/// </summary>
public DateTime? OccurrenceStart { get; set; }
/// <summary>Request only: which dates of a repeating item the change applies to, together with OccurrenceStart.</summary>
public EnumCalendarEditScope? EditScope { get; set; }
#endregion
#region Functions
/// <summary>
/// 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.
/// </summary>
public List<int> GetReminderOffsetMinutes()
{
List<int> offsets = new List<int>();
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
/// <summary>
/// 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.
/// </summary>
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
/// <summary>
/// One entry the calendar screen draws: an Event/Task occurrence or a read-only
/// holiday / leave / birthday / anniversary entry.
/// </summary>
public class CalendarFeedItem
{
/// <summary>Unique key for the screen, e.g. "item-12", "holiday-2026-10-16".</summary>
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; }
/// <summary>True when this entry is one occurrence of a repeating item.</summary>
public bool IsRecurring { get; set; }
/// <summary>Start of this occurrence (needed to change or skip just this one).</summary>
public DateTime? OccurrenceStart { get; set; }
}
/// <summary>A reminder the dispatcher found due: which item, which occurrence, and the reminder moment.</summary>
public class CalendarDueReminder
{
public int CalendarItemID { get; set; }
public DateTime TriggerAt { get; set; }
public DateTime OccurrenceStart { get; set; }
public DateTime OccurrenceEnd { get; set; }
}
/// <summary>A schedule-job run the dispatcher found due: which job, and the run moment (the task's start).</summary>
public class CalendarDueRun
{
public int CalendarItemID { get; set; }
public DateTime OccurrenceStart { get; set; }
}
/// <summary>One person a schedule job would give a task to (employee, or a user account without an employee).</summary>
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; }
/// <summary>Schedule emails only: where the e-mail would go (empty = the person would be skipped).</summary>
public string Email { get; set; }
}
/// <summary>"Test run" of a schedule job or schedule email: who would get it right now, and when it runs next.</summary>
public class CalendarJobPreview
{
public List<CalendarJobTarget> Targets { get; set; } = new List<CalendarJobTarget>();
/// <summary>The next few run moments (empty when the job never runs again).</summary>
public List<DateTime> NextRuns { get; set; } = new List<DateTime>();
/// <summary>Schedule emails only: the subject and body as the first person would get them (tags filled in).</summary>
public string SampleSubject { get; set; }
public string SampleBody { get; set; }
/// <summary>Schedule emails only: whose data the sample shows.</summary>
public string SampleFor { get; set; }
}
/// <summary>What one run of a schedule job did.</summary>
public class CalendarJobRunResult
{
/// <summary>The task of this run (new, or the one an earlier attempt already created); 0 when none.</summary>
public int TaskID { get; set; }
/// <summary>True when this call created the task (so its people still have to be told).</summary>
public bool Created { get; set; }
public int AssigneeCount { get; set; }
/// <summary>Why no task was created, when it was not.</summary>
public string Message { get; set; }
}
/// <summary>
/// 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.
/// </summary>
public class CalendarEmailRunResult
{
/// <summary>The e-mail batch of this run (new, or the one an earlier attempt already created); 0 when none.</summary>
public int MasterEmailLogID { get; set; }
/// <summary>True when this call created the batch.</summary>
public bool Created { get; set; }
public int RecipientCount { get; set; }
public DateTime RunAt { get; set; }
/// <summary>Why no batch was created, when it was not.</summary>
public string Message { get; set; }
/// <summary>System use: who set the schedule email up (the batch is logged as theirs).</summary>
[Newtonsoft.Json.JsonIgnore]
public int CreatedBy { get; set; }
/// <summary>System use: the one file every recipient of the batch gets, or null.</summary>
[Newtonsoft.Json.JsonIgnore]
public EmailAttachmentInfo Attachment { get; set; }
}
/// <summary>One run of a schedule email, with its e-mail batch's counts (read from the recipient rows).</summary>
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; }
}
/// <summary>A task a schedule job created, with its progress.</summary>
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; }
}
/// <summary>
/// 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.
/// </summary>
public class CalendarUserOption
{
public int UserID { get; set; }
public string LoginID { get; set; }
public string UserName { get; set; }
/// <summary>The user's EmailAddress (or the older Email column when that is empty): where their invitations go.</summary>
public string EmailAddress { get; set; }
/// <summary>Set when the account belongs to an employee; such a pick is stored as that employee.</summary>
public int? EmployeeID { get; set; }
/// <summary>That employee's number (shown instead of the login for an employee's account).</summary>
public string EmployeeNo { get; set; }
}
/// <summary>What a save did, so the right people are told about it afterwards.</summary>
public class CalendarSaveResult
{
/// <summary>The item that was saved (a new item when one occurrence or the following dates were changed).</summary>
public int CalendarItemID { get; set; }
/// <summary>The repeating item that was changed along the way (skipped day or shortened series), if any.</summary>
public int? SeriesID { get; set; }
/// <summary>
/// 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.
/// </summary>
public bool DetailsChanged { get; set; }
}
/// <summary>
/// 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.
/// </summary>
public class CalendarUpcoming
{
/// <summary>Entries not ended yet that start within the next days (today's included).</summary>
public List<CalendarFeedItem> Items { get; set; } = new List<CalendarFeedItem>();
/// <summary>Entries that ended within the past days (yesterday's attendance, last week's leave...).</summary>
public List<CalendarFeedItem> Recent { get; set; } = new List<CalendarFeedItem>();
/// <summary>Tasks assigned to the user that are not done yet.</summary>
public int OpenTaskCount { get; set; }
}
/// <summary>What the logged-in user may do, so the screen offers only what the server allows.</summary>
public class CalendarOptions
{
/// <summary>HR / admin logins, while Calendar:ScheduleJobsEnabled is on.</summary>
public bool CanCreateScheduleJobs { get; set; }
/// <summary>HR / admin logins, while Calendar:ScheduleEmailsEnabled is on.</summary>
public bool CanCreateScheduleEmails { get; set; }
/// <summary>The tags a schedule email's subject and body may use, each filled in per recipient.</summary>
public List<CalendarEmailTag> EmailTags { get; set; } = new List<CalendarEmailTag>();
}
/// <summary>A tag of a schedule email's subject or body, e.g. "&lt;EMP-NAME&gt;", and what it is replaced with.</summary>
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
/// <summary>
/// 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).
/// </summary>
public interface ICalendarItemService
{
List<CalendarFeedItem> GetFeed(CurrentUser user, DateTime fromDate, DateTime toDate, List<EnumCalendarLayer> layers);
/// <summary>Everything on the user's calendar in the given number of days before and after now (see CalendarUpcoming).</summary>
CalendarUpcoming GetUpcoming(CurrentUser user, int days);
/// <summary>What the user may do on the calendar screen.</summary>
CalendarOptions GetOptions(CurrentUser user);
CalendarItem Get(CurrentUser user, int id);
CalendarSaveResult Save(CurrentUser user, CalendarItem item);
/// <summary>
/// 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.
/// </summary>
EnumCalendarChange Cancel(CurrentUser user, int id, DateTime? occurrenceStart, EnumCalendarEditScope? scope);
/// <summary>Saves the user's Yes / No / Maybe. Returns the user's attendee row ID.</summary>
int Respond(CurrentUser user, int calendarItemID, EnumResponseStatus responseStatus);
/// <summary>Saves the user's task status and remarks. Returns the user's attendee row ID.</summary>
int UpdateTaskStatus(CurrentUser user, int calendarItemID, EnumCalendarTaskStatus taskStatus, string remarks);
void MarkRead(CurrentUser user, int calendarItemID);
List<CalendarItem> GetMyTasks(CurrentUser user, EnumCalendarTaskStatus? taskStatus);
List<CalendarUserOption> GetActiveUsers(CurrentUser user);
/// <summary>HR: who an unsaved (or saved) schedule job would give a task to right now, and its next run moments.</summary>
CalendarJobPreview PreviewScheduleJob(CurrentUser user, CalendarItem job);
/// <summary>HR: runs a schedule job at once (outside its timetable) and returns the task it created.</summary>
CalendarJobRunResult RunScheduleJobNow(CurrentUser user, int id);
/// <summary>
/// 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).
/// </summary>
CalendarEmailRunResult RunScheduleEmailNow(CurrentUser user, int id);
#region System use (Hangfire jobs) - never exposed through a controller
/// <summary>Finds reminders that are due, moves each item's NextTriggerAt on, and returns the ones to send.</summary>
List<CalendarDueReminder> TakeDueReminders(DateTime now, int graceMinutes, int maxItems);
/// <summary>The item with all attendee rows (names included), or null when it does not exist.</summary>
CalendarItem GetForSystem(int id);
/// <summary>Marks a reminder as being sent to one attendee; false when it was already sent.</summary>
bool ClaimReminder(int attendeeID, DateTime triggerAt);
/// <summary>Undoes ClaimReminder after a failed send, so a retry sends it again.</summary>
void ReleaseReminder(int attendeeID, DateTime triggerAt, DateTime? previousReminderAt);
/// <summary>Adds an in-app (bell) notification for an employee.</summary>
void AddInAppNotification(int employeeID, string header, string description, int calendarItemID, int createdBy);
/// <summary>Records the Outlook version last sent to one attendee (NULL after a cancellation).</summary>
void MarkInviteSent(int attendeeID, int? outlookSequence);
/// <summary>Finds schedule jobs that are due, moves each one's NextTriggerAt to its next run, and returns the runs to do.</summary>
List<CalendarDueRun> TakeDueScheduleRuns(DateTime now, int maxItems);
/// <summary>
/// Creates the task of one schedule-job run, at most once per run (a repeat call returns the task already created).
/// </summary>
CalendarJobRunResult RunScheduleJob(int jobID, DateTime occurrenceStart);
/// <summary>Finds schedule emails that are due, moves each one's NextTriggerAt to its next run, and returns the runs to send.</summary>
List<CalendarDueRun> TakeDueScheduleEmails(DateTime now, int maxItems);
/// <summary>
/// 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.
/// </summary>
CalendarEmailRunResult PrepareScheduleEmailRun(int itemID, DateTime runAt);
#endregion
}
#endregion
}