using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using HRM.BO;
using HRM.BO.Configuration;
using Ease.Core;
using Ease.Core.DataAccess;
using Ease.Core.Model;
using Ease.Core.Utility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace HRM.DA
{
///
/// HRM Calendar: Events and Tasks with attendees, HR's Schedule Jobs and Schedule Emails, plus read-only holiday,
/// leave, birthday and work-anniversary layers. Every public method checks permissions itself.
///
public class CalendarItemService : ServiceTemplate, ICalendarItemService
{
#region Limits
private const int MaxReminders = 5;
private const int MaxReminderMinutes = 60 * 24 * 365;
private const int MaxItemDays = 366;
private const int MaxFeedDays = 100;
private const int MaxTitleLength = 250;
private const int MaxLocationLength = 500;
private const int MaxDescriptionLength = 8000;
/// A schedule email's body (kept in Description) may be much longer than an item's description.
private const int MaxEmailBodyLength = 100000;
/// Largest file a schedule email may carry: the same ceiling as Mail Manager's general mail.
private const int MaxAttachmentBytes = 10 * 1024 * 1024;
private const int MaxAttachmentNameLength = 260;
/// Longest MasterEmailLog.Description written for a schedule-email batch (as for general mail).
private const int MaxBatchDescriptionLength = 200;
private const int MaxRemarksLength = 2000;
private const int MaxUpcomingDays = 31;
private const int MaxUpcomingItems = 50;
private const int MaxPreviewRuns = 5;
private const int MaxRecentRuns = 10;
/// How long a schedule job's run shows on the calendar (the task it creates keeps its own length).
private const int JobRunMinutes = 30;
private static readonly Regex ColorPattern = new Regex("^#[0-9A-Fa-f]{6}$");
#endregion
private readonly CalendarSettings _settings;
public CalendarItemService() : this(new CalendarSettings())
{
}
/// The "Calendar" section of appsettings.json (schedule jobs on/off, limits).
public CalendarItemService(CalendarSettings settings)
{
_settings = settings ?? new CalendarSettings();
}
#region Mapping
private void MapObject(CalendarItem oItem, DataReader oReader)
{
base.SetObjectID(oItem, oReader.GetInt32("CalendarItemID").Value);
oItem.ItemType = (EnumCalendarItemType)oReader.GetInt32("ItemType").Value;
oItem.Title = oReader.GetString("Title", string.Empty);
oItem.Description = oReader.GetString("Description");
oItem.Location = oReader.GetString("Location");
oItem.Color = oReader.GetString("Color");
oItem.Priority = (EnumCalendarPriority?)oReader.GetInt32("Priority");
oItem.StartDateTime = oReader.GetDateTime("StartDateTime").Value;
oItem.EndDateTime = oReader.GetDateTime("EndDateTime").Value;
oItem.IsAllDay = oReader.GetBoolean("IsAllDay", false);
oItem.RecurrenceRule = oReader.GetString("RecurrenceRule");
oItem.RecurrenceEndDate = oReader.GetDateTime("RecurrenceEndDate");
oItem.ExceptionDates = oReader.GetString("ExceptionDates");
oItem.ReminderOffsets = oReader.GetString("ReminderOffsets");
oItem.ReminderChannel = (EnumReminderChannel?)oReader.GetInt32("ReminderChannel");
oItem.NextTriggerAt = oReader.GetDateTime("NextTriggerAt");
oItem.SourceItemID = oReader.GetInt32("SourceItemID");
oItem.SourceOccurrence = oReader.GetDateTime("SourceOccurrence");
oItem.OutlookSequence = oReader.GetInt32("OutlookSequence", 0);
oItem.OutlookEventID = oReader.GetString("OutlookEventID");
oItem.PayrollTypeID = oReader.GetInt32("PayrollTypeID", 0);
oItem.Status = (EnumCalendarItemStatus)oReader.GetInt32("Status").Value;
oItem.CreatedBy = oReader.GetInt32("CreatedBy", 0);
oItem.CreatedDate = oReader.GetDateTime("CreatedDate").Value;
oItem.ModifiedBy = oReader.GetInt32("ModifiedBy");
oItem.ModifiedDate = oReader.GetDateTime("ModifiedDate");
this.SetObjectState(oItem, ObjectState.Saved);
}
/// Reads the "My..." columns produced by CalendarItemDA's my-attendee query.
private void MapMyAttendee(CalendarItem oItem, DataReader oReader)
{
CalendarItemAttendee me = new CalendarItemAttendee();
base.SetObjectID(me, oReader.GetInt32("MyAttendeeID").Value);
me.CalendarItemID = oItem.ID;
me.Role = (EnumAttendeeRole)oReader.GetInt32("MyRole").Value;
me.ResponseStatus = (EnumResponseStatus)oReader.GetInt32("MyResponseStatus").Value;
me.TaskStatus = (EnumCalendarTaskStatus?)oReader.GetInt32("MyTaskStatus");
me.Remarks = oReader.GetString("MyRemarks");
me.RemarksDate = oReader.GetDateTime("MyRemarksDate");
me.IsRead = oReader.GetBoolean("MyIsRead", false);
me.ReadDate = oReader.GetDateTime("MyReadDate");
me.TitleOverride = oReader.GetString("MyTitleOverride");
me.FromOverride = oReader.GetDateTime("MyFromOverride");
me.ToOverride = oReader.GetDateTime("MyToOverride");
this.SetObjectState(me, ObjectState.Saved);
oItem.MyAttendee = me;
}
private void MapAttendee(CalendarItemAttendee oAttendee, DataReader oReader, bool withNames)
{
base.SetObjectID(oAttendee, oReader.GetInt32("AttendeeID").Value);
oAttendee.CalendarItemID = oReader.GetInt32("CalendarItemID").Value;
oAttendee.AttendeeType = (EnumAttendeeType)oReader.GetInt32("AttendeeType").Value;
oAttendee.EmployeeID = oReader.GetInt32("EmployeeID");
oAttendee.UserID = oReader.GetInt32("UserID");
oAttendee.DepartmentID = oReader.GetInt32("DepartmentID");
oAttendee.Email = oReader.GetString("Email");
oAttendee.Role = (EnumAttendeeRole)oReader.GetInt32("Role").Value;
oAttendee.TitleOverride = oReader.GetString("TitleOverride");
oAttendee.SubjectOverride = oReader.GetString("SubjectOverride");
oAttendee.FromOverride = oReader.GetDateTime("FromOverride");
oAttendee.ToOverride = oReader.GetDateTime("ToOverride");
oAttendee.ResponseStatus = (EnumResponseStatus)oReader.GetInt32("ResponseStatus").Value;
oAttendee.TaskStatus = (EnumCalendarTaskStatus?)oReader.GetInt32("TaskStatus");
oAttendee.Remarks = oReader.GetString("Remarks");
oAttendee.RemarksDate = oReader.GetDateTime("RemarksDate");
oAttendee.IsRead = oReader.GetBoolean("IsRead", false);
oAttendee.ReadDate = oReader.GetDateTime("ReadDate");
oAttendee.LastReminderAt = oReader.GetDateTime("LastReminderAt");
oAttendee.InviteSentSequence = oReader.GetInt32("InviteSentSequence");
oAttendee.Status = (EnumAttendeeStatus)oReader.GetInt32("Status").Value;
oAttendee.CreatedBy = oReader.GetInt32("CreatedBy", 0);
oAttendee.CreatedDate = oReader.GetDateTime("CreatedDate").Value;
oAttendee.ModifiedBy = oReader.GetInt32("ModifiedBy");
oAttendee.ModifiedDate = oReader.GetDateTime("ModifiedDate");
if (withNames)
{
oAttendee.Name = oReader.GetString("Name", string.Empty);
oAttendee.EmployeeNo = oReader.GetString("EmployeeNo");
oAttendee.DepartmentName = oReader.GetString("DepartmentName");
}
this.SetObjectState(oAttendee, ObjectState.Saved);
}
protected override T CreateObject(DataReader oReader)
{
CalendarItem oItem = new CalendarItem();
MapObject(oItem, oReader);
return oItem as T;
}
private List CreateAttendees(DataReader oReader, bool withNames)
{
List attendees = new List();
while (oReader.Read())
{
CalendarItemAttendee oAttendee = new CalendarItemAttendee();
MapAttendee(oAttendee, oReader, withNames);
attendees.Add(oAttendee);
}
return attendees;
}
#endregion
#region Feed
public List GetFeed(CurrentUser user, DateTime fromDate, DateTime toDate, List layers)
{
List feed = new List();
TransactionContext tc = null;
try
{
RequireUser(user);
if (toDate <= fromDate || (toDate - fromDate).TotalDays > MaxFeedDays)
throw new ArgumentException("The calendar date range is not valid.");
if (layers == null || layers.Count == 0)
layers = Enum.GetValues(typeof(EnumCalendarLayer)).Cast().ToList();
int? employeeID = user.EmployeeID;
tc = TransactionContext.Begin();
if (layers.Contains(EnumCalendarLayer.Event) || layers.Contains(EnumCalendarLayer.Task)
|| layers.Contains(EnumCalendarLayer.ScheduleJob) || layers.Contains(EnumCalendarLayer.ScheduleEmail))
feed.AddRange(GetItemFeed(tc, user, employeeID, fromDate, toDate, layers));
EmployeeInfo me = null;
if (employeeID.HasValue)
me = GetEmployees(tc, new List { employeeID.Value }).FirstOrDefault();
if (layers.Contains(EnumCalendarLayer.Holiday) || layers.Contains(EnumCalendarLayer.WeeklyHoliday))
feed.AddRange(GetHolidayFeed(tc, me, me?.PayrollTypeID ?? user.PayrollTypeID, fromDate, toDate, layers));
if (me != null && layers.Contains(EnumCalendarLayer.Leave))
feed.AddRange(GetLeaveFeed(tc, me, fromDate, toDate));
if (me != null && layers.Contains(EnumCalendarLayer.Attendance))
feed.AddRange(GetAttendanceFeed(tc, me, fromDate, toDate));
if (me != null && (layers.Contains(EnumCalendarLayer.Birthday) || layers.Contains(EnumCalendarLayer.Anniversary)))
feed.AddRange(GetOwnDatesFeed(tc, me, fromDate, toDate, layers));
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return feed;
}
public CalendarUpcoming GetUpcoming(CurrentUser user, int days)
{
RequireUser(user);
if (days < 1 || days > MaxUpcomingDays)
throw new ArgumentException("Days must be from 1 to " + MaxUpcomingDays + ".");
DateTime now = DateTime.Now;
// Every layer the user sees, schedule-job and schedule-email runs aside (those are HR's set-up, not the user's own days).
List layers = Enum.GetValues(typeof(EnumCalendarLayer)).Cast()
.Where(l => l != EnumCalendarLayer.ScheduleJob && l != EnumCalendarLayer.ScheduleEmail)
.ToList();
// one read covers both sides of now; each entry then lands in exactly one list by its end
List feed = GetFeed(user, now.Date.AddDays(-days), now.Date.AddDays(days + 1), layers)
.Where(f => f.ResponseStatus != EnumResponseStatus.Declined)
.ToList();
CalendarUpcoming upcoming = new CalendarUpcoming();
// still running or coming: open tasks only (a done task is no longer something to look out for)
upcoming.Items = feed
.Where(f => f.End > now && f.Start < now.AddDays(days) && f.TaskStatus != EnumCalendarTaskStatus.Done)
.OrderBy(f => f.Start).ThenBy(f => f.Layer)
.Take(MaxUpcomingItems)
.ToList();
// already over, newest first
upcoming.Recent = feed
.Where(f => f.End <= now && f.End > now.Date.AddDays(-days))
.OrderByDescending(f => f.Start).ThenBy(f => f.Layer)
.Take(MaxUpcomingItems)
.ToList();
upcoming.OpenTaskCount = GetMyTasks(user, null)
.Count(t => t.MyAttendee != null && t.MyAttendee.TaskStatus != EnumCalendarTaskStatus.Done);
return upcoming;
}
public CalendarOptions GetOptions(CurrentUser user)
{
RequireUser(user);
return new CalendarOptions
{
CanCreateScheduleJobs = IsHr(user) && _settings.ScheduleJobsEnabled,
CanCreateScheduleEmails = CanUseScheduleEmails(user),
EmailTags = ScheduleEmailTags.List()
};
}
private List GetItemFeed(TransactionContext tc, CurrentUser user, int? employeeID,
DateTime fromDate, DateTime toDate, List layers)
{
List feed = new List();
DataReader dr = new DataReader(CalendarItemDA.GetFeed(tc, employeeID ?? 0, user.UserID, fromDate, toDate));
while (dr.Read())
{
CalendarItem oItem = new CalendarItem();
MapObject(oItem, dr);
MapMyAttendee(oItem, dr);
EnumCalendarLayer layer = LayerOf(oItem.ItemType);
if (!layers.Contains(layer))
continue;
CalendarItemAttendee me = oItem.MyAttendee;
bool isRecurring = !string.IsNullOrWhiteSpace(oItem.RecurrenceRule);
if (!isRecurring)
{
// one-off item: the person's own dates (task assignee) win over the item's dates
feed.Add(ToFeedItem(oItem, me, user, layer, me.FromOverride ?? oItem.StartDateTime,
me.ToOverride ?? oItem.EndDateTime, false));
continue;
}
foreach (var occurrence in CalendarRecurrence.Occurrences(oItem, fromDate))
{
if (occurrence.Start >= toDate)
break;
feed.Add(ToFeedItem(oItem, me, user, layer, occurrence.Start, occurrence.End, true));
}
}
dr.Close();
if (layers.Contains(EnumCalendarLayer.ScheduleJob) && IsHr(user) && user.PayrollTypeID.HasValue)
feed.AddRange(GetScheduleJobFeed(tc, user, EnumCalendarItemType.ScheduleJob, fromDate, toDate));
if (layers.Contains(EnumCalendarLayer.ScheduleEmail) && CanUseScheduleEmails(user) && user.PayrollTypeID.HasValue)
feed.AddRange(GetScheduleJobFeed(tc, user, EnumCalendarItemType.ScheduleEmail, fromDate, toDate));
return feed;
}
///
/// HR: the runs of every active schedule job (or schedule email) of the user's payroll type, so any HR user can
/// find, change or stop one (not only the one who set it up). A self-service user sees only the schedule emails
/// they set up themselves. A job shows at its run moments, not for the length of the task it creates.
///
private List GetScheduleJobFeed(TransactionContext tc, CurrentUser user, EnumCalendarItemType itemType,
DateTime fromDate, DateTime toDate)
{
List feed = new List();
EnumCalendarLayer layer = LayerOf(itemType);
DataReader dr = new DataReader(CalendarItemDA.GetScheduleJobFeed(tc, itemType, user.PayrollTypeID.Value, fromDate, toDate,
IsHr(user) ? (int?)null : user.UserID));
List jobs = this.CreateObjects(dr);
dr.Close();
// HR is not a job's attendee: an empty row stands in (no own title, answer or task status)
CalendarItemAttendee none = new CalendarItemAttendee();
foreach (CalendarItem job in jobs)
{
bool isRecurring = !string.IsNullOrWhiteSpace(job.RecurrenceRule);
foreach (var occurrence in CalendarRecurrence.Occurrences(job, fromDate))
{
if (occurrence.Start >= toDate)
break;
DateTime runEnd = job.IsAllDay ? occurrence.Start : occurrence.Start.AddMinutes(JobRunMinutes);
feed.Add(ToFeedItem(job, none, user, layer, occurrence.Start, runEnd, isRecurring));
}
}
return feed;
}
private static EnumCalendarLayer LayerOf(EnumCalendarItemType itemType)
{
switch (itemType)
{
case EnumCalendarItemType.Task: return EnumCalendarLayer.Task;
case EnumCalendarItemType.ScheduleJob: return EnumCalendarLayer.ScheduleJob;
case EnumCalendarItemType.ScheduleEmail: return EnumCalendarLayer.ScheduleEmail;
default: return EnumCalendarLayer.Event;
}
}
/// One calendar entry for an item (or one occurrence of a repeating item). End becomes exclusive for all-day items.
private static CalendarFeedItem ToFeedItem(CalendarItem oItem, CalendarItemAttendee me, CurrentUser user,
EnumCalendarLayer layer, DateTime start, DateTime end, bool isRecurring)
{
return new CalendarFeedItem
{
Key = isRecurring ? "item-" + oItem.ID + "-" + start.ToString("yyyyMMddHHmm") : "item-" + oItem.ID,
Layer = layer,
CalendarItemID = oItem.ID,
Title = string.IsNullOrWhiteSpace(me.TitleOverride) ? oItem.Title : me.TitleOverride,
Start = start,
End = oItem.IsAllDay ? end.Date.AddDays(1) : end,
IsAllDay = oItem.IsAllDay,
Color = oItem.Color,
CanEdit = CanManage(user, oItem, me),
Priority = oItem.Priority,
ResponseStatus = me.ResponseStatus,
TaskStatus = me.TaskStatus,
IsRecurring = isRecurring,
OccurrenceStart = isRecurring ? start : (DateTime?)null
};
}
///
/// Holidays straight from HR's setup, for any year: national / other holidays (AttnNationalHoliday, each day of
/// each holiday's range) of the payroll type, and the weekly holidays (WeeklyHoliday weekdays) - company-wide ones
/// plus the employee's own location's. A login without an employee gets the company-wide ones only.
///
private List GetHolidayFeed(TransactionContext tc, EmployeeInfo me, int? payrollTypeID,
DateTime fromDate, DateTime toDate, List layers)
{
List feed = new List();
DateTime first = fromDate.Date;
DateTime end = toDate.Date < toDate ? toDate.Date.AddDays(1) : toDate.Date; // exclusive
int? locationID = me?.LocationID;
if (layers.Contains(EnumCalendarLayer.Holiday) && payrollTypeID.HasValue)
{
// one entry per day and name (two holidays on one day both show; the same one twice does not)
HashSet seen = new HashSet();
DataReader dr = new DataReader(CalendarItemDA.GetNationalHolidays(tc, first, end, payrollTypeID.Value, locationID));
while (dr.Read())
{
string description = dr.GetString("Description");
string title = string.IsNullOrWhiteSpace(description) ? "Holiday" : description.Trim();
DateTime from = dr.GetDateTime("FromDate").Value.Date;
DateTime to = (dr.GetDateTime("ToDate") ?? from).Date;
for (DateTime day = from < first ? first : from; day <= to && day < end; day = day.AddDays(1))
{
if (seen.Add(day.ToString("yyyyMMdd") + "|" + title.ToLowerInvariant()))
feed.Add(DayEntry("holiday-" + day.ToString("yyyyMMdd") + "-" + seen.Count, EnumCalendarLayer.Holiday, title, day));
}
}
dr.Close();
}
if (layers.Contains(EnumCalendarLayer.WeeklyHoliday))
{
// DateType 1 = Sunday ... 7 = Saturday; DayOfWeek is 0 = Sunday
HashSet weekdays = new HashSet();
DataReader dr = new DataReader(CalendarItemDA.GetWeeklyHolidays(tc, locationID));
while (dr.Read())
{
int dateType = dr.GetInt32("DateType", 0);
if (dateType >= 1 && dateType <= 7)
weekdays.Add((DayOfWeek)(dateType - 1));
}
dr.Close();
for (DateTime day = first; day < end && weekdays.Count > 0; day = day.AddDays(1))
{
if (weekdays.Contains(day.DayOfWeek))
feed.Add(DayEntry("weekly-" + day.ToString("yyyyMMdd"), EnumCalendarLayer.WeeklyHoliday, "Weekly holiday", day));
}
}
return feed;
}
/// The employee's own approved (or availed) leave, with its leave type.
private List GetLeaveFeed(TransactionContext tc, EmployeeInfo me, DateTime fromDate, DateTime toDate)
{
List feed = new List();
DataReader dr = new DataReader(CalendarItemDA.GetApprovedLeaves(tc, me.EmployeeID, fromDate.Date, toDate.Date));
while (dr.Read())
{
string leaveName = dr.GetString("LeaveName");
feed.Add(new CalendarFeedItem
{
Key = "leave-" + dr.GetInt32("TRANID", 0),
Layer = EnumCalendarLayer.Leave,
Title = string.IsNullOrWhiteSpace(leaveName) ? "On leave" : "On leave (" + leaveName.Trim() + ")",
Start = dr.GetDateTime("FromDate").Value.Date,
End = dr.GetDateTime("ToDate").Value.Date.AddDays(1),
IsAllDay = true
});
}
dr.Close();
return feed;
}
///
/// The employee's own processed attendance, one entry per day: present (with in / out time), late, left early,
/// absent, half day, outside duty... Leave and holidays are left out here: their own layers show them.
///
private List GetAttendanceFeed(TransactionContext tc, EmployeeInfo me, DateTime fromDate, DateTime toDate)
{
List feed = new List();
DateTime end = toDate.Date < toDate ? toDate.Date.AddDays(1) : toDate.Date;
DataReader dr = new DataReader(CalendarItemDA.GetAttendance(tc, me.EmployeeID, fromDate.Date, end));
while (dr.Read())
{
DateTime day = dr.GetDateTime("AttnDate").Value.Date;
EnumAttendanceType type = (EnumAttendanceType)dr.GetInt32("AttenType", 0);
bool isLate = dr.GetBoolean("IsLate", false);
(string Status, string Color)? look = AttendanceLook(type, isLate);
if (!look.HasValue)
continue;
string times = AttendanceTimes(dr.GetDateTime("InTime"), dr.GetDateTime("OutTime"));
CalendarFeedItem entry = DayEntry("attendance-" + day.ToString("yyyyMMdd"), EnumCalendarLayer.Attendance,
times == null ? look.Value.Status : look.Value.Status + " ยท " + times, day);
entry.Color = look.Value.Color;
feed.Add(entry);
}
dr.Close();
return feed;
}
/// How one attendance day is shown: its word and color, or null for days other layers already show.
private static (string Status, string Color)? AttendanceLook(EnumAttendanceType type, bool isLate)
{
const string green = "#1D9E75", amber = "#BA7517", red = "#A32D2D", blue = "#185FA5", gray = "#5F5E5A";
switch (type)
{
case EnumAttendanceType.Present:
case EnumAttendanceType.ManualEntry: return isLate ? ("Late", amber) : ("Present", green);
case EnumAttendanceType.Delay:
case EnumAttendanceType.Late: return ("Late", amber);
case EnumAttendanceType.Early: return ("Left early", amber);
case EnumAttendanceType.HalfDay: return ("Half day", amber);
case EnumAttendanceType.Absent: return ("Absent", red);
case EnumAttendanceType.OutSideDuty: return ("Outside duty", blue);
case EnumAttendanceType.Compensation: return ("Compensation", blue);
case EnumAttendanceType.LOA: return ("LOA", gray);
default: return null; // Leave, Holiday, Weekly holiday / off, None
}
}
/// "9:05 AM - 6:10 PM", "In 9:05 AM", or null when there is no punch.
private static string AttendanceTimes(DateTime? inTime, DateTime? outTime)
{
bool hasIn = inTime.HasValue && inTime.Value.Year > 1900;
bool hasOut = outTime.HasValue && outTime.Value.Year > 1900;
if (hasIn && hasOut)
return inTime.Value.ToString("h:mm tt") + " - " + outTime.Value.ToString("h:mm tt");
if (hasIn)
return "In " + inTime.Value.ToString("h:mm tt");
if (hasOut)
return "Out " + outTime.Value.ToString("h:mm tt");
return null;
}
///
/// The user's own birthday and work anniversaries (no year shown). Nobody sees anyone else's: the layers are
/// always about oneself.
///
private List GetOwnDatesFeed(TransactionContext tc, EmployeeInfo me,
DateTime fromDate, DateTime toDate, List layers)
{
List feed = new List();
DataReader dr = new DataReader(CalendarItemDA.GetOwnDates(tc, me.EmployeeID));
if (dr.Read())
{
DateTime? birthDate = dr.GetDateTime("BIRTHDATE");
DateTime? joiningDate = dr.GetDateTime("JOININGDATE");
for (int year = fromDate.Year; year <= toDate.Year; year++)
{
if (layers.Contains(EnumCalendarLayer.Birthday) && IsUsableDate(birthDate))
{
DateTime day = SameDayInYear(birthDate.Value, year);
if (day >= fromDate.Date && day < toDate)
feed.Add(DayEntry("birthday-" + me.EmployeeID + "-" + year, EnumCalendarLayer.Birthday, "My birthday", day));
}
if (layers.Contains(EnumCalendarLayer.Anniversary) && IsUsableDate(joiningDate) && year > joiningDate.Value.Year)
{
DateTime day = SameDayInYear(joiningDate.Value, year);
int years = year - joiningDate.Value.Year;
if (day >= fromDate.Date && day < toDate)
feed.Add(DayEntry("anniversary-" + me.EmployeeID + "-" + year, EnumCalendarLayer.Anniversary,
"Work anniversary: " + years + (years == 1 ? " year" : " years") + " with us", day));
}
}
}
dr.Close();
return feed;
}
private static bool IsUsableDate(DateTime? date)
{
return date.HasValue && date.Value.Year > 1900;
}
/// The same month and day in another year; 29 February becomes 28 February in non-leap years.
private static DateTime SameDayInYear(DateTime date, int year)
{
int day = Math.Min(date.Day, DateTime.DaysInMonth(year, date.Month));
return new DateTime(year, date.Month, day);
}
private static CalendarFeedItem DayEntry(string key, EnumCalendarLayer layer, string title, DateTime day)
{
return new CalendarFeedItem
{
Key = key,
Layer = layer,
Title = title,
Start = day,
End = day.AddDays(1),
IsAllDay = true
};
}
#endregion
#region Get
public CalendarItem Get(CurrentUser user, int id)
{
CalendarItem oItem = null;
TransactionContext tc = null;
try
{
RequireUser(user);
tc = TransactionContext.Begin();
oItem = LoadItem(tc, id);
CalendarItemAttendee me = LoadMyAttendee(tc, user, id);
bool canManage = CanManage(user, oItem, me);
if (IsScheduled(oItem.ItemType))
{
// A job is HR's set-up: its targets see the tasks (or e-mails) it creates, never the job itself.
if (!canManage)
throw new UnauthorizedAccessException("Only the organizer or HR can open a " + ScheduledTypeText(oItem.ItemType) + ".");
if (me != null && me.Role != EnumAttendeeRole.Organizer)
me = null;
if (oItem.ItemType == EnumCalendarItemType.ScheduleJob)
{
oItem.RecentRuns = GetRecentRuns(tc, id);
}
else
{
oItem.RecentEmailRuns = GetRecentEmailRuns(tc, id);
LoadAttachmentInfo(tc, oItem);
}
}
else if (me == null)
{
throw new UnauthorizedAccessException("You are not part of this calendar item.");
}
DataReader dr = new DataReader(CalendarItemAttendeeDA.GetByItem(tc, id));
List attendees = CreateAttendees(dr, true);
dr.Close();
// Only the organizer (and HR, who may change the item) sees removed attendees and e-mail addresses.
if (!canManage)
{
attendees = attendees.Where(a => a.Status == EnumAttendeeStatus.Active).ToList();
attendees.ForEach(a => { a.Email = null; a.LastReminderAt = null; a.InviteSentSequence = null; });
}
oItem.Attendees = attendees;
oItem.MyAttendee = me;
oItem.OrganizerName = attendees.FirstOrDefault(a => a.Role == EnumAttendeeRole.Organizer)?.Name;
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return oItem;
}
public List GetMyTasks(CurrentUser user, EnumCalendarTaskStatus? taskStatus)
{
List items = new List();
TransactionContext tc = null;
try
{
RequireUser(user);
tc = TransactionContext.Begin();
DataReader dr = new DataReader(CalendarItemDA.GetMyTasks(tc, user.EmployeeID ?? 0, user.UserID, (int?)taskStatus));
while (dr.Read())
{
CalendarItem oItem = new CalendarItem();
MapObject(oItem, dr);
MapMyAttendee(oItem, dr);
oItem.OrganizerName = dr.GetString("OrganizerName");
items.Add(oItem);
}
dr.Close();
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return items;
}
/// Active admin-side user accounts for the participant picker. Admin logins only.
public List GetActiveUsers(CurrentUser user)
{
List users = new List();
TransactionContext tc = null;
try
{
RequireUser(user);
if (user.UserType == EnumUserType.Employee)
throw new UnauthorizedAccessException("Only admin users can add users as participants.");
tc = TransactionContext.Begin();
DataReader dr = new DataReader(CalendarItemDA.GetActiveUsers(tc));
while (dr.Read())
{
int? employeeID = dr.GetInt32("EMPLOYEEID");
users.Add(new CalendarUserOption
{
UserID = dr.GetInt32("USERID", 0),
LoginID = dr.GetString("LOGINID", string.Empty),
UserName = dr.GetString("USERNAME", string.Empty),
EmailAddress = dr.GetString("EmailAddress"),
EmployeeID = employeeID.HasValue && employeeID.Value > 0 ? employeeID : null,
EmployeeNo = employeeID.HasValue && employeeID.Value > 0 ? dr.GetString("EMPLOYEENO") : null
});
}
dr.Close();
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return users;
}
#endregion
#region Schedule jobs
public CalendarJobPreview PreviewScheduleJob(CurrentUser user, CalendarItem job)
{
CalendarJobPreview preview = new CalendarJobPreview();
TransactionContext tc = null;
try
{
RequireUser(user);
if (job == null || !IsScheduled(job.ItemType))
throw new ArgumentException("Only a schedule job or a schedule email can be test run.");
CheckCanUseScheduled(user, job.ItemType);
if (job.ItemType == EnumCalendarItemType.ScheduleEmail)
NormalizeScheduleEmail(job);
ValidateItem(job);
if (!user.PayrollTypeID.HasValue)
throw new ArgumentException("Payroll type is not selected.");
DateTime now = DateTime.Now;
tc = TransactionContext.Begin();
// the same checks and target rows a save would make, then the people they stand for right now
CalendarItemAttendee organizer = BuildOrganizer(user.EmployeeID, user.EmployeeID.HasValue ? (int?)null : user.UserID,
user, job, now);
List targets = ResolveAttendees(tc, user, job, organizer, now);
if (job.ItemType == EnumCalendarItemType.ScheduleEmail)
CheckEmailRecipientPermission(tc, user, targets);
preview.Targets = ExpandTargets(tc, WithSelfRecipient(job, organizer, targets), user.PayrollTypeID.Value)
.Select(t => new CalendarJobTarget
{
EmployeeID = t.Row.EmployeeID,
UserID = t.Row.UserID,
Name = t.Row.Name,
EmployeeNo = t.Row.EmployeeNo,
DepartmentID = t.DepartmentID,
Email = job.ItemType == EnumCalendarItemType.ScheduleEmail ? t.Row.Email : null
})
.OrderBy(t => t.Name)
.ToList();
preview.NextRuns = CalendarRecurrence.NextStarts(job, now, MaxPreviewRuns);
// a schedule email also shows what its first recipient would get, tags filled in
if (job.ItemType == EnumCalendarItemType.ScheduleEmail && preview.Targets.Count > 0)
{
CalendarJobTarget first = preview.Targets[0];
EmployeeTagData data = null;
if (first.EmployeeID.HasValue)
GetTagData(tc, new List { first.EmployeeID.Value }).TryGetValue(first.EmployeeID.Value, out data);
Dictionary values = ScheduleEmailTags.Values(data, first.Name, now);
preview.SampleSubject = ScheduleEmailTags.FillSubject(job.Title, values);
preview.SampleBody = ScheduleEmailTags.FillBody(job.Description, values);
preview.SampleFor = first.Name;
}
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return preview;
}
public CalendarJobRunResult RunScheduleJobNow(CurrentUser user, int id)
{
CalendarItem job;
TransactionContext tc = null;
try
{
RequireUser(user);
CheckCanUseScheduleJobs(user);
tc = TransactionContext.Begin();
job = LoadItem(tc, id);
if (job.ItemType != EnumCalendarItemType.ScheduleJob)
throw new ArgumentException("This calendar item is not a schedule job.");
CheckCanChange(tc, user, job);
tc.End();
tc = null;
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
// An extra run of its own, outside the timetable. Whole seconds: that is what the database keeps, and the
// run is found again by this moment.
DateTime now = DateTime.Now;
DateTime runAt = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
return RunScheduleJob(id, runAt);
}
public CalendarEmailRunResult RunScheduleEmailNow(CurrentUser user, int id)
{
TransactionContext tc = null;
try
{
RequireUser(user);
CheckCanUseScheduled(user, EnumCalendarItemType.ScheduleEmail);
tc = TransactionContext.Begin();
CalendarItem item = LoadItem(tc, id);
if (item.ItemType != EnumCalendarItemType.ScheduleEmail)
throw new ArgumentException("This calendar item is not a schedule email.");
CheckCanChange(tc, user, item);
tc.End();
tc = null;
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
// An extra run of its own, outside the timetable (whole seconds, like RunScheduleJobNow).
DateTime now = DateTime.Now;
DateTime runAt = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
return PrepareScheduleEmailRun(id, runAt);
}
public List TakeDueScheduleRuns(DateTime now, int maxItems)
{
return TakeDueRuns(EnumCalendarItemType.ScheduleJob, now, maxItems);
}
public List TakeDueScheduleEmails(DateTime now, int maxItems)
{
return TakeDueRuns(EnumCalendarItemType.ScheduleEmail, now, maxItems);
}
private List TakeDueRuns(EnumCalendarItemType itemType, DateTime now, int maxItems)
{
List due = new List();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin(true);
DataReader dr = new DataReader(CalendarItemDA.GetDueScheduleRuns(tc, itemType, now, maxItems));
List jobs = this.CreateObjects(dr);
dr.Close();
foreach (CalendarItem job in jobs)
{
DateTime trigger = job.NextTriggerAt.Value;
// Runs missed while the server was down are not all made up: only the latest one is done.
DateTime? run = CalendarRecurrence.LatestStartBetween(job, trigger, now);
DateTime? next = CalendarRecurrence.NextStart(job, now);
// Only the caller that moves NextTriggerAt on may run it, so a run can never be taken twice.
if (!CalendarItemDA.AdvanceTrigger(tc, job.ID, trigger, next) || !run.HasValue)
continue;
due.Add(new CalendarDueRun { CalendarItemID = job.ID, OccurrenceStart = run.Value });
}
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return due;
}
///
/// Creates the task of one run from the job's template: same title, details, priority, color and reminders;
/// starts at the run moment and lasts as long as the job's start-to-end; assigned to the job's targets as they
/// are right now (departments expanded into their live employees). The job's organizer is the task's organizer
/// and must still be an active HR user. The (job, run) pair is unique in the database, so a run makes one task.
///
public CalendarJobRunResult RunScheduleJob(int jobID, DateTime occurrenceStart)
{
CalendarJobRunResult result = new CalendarJobRunResult();
TransactionContext tc = null;
try
{
DateTime now = DateTime.Now;
tc = TransactionContext.Begin(true);
CalendarItem job = null;
DataReader drJob = new DataReader(CalendarItemDA.Get(tc, jobID));
if (drJob.Read())
job = this.CreateObject(drJob);
drJob.Close();
object existing = CalendarItemDA.GetTaskOfRun(tc, jobID, occurrenceStart);
if (existing != null && existing != DBNull.Value)
{
result.TaskID = Convert.ToInt32(existing);
result.Message = "This run already created its task.";
}
else if (job == null || job.ItemType != EnumCalendarItemType.ScheduleJob)
{
result.Message = "The schedule job was not found.";
}
else if (job.Status != EnumCalendarItemStatus.Active)
{
result.Message = "The schedule job is cancelled.";
}
else
{
CreateRunTask(tc, job, occurrenceStart, now, result);
}
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return result;
}
private void CreateRunTask(TransactionContext tc, CalendarItem job, DateTime occurrenceStart, DateTime now,
CalendarJobRunResult result)
{
// the person who set the job up must still be allowed to: an active HR / admin login
UserInfo owner = null;
DataReader drOwner = new DataReader(CalendarItemDA.GetUserBasics(tc, job.CreatedBy.ToString()));
if (drOwner.Read())
{
owner = new UserInfo
{
UserID = drOwner.GetInt32("USERID", 0),
Status = drOwner.GetInt32("STATUS", 0),
UserType = drOwner.GetInt32("USERTYPE", 0)
};
}
drOwner.Close();
if (owner == null || !IsUsableUserStatus(owner.Status) || owner.UserType == (int)EnumUserType.Employee)
{
result.Message = "The person who set up this schedule job is no longer an active HR user.";
return;
}
DataReader dr = new DataReader(CalendarItemAttendeeDA.GetByItem(tc, job.ID));
List rows = CreateAttendees(dr, true);
dr.Close();
CalendarItemAttendee jobOrganizer = rows.FirstOrDefault(a => a.Role == EnumAttendeeRole.Organizer);
if (jobOrganizer == null)
{
result.Message = "The organizer of this schedule job was not found.";
return;
}
List targets = rows.Where(a => a.Role != EnumAttendeeRole.Organizer && a.Status == EnumAttendeeStatus.Active).ToList();
string organizerKey = AttendeeKey(jobOrganizer);
bool selfAssigned = false;
List assignees = new List();
foreach (var target in ExpandTargets(tc, targets, job.PayrollTypeID))
{
CalendarItemAttendee row = target.Row;
if (AttendeeKey(row) == organizerKey)
{
selfAssigned = true; // the organizer is one of the targets: their own row carries the task
continue;
}
row.Role = EnumAttendeeRole.Assignee;
row.ResponseStatus = EnumResponseStatus.Pending;
row.TaskStatus = EnumCalendarTaskStatus.NotStarted;
row.IsRead = false;
row.Status = EnumAttendeeStatus.Active;
assignees.Add(row);
}
if (assignees.Count == 0 && !selfAssigned)
{
result.Message = "Nobody to assign: the job's targets have no active employees right now.";
return;
}
if (assignees.Count > MaxAttendees)
{
result.Message = "The job's targets have " + assignees.Count + " people; a task can have at most " + MaxAttendees + ".";
return;
}
CalendarItemAttendee organizer = new CalendarItemAttendee
{
AttendeeType = jobOrganizer.AttendeeType,
EmployeeID = jobOrganizer.EmployeeID,
UserID = jobOrganizer.UserID,
Role = EnumAttendeeRole.Organizer,
ResponseStatus = EnumResponseStatus.Accepted,
TaskStatus = selfAssigned ? EnumCalendarTaskStatus.NotStarted : (EnumCalendarTaskStatus?)null,
IsRead = true,
ReadDate = now,
Status = EnumAttendeeStatus.Active
};
organizer.Email = GetOrganizerEmail(tc, organizer);
CalendarItem task = new CalendarItem
{
ItemType = EnumCalendarItemType.Task,
Title = job.Title,
Description = job.Description,
Location = job.Location,
Color = job.Color,
Priority = job.Priority,
IsAllDay = job.IsAllDay,
StartDateTime = occurrenceStart,
EndDateTime = occurrenceStart + (job.EndDateTime - job.StartDateTime),
ReminderOffsets = job.ReminderOffsets,
ReminderChannel = job.ReminderChannel
};
if (task.IsAllDay)
{
task.StartDateTime = task.StartDateTime.Date;
task.EndDateTime = task.EndDateTime.Date;
}
task.NextTriggerAt = ComputeNextTrigger(task, assignees, now);
Insert(tc, job.CreatedBy, task, organizer, assignees, now, job.CreatedBy, job.PayrollTypeID, job.ID, occurrenceStart);
result.TaskID = task.ID;
result.Created = true;
result.AssigneeCount = assignees.Count + (selfAssigned ? 1 : 0);
}
///
/// What a run would trip over, checked when the job is saved instead of failing quietly at run time: no targets,
/// targets with nobody active in them right now, more people than a task can take, or a repeat that leaves
/// months out.
///
private void CheckScheduleJob(TransactionContext tc, CalendarItem job, CalendarItemAttendee organizer,
List targets, int payrollTypeID)
{
if (targets.Count == 0)
throw new ArgumentException("Add at least one target: an employee or a user.");
// the same people a run would assign right now; the organizer, when among them, keeps their own row
string organizerKey = AttendeeKey(organizer);
List people = ExpandTargets(tc, targets, payrollTypeID).Select(t => t.Row).ToList();
if (people.Count == 0)
throw new ArgumentException("Nobody to assign: the selected targets have no active employees right now.");
int assignees = people.Count(p => AttendeeKey(p) != organizerKey);
if (assignees > MaxAttendees)
throw new ArgumentException("The selected targets have " + assignees + " people right now; a task can have at most "
+ MaxAttendees + ".");
string skipped = CalendarRecurrence.SkippedPeriodsProblem(job);
if (skipped != null)
throw new ArgumentException(skipped);
}
///
/// The people a schedule job's target rows stand for right now: picked employees who are still live, the live
/// employees of picked departments (of the given payroll type), and picked user accounts that are still usable.
/// Each person once, with name and e-mail filled in; DepartmentID is the employee's department.
///
private List<(CalendarItemAttendee Row, int? DepartmentID)> ExpandTargets(TransactionContext tc,
List targets, int payrollTypeID)
{
Dictionary employees = new Dictionary();
List employeeIDs = targets.Where(t => t.AttendeeType == EnumAttendeeType.Employee && t.EmployeeID.HasValue)
.Select(t => t.EmployeeID.Value).Distinct().ToList();
foreach (EmployeeInfo employee in GetEmployees(tc, employeeIDs).Where(e => e.Status == (int)EnumEmployeeStatus.Live))
employees[employee.EmployeeID] = employee;
List departmentIDs = targets.Where(t => t.AttendeeType == EnumAttendeeType.Department && t.DepartmentID.HasValue)
.Select(t => t.DepartmentID.Value).Distinct().ToList();
if (departmentIDs.Count > 0)
{
DataReader dr = new DataReader(CalendarItemDA.GetLiveEmployeesOfDepartments(tc, string.Join(",", departmentIDs), payrollTypeID));
while (dr.Read())
{
EmployeeInfo employee = ReadEmployee(dr);
if (!employees.ContainsKey(employee.EmployeeID))
employees.Add(employee.EmployeeID, employee);
}
dr.Close();
}
List<(CalendarItemAttendee, int?)> people = employees.Values
.Select(e => (new CalendarItemAttendee
{
AttendeeType = EnumAttendeeType.Employee,
EmployeeID = e.EmployeeID,
Email = e.Email,
Name = e.Name,
EmployeeNo = e.EmployeeNo
}, e.DepartmentID))
.ToList();
List userIDs = targets.Where(t => t.AttendeeType == EnumAttendeeType.User && t.UserID.HasValue)
.Select(t => t.UserID.Value).Distinct().ToList();
if (userIDs.Count > 0)
{
DataReader dr = new DataReader(CalendarItemDA.GetUserBasics(tc, string.Join(",", userIDs)));
while (dr.Read())
{
int? employeeID = dr.GetInt32("EMPLOYEEID");
// an account that belongs to an employee is stored as that employee when the job is saved
if (!IsUsableUserStatus(dr.GetInt32("STATUS", 0)) || (employeeID.HasValue && employeeID.Value > 0))
continue;
people.Add((new CalendarItemAttendee
{
AttendeeType = EnumAttendeeType.User,
UserID = dr.GetInt32("USERID", 0),
Email = dr.GetString("Email"),
Name = dr.GetString("USERNAME", string.Empty)
}, (int?)null));
}
dr.Close();
}
return people;
}
/// The latest tasks a schedule job created, newest first.
private static List GetRecentRuns(TransactionContext tc, int jobID)
{
List runs = new List();
DataReader dr = new DataReader(CalendarItemDA.GetJobRuns(tc, jobID, MaxRecentRuns));
while (dr.Read())
{
runs.Add(new CalendarJobRun
{
TaskID = dr.GetInt32("CalendarItemID", 0),
RunAt = dr.GetDateTime("SourceOccurrence").Value,
Status = (EnumCalendarItemStatus)dr.GetInt32("Status", 1),
AssigneeCount = dr.GetInt32("AssigneeCount", 0),
DoneCount = dr.GetInt32("DoneCount", 0)
});
}
dr.Close();
return runs;
}
#endregion
#region Schedule emails
///
/// Creates the e-mail batch of one run in the central e-mail log: one recipient row per person the targets stand for
/// right now (departments expanded into their live employees), each with the subject and body tags filled in from
/// their own record, and the item's attachment shared by all. The run is claimed first (the item and run moment are
/// unique in CalendarEmailRun), so it is created once even if this is called again; a repeat call returns the batch
/// already created. The batch is logged as created by the person who set the schedule email up.
///
public CalendarEmailRunResult PrepareScheduleEmailRun(int itemID, DateTime runAt)
{
CalendarEmailRunResult result = new CalendarEmailRunResult { RunAt = runAt };
EmailDispatchRequest request = null;
int runID = 0;
TransactionContext tc = null;
try
{
DateTime now = DateTime.Now;
tc = TransactionContext.Begin(true);
CalendarItem item = null;
DataReader drItem = new DataReader(CalendarItemDA.Get(tc, itemID));
if (drItem.Read())
item = this.CreateObject(drItem);
drItem.Close();
if (item != null)
result.CreatedBy = item.CreatedBy;
// an earlier attempt may have claimed the run without getting as far as its batch
bool claimed = false;
DataReader drRun = new DataReader(CalendarEmailDA.GetRun(tc, itemID, runAt));
if (drRun.Read())
{
claimed = true;
runID = drRun.GetInt32("CalendarEmailRunID", 0);
result.MasterEmailLogID = drRun.GetInt32("MasterEmailLogID", 0);
}
drRun.Close();
if (result.MasterEmailLogID > 0)
result.Message = "This run already created its e-mail batch.";
else if (item == null || item.ItemType != EnumCalendarItemType.ScheduleEmail)
result.Message = "The schedule email was not found.";
else if (item.Status != EnumCalendarItemStatus.Active)
result.Message = "The schedule email is cancelled.";
else
{
request = BuildEmailRequest(tc, item, runAt, now, result);
if (request != null && !claimed)
{
runID = tc.GenerateID("CalendarEmailRun", "CalendarEmailRunID");
CalendarEmailDA.InsertRun(tc, runID, itemID, runAt, request.Recipients.Count, now);
}
}
tc.End();
tc = null;
if (request == null)
{
// a batch created earlier still has to be sent (or finished): hand back its shared file
if (result.MasterEmailLogID > 0)
result.Attachment = ReadBatchAttachment(result.MasterEmailLogID);
return result;
}
// The batch and every recipient row are written before the first mail goes out (EmailDispatchService).
int masterEmailLogID = new EmailDispatchService(new MasterEmailLogService()).CreateBatch(request);
tc = TransactionContext.Begin(true);
CalendarEmailDA.SetRunBatch(tc, runID, masterEmailLogID, request.Recipients.Count);
tc.End();
tc = null;
result.MasterEmailLogID = masterEmailLogID;
result.Created = true;
result.RecipientCount = request.Recipients.Count;
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return result;
}
///
/// The e-mail request of one run, or null (with result.Message set) when there is nobody to send to. The owner must
/// still be an active login: an HR / admin login, or a self-service employee, whose e-mail then reaches only the
/// recipients who are still in their team. Like Mail Manager's general mail, a schedule email always goes to each
/// recipient's own address (employee: EMAILADDRESS; user: the user's e-mail),
/// whatever Calendar:SendMail and Calendar:RedirectAllMailTo say (those stay for reminders and invitations).
///
private EmailDispatchRequest BuildEmailRequest(TransactionContext tc, CalendarItem item, DateTime runAt, DateTime now,
CalendarEmailRunResult result)
{
UserInfo owner = null;
DataReader drOwner = new DataReader(CalendarItemDA.GetUserBasics(tc, item.CreatedBy.ToString()));
if (drOwner.Read())
{
owner = new UserInfo
{
UserID = drOwner.GetInt32("USERID", 0),
Status = drOwner.GetInt32("STATUS", 0),
UserType = drOwner.GetInt32("USERTYPE", 0),
EmployeeID = drOwner.GetInt32("EMPLOYEEID")
};
}
drOwner.Close();
bool selfService = owner != null && owner.UserType == (int)EnumUserType.Employee;
if (owner == null || !IsUsableUserStatus(owner.Status) || (selfService && !(owner.EmployeeID > 0)))
{
result.Message = "The person who set up this schedule email is no longer an active user.";
return null;
}
DataReader dr = new DataReader(CalendarItemAttendeeDA.GetByItem(tc, item.ID));
List rows = CreateAttendees(dr, true);
dr.Close();
List targets = rows
.Where(a => a.Role != EnumAttendeeRole.Organizer && a.Status == EnumAttendeeStatus.Active).ToList();
targets = WithSelfRecipient(item, rows.FirstOrDefault(a => a.Role == EnumAttendeeRole.Organizer), targets);
List people = ExpandTargets(tc, targets, item.PayrollTypeID)
.Select(t => t.Row)
.OrderBy(p => p.Name)
.ToList();
if (people.Count == 0)
{
result.Message = "Nobody to send to: the recipients have no active employees right now.";
return null;
}
Dictionary tagData = GetTagData(tc,
people.Where(p => p.EmployeeID.HasValue).Select(p => p.EmployeeID.Value).ToList());
if (selfService)
{
// a self-service e-mail goes to the owner's own team only: someone who has left the team since is left out
people = people.Where(p => p.EmployeeID.HasValue && tagData.TryGetValue(p.EmployeeID.Value, out EmployeeTagData d)
&& (d.LineManagerID == owner.EmployeeID || d.EmployeeID == owner.EmployeeID)).ToList();
if (people.Count == 0)
{
result.Message = "Nobody to send to: none of the recipients is in the sender's team any more.";
return null;
}
}
EmailAttachmentInfo attachment = LoadAttachment(tc, item.ID);
List recipients = new List();
foreach (CalendarItemAttendee person in people)
{
EmployeeTagData data = null;
if (person.EmployeeID.HasValue)
tagData.TryGetValue(person.EmployeeID.Value, out data);
Dictionary values = ScheduleEmailTags.Values(data, person.Name, now);
EmailRecipient recipient = new EmailRecipient
{
EmployeeID = person.EmployeeID,
EmployeeNo = person.EmployeeNo,
EmployeeName = person.Name,
Subject = ScheduleEmailTags.FillSubject(item.Title, values),
Body = ScheduleEmailTags.FillBody(item.Description, values),
ReferenceID = item.ID
};
// no address: the dispatcher logs the person as Skipped ("Email address missing.")
recipient.MailTo = string.IsNullOrWhiteSpace(person.Email) ? string.Empty : person.Email.Trim();
recipients.Add(recipient);
}
string description = "Schedule Email: " + item.Title;
EmailDispatchRequest request = new EmailDispatchRequest
{
EmailType = EnumEmailType.ScheduleEmail,
Description = description.Length > MaxBatchDescriptionLength ? description.Substring(0, MaxBatchDescriptionLength) : description,
PayrollTypeID = item.PayrollTypeID,
UserID = item.CreatedBy,
Recipients = recipients,
// Everyone gets the same file: one copy on the batch header (the keys Mail Manager's general mail uses,
// so the log screen's download and retry find it), none on the recipient rows.
PreserveAttachment = false,
ParameterJson = JsonConvert.SerializeObject(new
{
attachmentName = attachment?.FileName,
attachmentData = attachment == null ? null : Convert.ToBase64String(attachment.Data),
payrollTypeId = item.PayrollTypeID,
calendarItemId = item.ID,
runAt = runAt.ToString("yyyy-MM-ddTHH:mm:ss")
})
};
if (attachment != null)
request.AttachmentResolver = (EmailRecipient r) => attachment;
result.Attachment = attachment;
result.RecipientCount = recipients.Count;
return request;
}
/// The one file of an e-mail batch, read back off its header (ParameterJson); null when it has none.
private static EmailAttachmentInfo ReadBatchAttachment(int masterEmailLogID)
{
MasterEmailLog log = new MasterEmailLogService().Get(masterEmailLogID);
if (log == null || string.IsNullOrWhiteSpace(log.ParameterJson))
return null;
try
{
JObject parameters = JsonConvert.DeserializeObject(log.ParameterJson);
string fileName = parameters.Value("attachmentName");
string base64 = parameters.Value("attachmentData");
if (string.IsNullOrWhiteSpace(fileName) || string.IsNullOrWhiteSpace(base64))
return null;
return new EmailAttachmentInfo(fileName, Convert.FromBase64String(base64));
}
catch (Exception e)
{
ExceptionLog.Write(e);
return null;
}
}
///
/// A schedule email's targets plus its organizer when the organizer picked themselves as a recipient (their row
/// then carries a task status, see BuildOrganizer). Other kinds of item: the targets as they are.
///
private static List WithSelfRecipient(CalendarItem item, CalendarItemAttendee organizer,
List targets)
{
if (item.ItemType != EnumCalendarItemType.ScheduleEmail || organizer == null || !organizer.TaskStatus.HasValue
|| organizer.Status != EnumAttendeeStatus.Active)
return targets;
return targets.Concat(new[] { organizer }).ToList();
}
/// What a run would trip over, checked when the schedule email is saved: no recipients, or nobody active in them.
private void CheckScheduleEmail(TransactionContext tc, CalendarItem item, List targets, int payrollTypeID)
{
if (targets.Count == 0)
throw new ArgumentException("Add at least one recipient: an employee or a user.");
if (ExpandTargets(tc, targets, payrollTypeID).Count == 0)
throw new ArgumentException("Nobody to send to: the selected recipients have no active employees right now.");
string skipped = CalendarRecurrence.SkippedPeriodsProblem(item);
if (skipped != null)
throw new ArgumentException(skipped);
}
///
/// A schedule email is sent at one moment: no end, no "entire day", no location, priority or reminders. Its end is
/// its start (every check on dates then holds as for any item).
///
private static void NormalizeScheduleEmail(CalendarItem item)
{
item.IsAllDay = false;
item.EndDateTime = item.StartDateTime;
item.Location = null;
item.Priority = null;
item.ReminderOffsets = null;
item.ReminderChannel = null;
}
/// The new attachment sent with a save, checked; null when none was sent.
private static byte[] ReadNewAttachment(CalendarItem item)
{
if (item.ItemType != EnumCalendarItemType.ScheduleEmail || string.IsNullOrWhiteSpace(item.AttachmentData))
return null;
item.AttachmentName = string.IsNullOrWhiteSpace(item.AttachmentName) ? null : FileNameOnly(item.AttachmentName);
if (item.AttachmentName == null)
throw new ArgumentException("The attachment has no file name.");
if (item.AttachmentName.Length > MaxAttachmentNameLength)
throw new ArgumentException("The attachment's file name can be at most " + MaxAttachmentNameLength + " characters.");
byte[] data;
try
{
data = Convert.FromBase64String(item.AttachmentData);
}
catch (FormatException)
{
throw new ArgumentException("The attachment could not be read. Please pick it again.");
}
if (data.Length == 0)
throw new ArgumentException("The attachment is empty.");
if (data.Length > MaxAttachmentBytes)
throw new ArgumentException("The attachment is larger than " + (MaxAttachmentBytes / (1024 * 1024)) + " MB.");
return data;
}
/// A file name without any folder part ("C:\x\a.pdf" -> "a.pdf").
private static string FileNameOnly(string fileName)
{
string name = fileName.Trim();
int slash = Math.Max(name.LastIndexOf('/'), name.LastIndexOf('\\'));
return slash >= 0 ? name.Substring(slash + 1).Trim() : name;
}
///
/// Brings the stored attachment in line with the save: a new file replaces it, RemoveAttachment drops it, and
/// otherwise it stays; a part split off a repeating schedule email takes the series' file along.
///
private static void SaveAttachment(TransactionContext tc, CurrentUser user, CalendarItem item, CalendarItem existing,
byte[] newAttachment, DateTime now)
{
if (newAttachment != null)
{
CalendarEmailDA.DeleteAttachments(tc, item.ID);
CalendarEmailDA.InsertAttachment(tc, tc.GenerateID("CalendarItemAttachment", "CalendarItemAttachmentID"), item.ID,
item.AttachmentName, newAttachment, user.UserID, now);
}
else if (item.RemoveAttachment)
{
CalendarEmailDA.DeleteAttachments(tc, item.ID);
}
else if (existing != null && existing.ID != item.ID)
{
CalendarEmailDA.CopyAttachment(tc, tc.GenerateID("CalendarItemAttachment", "CalendarItemAttachmentID"),
existing.ID, item.ID, user.UserID, now);
}
}
/// Fills the item's attachment name and size (not the bytes).
private static void LoadAttachmentInfo(TransactionContext tc, CalendarItem item)
{
DataReader dr = new DataReader(CalendarEmailDA.GetAttachmentInfo(tc, item.ID));
if (dr.Read())
{
item.AttachmentName = dr.GetString("FileName");
item.AttachmentSize = dr.GetInt32("FileSize");
}
dr.Close();
}
private static EmailAttachmentInfo LoadAttachment(TransactionContext tc, int calendarItemID)
{
EmailAttachmentInfo attachment = null;
System.Data.IDataReader reader = CalendarEmailDA.GetAttachment(tc, calendarItemID);
try
{
if (reader.Read())
attachment = new EmailAttachmentInfo(Convert.ToString(reader["FileName"]), (byte[])reader["FileData"]);
}
finally
{
reader.Close();
}
return attachment;
}
/// The latest runs of a schedule email, newest first, with their sent / failed counts.
private static List GetRecentEmailRuns(TransactionContext tc, int calendarItemID)
{
List runs = new List();
DataReader dr = new DataReader(CalendarEmailDA.GetRuns(tc, calendarItemID, MaxRecentRuns));
while (dr.Read())
{
runs.Add(new CalendarEmailRun
{
RunAt = dr.GetDateTime("RunAt").Value,
MasterEmailLogID = dr.GetInt32("MasterEmailLogID"),
TotalCount = dr.GetInt32("TotalCount", 0),
SentCount = dr.GetInt32("SentCount", 0),
FailedCount = dr.GetInt32("FailedCount", 0),
SkippedCount = dr.GetInt32("SkippedCount", 0),
PendingCount = dr.GetInt32("PendingCount", 0)
});
}
dr.Close();
return runs;
}
/// What the tags are filled from, for the given employees, by employee ID.
private static Dictionary GetTagData(TransactionContext tc, List employeeIDs)
{
Dictionary data = new Dictionary();
if (employeeIDs.Count == 0)
return data;
DataReader dr = new DataReader(CalendarEmailDA.GetEmployeeTagData(tc, string.Join(",", employeeIDs.Distinct())));
while (dr.Read())
{
EmployeeTagData row = new EmployeeTagData
{
EmployeeID = dr.GetInt32("EMPLOYEEID", 0),
EmployeeNo = dr.GetString("EMPLOYEENO"),
Name = dr.GetString("NAME"),
Gender = (EnumGender)dr.GetInt32("GENDER", 0),
MaritalStatus = (EnumMaritalStatus)dr.GetInt32("MARITALSTATUSID", 0),
JoiningDate = dr.GetDateTime("JOININGDATE"),
BasicSalary = dr.GetDouble("BASICSALARY"),
GrossSalary = dr.GetDouble("GROSSSALARY"),
Designation = dr.GetString("DesignationName"),
Department = dr.GetString("DepartmentName"),
Location = dr.GetString("LocationName"),
Category = dr.GetString("CategoryName"),
Religion = dr.GetString("ReligionName"),
LineManager = dr.GetString("LineManagerName"),
LineManagerID = dr.GetInt32("LINEMANAGERID")
};
data[row.EmployeeID] = row;
}
dr.Close();
return data;
}
#endregion
#region Save
public CalendarSaveResult Save(CurrentUser user, CalendarItem item)
{
CalendarSaveResult result = new CalendarSaveResult();
TransactionContext tc = null;
try
{
RequireUser(user);
if (item != null && item.ItemType == EnumCalendarItemType.ScheduleEmail)
NormalizeScheduleEmail(item);
ValidateItem(item);
if (!user.PayrollTypeID.HasValue)
throw new ArgumentException("Payroll type is not selected.");
if (IsScheduled(item.ItemType))
CheckCanUseScheduled(user, item.ItemType);
byte[] newAttachment = ReadNewAttachment(item);
DateTime now = DateTime.Now;
tc = TransactionContext.Begin(true);
CalendarItem existing = null;
List current = null;
if (!item.IsNew)
{
existing = LoadItem(tc, item.ID);
CheckCanChange(tc, user, existing);
if (existing.ItemType != item.ItemType)
throw new ArgumentException("The type of a calendar item cannot be changed.");
DataReader dr = new DataReader(CalendarItemAttendeeDA.GetByItem(tc, item.ID));
current = CreateAttendees(dr, false);
dr.Close();
}
// The organizer stays the person who created the item, also when HR changes it.
CalendarItemAttendee organizer = existing == null
? BuildOrganizer(user.EmployeeID, user.EmployeeID.HasValue ? (int?)null : user.UserID, user, item, now)
: BuildOrganizerOf(current, user, item, now);
organizer.Email = GetOrganizerEmail(tc, organizer); // so the organizer also gets the item in Outlook
List requested = ResolveAttendees(tc, user, item, organizer, now);
if (item.ItemType == EnumCalendarItemType.Task)
CheckTaskAssignPermission(tc, user, requested);
else if (item.ItemType == EnumCalendarItemType.ScheduleEmail)
CheckEmailRecipientPermission(tc, user, requested);
if (existing != null && item.OccurrenceStart.HasValue)
{
DateTime occurrence = item.OccurrenceStart.Value;
EnumCalendarEditScope scope = item.EditScope ?? EnumCalendarEditScope.ThisOccurrence;
if (string.IsNullOrWhiteSpace(existing.RecurrenceRule))
throw new ArgumentException("This calendar item does not repeat.");
if (scope == EnumCalendarEditScope.ThisOccurrence)
{
// ONE occurrence: the series skips that day and the changes become a new one-off item.
SkipOccurrence(tc, user, existing, occurrence, now);
StartAsNewItem(item, requested);
item.RecurrenceRule = null;
item.RecurrenceEndDate = null;
item.ExceptionDates = null;
result.SeriesID = existing.ID;
current = null;
}
else if (!CalendarRecurrence.IsFirstOccurrence(existing, occurrence))
{
// This and following: the series ends before that day and the changes become a new series from it.
CheckOccurrence(existing, occurrence);
bool sameRule = string.Equals(item.RecurrenceRule, existing.RecurrenceRule, StringComparison.Ordinal);
int datesBefore = CalendarRecurrence.CountBefore(existing, occurrence);
string laterSkips = CalendarRecurrence.SplitExceptionDates(existing.ExceptionDates, occurrence, true);
EndSeriesBefore(tc, user, existing, occurrence, now);
StartAsNewItem(item, requested);
item.ExceptionDates = item.RecurrenceRule == null ? null : laterSkips;
if (sameRule)
item.RecurrenceRule = ReduceCount(item.RecurrenceRule, datesBefore);
CalendarRecurrence.Normalize(item);
result.SeriesID = existing.ID;
current = null;
}
// "This and following" from the first date is a change to the whole series.
}
if (item.ItemType == EnumCalendarItemType.ScheduleJob)
CheckScheduleJob(tc, item, organizer, requested, existing?.PayrollTypeID ?? user.PayrollTypeID.Value);
else if (item.ItemType == EnumCalendarItemType.ScheduleEmail)
CheckScheduleEmail(tc, item, WithSelfRecipient(item, organizer, requested), existing?.PayrollTypeID ?? user.PayrollTypeID.Value);
item.NextTriggerAt = ComputeNextTrigger(item, requested, now);
if (item.ItemType == EnumCalendarItemType.ScheduleJob && !item.NextTriggerAt.HasValue)
throw new ArgumentException("This schedule job would never run: its first run (start) must be later than now.");
if (item.ItemType == EnumCalendarItemType.ScheduleEmail && !item.NextTriggerAt.HasValue)
throw new ArgumentException("This schedule email would never be sent: its send time must be later than now.");
if (item.IsNew)
{
// A part split off a series keeps that series' organizer and payroll type.
Insert(tc, user.UserID, item, organizer, requested, now,
existing?.CreatedBy ?? user.UserID, existing?.PayrollTypeID ?? user.PayrollTypeID.Value);
result.DetailsChanged = true;
}
else
{
result.DetailsChanged = Update(tc, user, item, existing, organizer, requested, current, now);
}
if (item.ItemType == EnumCalendarItemType.ScheduleEmail)
SaveAttachment(tc, user, item, existing, newAttachment, now);
result.CalendarItemID = item.ID;
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return result;
}
/// Turns a request that edits part of a series into a new item (the item and its people get new IDs).
private void StartAsNewItem(CalendarItem item, List requested)
{
base.SetObjectID(item, 0);
requested.ForEach(a => base.SetObjectID(a, 0));
}
///
/// A new series that keeps the old rule (and so its COUNT) continues the old one: the dates already used up by
/// the shortened series are taken off the count.
///
private static string ReduceCount(string rule, int datesBefore)
{
if (string.IsNullOrWhiteSpace(rule) || datesBefore <= 0)
return rule;
List parts = rule.Split(';', StringSplitOptions.RemoveEmptyEntries).ToList();
int index = parts.FindIndex(p => p.StartsWith("COUNT=", StringComparison.OrdinalIgnoreCase));
if (index < 0 || !int.TryParse(parts[index].Substring("COUNT=".Length), out int count))
return rule;
parts[index] = "COUNT=" + Math.Max(1, count - datesBefore);
return string.Join(";", parts);
}
/// Who is saving (stamped on the attendee rows).
/// CreatedBy: the organizer's user ID.
/// For a task created by a schedule job: the job (and, in sourceOccurrence, the run).
private void Insert(TransactionContext tc, int actingUserID, CalendarItem item,
CalendarItemAttendee organizer, List requested, DateTime now, int organizerUserID, int payrollTypeID,
int? sourceItemID = null, DateTime? sourceOccurrence = null)
{
base.SetObjectID(item, tc.GenerateID("CalendarItem", "CalendarItemID"));
item.CreatedBy = organizerUserID;
item.CreatedDate = now;
item.ModifiedBy = null;
item.ModifiedDate = null;
item.PayrollTypeID = payrollTypeID;
item.Status = EnumCalendarItemStatus.Active;
item.OutlookSequence = 1;
item.OutlookEventID = null;
item.SourceItemID = sourceItemID;
item.SourceOccurrence = sourceItemID.HasValue ? sourceOccurrence : null;
CalendarItemDA.Insert(tc, item);
foreach (CalendarItemAttendee attendee in new[] { organizer }.Concat(requested))
{
base.SetObjectID(attendee, tc.GenerateID("CalendarItemAttendee", "AttendeeID"));
attendee.CalendarItemID = item.ID;
attendee.CreatedBy = actingUserID;
attendee.CreatedDate = now;
CalendarItemAttendeeDA.Insert(tc, attendee);
}
}
/// Saves changes to an existing item. Returns true when what everyone sees changed.
private bool Update(TransactionContext tc, CurrentUser user, CalendarItem item, CalendarItem existing,
CalendarItemAttendee organizer, List requested, List current, DateTime now)
{
AttendeeChanges changes = SyncAttendees(tc, user, item.ID, organizer, requested, current, now);
// What the Outlook invitation shows to everyone.
bool detailsChanged = existing.Title != item.Title
|| existing.Description != item.Description
|| existing.Location != item.Location
|| existing.StartDateTime != item.StartDateTime
|| existing.EndDateTime != item.EndDateTime
|| existing.IsAllDay != item.IsAllDay
|| existing.Priority != item.Priority
|| existing.RecurrenceRule != item.RecurrenceRule
|| existing.ExceptionDates != item.ExceptionDates;
// People added or removed alone need no new Outlook version (new people have none yet, removed people get a
// cancellation). Someone's own title or dates, or someone coming back after a cancellation, do: their
// invitation must be newer than the one they already have.
bool newOutlookVersion = detailsChanged || changes.OverridesChanged || changes.Reactivated;
// Values nobody can change through this screen.
item.CreatedBy = existing.CreatedBy;
item.CreatedDate = existing.CreatedDate;
item.PayrollTypeID = existing.PayrollTypeID;
item.Status = existing.Status;
item.OutlookEventID = existing.OutlookEventID;
item.SourceItemID = existing.SourceItemID;
item.SourceOccurrence = existing.SourceOccurrence;
item.OutlookSequence = existing.OutlookSequence + (newOutlookVersion ? 1 : 0);
item.ModifiedBy = user.UserID;
item.ModifiedDate = now;
CalendarItemDA.Update(tc, item);
return detailsChanged;
}
private sealed class AttendeeChanges
{
/// Someone who stays on the item got a different own title, own dates or role.
public bool OverridesChanged;
/// Someone who had been removed is on the item again.
public bool Reactivated;
}
///
/// Brings the stored attendee rows in line with the requested list: new people are inserted, changed people are
/// updated (and re-activated if they had been removed), people no longer requested are marked Removed.
/// Rows that do not change are not written, so afterwards the rows stamped with this save's time are exactly
/// the people the change concerns. The organizer row is kept.
///
private AttendeeChanges SyncAttendees(TransactionContext tc, CurrentUser user, int calendarItemID,
CalendarItemAttendee organizer, List requested,
List current, DateTime now)
{
AttendeeChanges changes = new AttendeeChanges();
CalendarItemAttendee currentOrganizer = current.FirstOrDefault(a => a.Role == EnumAttendeeRole.Organizer);
if (currentOrganizer != null)
{
// The organizer's own task status follows whether the organizer assigned the task to themselves.
bool wasSelfAssigned = currentOrganizer.TaskStatus.HasValue;
bool isSelfAssigned = organizer.TaskStatus.HasValue;
// Items saved before Outlook invitations existed have no organizer e-mail yet.
bool emailChanged = !string.Equals(currentOrganizer.Email, organizer.Email, StringComparison.OrdinalIgnoreCase);
if (wasSelfAssigned != isSelfAssigned || emailChanged)
{
if (wasSelfAssigned != isSelfAssigned)
currentOrganizer.TaskStatus = isSelfAssigned ? EnumCalendarTaskStatus.NotStarted : (EnumCalendarTaskStatus?)null;
currentOrganizer.Email = organizer.Email;
currentOrganizer.ModifiedBy = user.UserID;
currentOrganizer.ModifiedDate = now;
CalendarItemAttendeeDA.UpdateByOrganizer(tc, currentOrganizer);
}
}
foreach (CalendarItemAttendee wanted in requested)
{
CalendarItemAttendee row = current.FirstOrDefault(a => a.Role != EnumAttendeeRole.Organizer && AttendeeKey(a) == AttendeeKey(wanted));
if (row == null)
{
base.SetObjectID(wanted, tc.GenerateID("CalendarItemAttendee", "AttendeeID"));
wanted.CalendarItemID = calendarItemID;
wanted.CreatedBy = user.UserID;
wanted.CreatedDate = now;
CalendarItemAttendeeDA.Insert(tc, wanted);
continue;
}
// Keep the attendee's own progress; only give a task status to someone who has none yet.
EnumCalendarTaskStatus? taskStatus = !wanted.TaskStatus.HasValue ? null : (row.TaskStatus ?? wanted.TaskStatus);
bool reactivated = row.Status != EnumAttendeeStatus.Active;
bool overridesChanged = row.TitleOverride != wanted.TitleOverride || row.SubjectOverride != wanted.SubjectOverride
|| row.FromOverride != wanted.FromOverride || row.ToOverride != wanted.ToOverride || row.Role != wanted.Role;
bool otherChanged = !string.Equals(row.Email, wanted.Email, StringComparison.OrdinalIgnoreCase)
|| row.TaskStatus != taskStatus;
if (!reactivated && !overridesChanged && !otherChanged)
continue;
if (reactivated)
changes.Reactivated = true;
else if (overridesChanged)
changes.OverridesChanged = true;
row.Role = wanted.Role;
row.Email = wanted.Email;
row.TitleOverride = wanted.TitleOverride;
row.SubjectOverride = wanted.SubjectOverride;
row.FromOverride = wanted.FromOverride;
row.ToOverride = wanted.ToOverride;
row.TaskStatus = taskStatus;
row.Status = EnumAttendeeStatus.Active;
row.ModifiedBy = user.UserID;
row.ModifiedDate = now;
CalendarItemAttendeeDA.UpdateByOrganizer(tc, row);
// Invited again after being removed: an old answer (e.g. a "No" that also stops reminders) no longer holds.
if (reactivated && row.ResponseStatus != EnumResponseStatus.Pending)
{
row.ResponseStatus = EnumResponseStatus.Pending;
CalendarItemAttendeeDA.UpdateResponse(tc, row.ID, EnumResponseStatus.Pending, user.UserID, now);
}
}
HashSet wantedKeys = new HashSet(requested.Select(AttendeeKey));
foreach (CalendarItemAttendee row in current.Where(a => a.Role != EnumAttendeeRole.Organizer
&& a.Status == EnumAttendeeStatus.Active && !wantedKeys.Contains(AttendeeKey(a))))
{
row.Status = EnumAttendeeStatus.Removed;
row.ModifiedBy = user.UserID;
row.ModifiedDate = now;
CalendarItemAttendeeDA.UpdateByOrganizer(tc, row);
}
return changes;
}
#endregion
#region Cancel / Respond / Task status / Read
public EnumCalendarChange Cancel(CurrentUser user, int id, DateTime? occurrenceStart, EnumCalendarEditScope? scope)
{
EnumCalendarChange change = EnumCalendarChange.Cancelled;
TransactionContext tc = null;
try
{
RequireUser(user);
DateTime now = DateTime.Now;
tc = TransactionContext.Begin(true);
CalendarItem oItem = LoadItem(tc, id);
CheckCanChange(tc, user, oItem);
bool wholeItem = !occurrenceStart.HasValue;
if (occurrenceStart.HasValue)
{
if (string.IsNullOrWhiteSpace(oItem.RecurrenceRule))
throw new ArgumentException("This calendar item does not repeat.");
if ((scope ?? EnumCalendarEditScope.ThisOccurrence) == EnumCalendarEditScope.ThisOccurrence)
{
SkipOccurrence(tc, user, oItem, occurrenceStart.Value, now);
change = EnumCalendarChange.Updated;
}
else if (CalendarRecurrence.IsFirstOccurrence(oItem, occurrenceStart.Value))
{
wholeItem = true; // from the first date on = the whole series
}
else
{
CheckOccurrence(oItem, occurrenceStart.Value);
EndSeriesBefore(tc, user, oItem, occurrenceStart.Value, now);
change = EnumCalendarChange.Updated;
}
}
if (wholeItem)
{
CalendarItemDA.UpdateStatus(tc, id, EnumCalendarItemStatus.Cancelled, oItem.OutlookSequence + 1,
null, user.UserID, now);
change = EnumCalendarChange.Cancelled;
}
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return change;
}
public int Respond(CurrentUser user, int calendarItemID, EnumResponseStatus responseStatus)
{
TransactionContext tc = null;
int attendeeID = 0;
try
{
RequireUser(user);
if (!Enum.IsDefined(typeof(EnumResponseStatus), responseStatus) || responseStatus == EnumResponseStatus.Pending)
throw new ArgumentException("Please choose Yes, No or Maybe.");
tc = TransactionContext.Begin(true);
CalendarItem oItem = LoadItem(tc, calendarItemID);
if (oItem.ItemType != EnumCalendarItemType.Event)
throw new ArgumentException("Only events take a Yes / No / Maybe answer.");
if (oItem.Status != EnumCalendarItemStatus.Active)
throw new ArgumentException("This event is cancelled or completed.");
CalendarItemAttendee me = LoadMyAttendee(tc, user, calendarItemID);
if (me == null)
throw new UnauthorizedAccessException("You are not invited to this event.");
if (me.Role == EnumAttendeeRole.Organizer)
throw new ArgumentException("The organizer does not answer their own event.");
CalendarItemAttendeeDA.UpdateResponse(tc, me.ID, responseStatus, user.UserID, DateTime.Now);
attendeeID = me.ID;
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return attendeeID;
}
public int UpdateTaskStatus(CurrentUser user, int calendarItemID, EnumCalendarTaskStatus taskStatus, string remarks)
{
TransactionContext tc = null;
int attendeeID = 0;
try
{
RequireUser(user);
if (!Enum.IsDefined(typeof(EnumCalendarTaskStatus), taskStatus))
throw new ArgumentException("Task status is not valid.");
remarks = string.IsNullOrWhiteSpace(remarks) ? null : remarks.Trim();
if (remarks != null && remarks.Length > MaxRemarksLength)
throw new ArgumentException("Remarks can be at most " + MaxRemarksLength + " characters.");
tc = TransactionContext.Begin(true);
CalendarItem oItem = LoadItem(tc, calendarItemID);
if (oItem.ItemType != EnumCalendarItemType.Task)
throw new ArgumentException("This calendar item is not a task.");
if (oItem.Status != EnumCalendarItemStatus.Active)
throw new ArgumentException("This task is cancelled or completed.");
CalendarItemAttendee me = LoadMyAttendee(tc, user, calendarItemID);
if (me == null || !me.TaskStatus.HasValue)
throw new UnauthorizedAccessException("This task is not assigned to you.");
DateTime now = DateTime.Now;
CalendarItemAttendeeDA.UpdateTaskStatus(tc, me.ID, taskStatus, remarks, remarks == null ? (DateTime?)null : now,
user.UserID, now);
attendeeID = me.ID;
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return attendeeID;
}
public void MarkRead(CurrentUser user, int calendarItemID)
{
TransactionContext tc = null;
try
{
RequireUser(user);
tc = TransactionContext.Begin(true);
CalendarItemAttendee me = LoadMyAttendee(tc, user, calendarItemID);
if (me == null)
throw new UnauthorizedAccessException("You are not part of this calendar item.");
if (!me.IsRead)
CalendarItemAttendeeDA.MarkRead(tc, me.ID, DateTime.Now);
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
#endregion
#region Repeating items
/// Throws unless the repeating item has an occurrence starting exactly at .
private static void CheckOccurrence(CalendarItem oItem, DateTime occurrenceStart)
{
if (!CalendarRecurrence.Occurrences(oItem, occurrenceStart).Any(o => o.Start == occurrenceStart))
throw new ArgumentException("That occurrence was not found.");
}
///
/// Skips one occurrence of a loaded, repeating item (its day goes into ExceptionDates); the caller has checked
/// the user may change it. The next reminder is worked out again and the Outlook version moves on.
///
private void SkipOccurrence(TransactionContext tc, CurrentUser user, CalendarItem oItem, DateTime occurrenceStart, DateTime now)
{
CheckOccurrence(oItem, occurrenceStart);
oItem.ExceptionDates = CalendarRecurrence.AddExceptionDate(oItem.ExceptionDates, occurrenceStart);
oItem.OutlookSequence++;
CalendarItemDA.UpdateExceptionDates(tc, oItem.ID, oItem.ExceptionDates, ComputeNextTrigger(oItem, null, now),
oItem.OutlookSequence, user.UserID, now);
}
///
/// Ends a loaded, repeating item just before ("this and following"): its rule
/// gets an UNTIL, skipped days from then on are dropped, the next reminder is worked out again and the Outlook
/// version moves on (Outlook then removes the later dates).
///
private void EndSeriesBefore(TransactionContext tc, CurrentUser user, CalendarItem oItem, DateTime occurrenceStart, DateTime now)
{
oItem.RecurrenceRule = CalendarRecurrence.RuleEndingBefore(oItem, occurrenceStart);
oItem.ExceptionDates = CalendarRecurrence.SplitExceptionDates(oItem.ExceptionDates, occurrenceStart, false);
CalendarRecurrence.Normalize(oItem);
oItem.OutlookSequence++;
CalendarItemDA.UpdateRecurrence(tc, oItem.ID, oItem.RecurrenceRule, oItem.RecurrenceEndDate, oItem.ExceptionDates,
ComputeNextTrigger(oItem, null, now), oItem.OutlookSequence, user.UserID, now);
}
#endregion
#region System use (Hangfire jobs)
public List TakeDueReminders(DateTime now, int graceMinutes, int maxItems)
{
List due = new List();
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin(true);
DataReader dr = new DataReader(CalendarItemDA.GetDueReminders(tc, now, maxItems));
List items = this.CreateObjects(dr);
dr.Close();
DateTime staleBefore = now.AddMinutes(-Math.Max(graceMinutes, 0));
foreach (CalendarItem oItem in items)
{
DateTime trigger = oItem.NextTriggerAt.Value;
List offsets;
try
{
offsets = oItem.GetReminderOffsetMinutes();
}
catch (ArgumentException)
{
offsets = new List();
}
// Task assignees with their own start date are reminded from that date (one-off items only).
List ownStarts = string.IsNullOrWhiteSpace(oItem.RecurrenceRule)
? GetOwnStarts(tc, oItem.ID)
: null;
// A reminder older than the grace period (server was down) is skipped, and so is every
// other reminder that went stale with it; the next one is the first still worth sending.
bool stale = trigger < staleBefore;
DateTime? next = CalendarRecurrence.NextTrigger(oItem, offsets, stale ? staleBefore : trigger, ownStarts);
var occurrence = stale ? null : CalendarRecurrence.OccurrenceForTrigger(oItem, offsets, trigger, ownStarts);
// Only the caller that moves NextTriggerAt on may send, so a reminder can never go out twice.
if (!CalendarItemDA.AdvanceTrigger(tc, oItem.ID, trigger, next) || occurrence == null)
continue;
due.Add(new CalendarDueReminder
{
CalendarItemID = oItem.ID,
TriggerAt = trigger,
OccurrenceStart = occurrence.Value.Start,
OccurrenceEnd = occurrence.Value.End
});
}
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return due;
}
public CalendarItem GetForSystem(int id)
{
CalendarItem oItem = null;
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin();
DataReader dr = new DataReader(CalendarItemDA.Get(tc, id));
if (dr.Read())
{
oItem = this.CreateObject(dr);
oItem.OrganizerName = dr.GetString("OrganizerName");
}
dr.Close();
if (oItem != null)
{
DataReader drAttendees = new DataReader(CalendarItemAttendeeDA.GetByItem(tc, id));
oItem.Attendees = CreateAttendees(drAttendees, true);
drAttendees.Close();
}
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return oItem;
}
public bool ClaimReminder(int attendeeID, DateTime triggerAt)
{
bool claimed = false;
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin(true);
claimed = CalendarItemAttendeeDA.ClaimReminder(tc, attendeeID, triggerAt);
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
return claimed;
}
public void ReleaseReminder(int attendeeID, DateTime triggerAt, DateTime? previousReminderAt)
{
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin(true);
CalendarItemAttendeeDA.ReleaseReminder(tc, attendeeID, triggerAt, previousReminderAt);
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
public void MarkInviteSent(int attendeeID, int? outlookSequence)
{
TransactionContext tc = null;
try
{
tc = TransactionContext.Begin(true);
CalendarItemAttendeeDA.SetInviteSent(tc, attendeeID, outlookSequence);
tc.End();
}
catch (Exception e)
{
#region Handle Exception
if (tc != null)
tc.HandleError();
ExceptionLog.Write(e);
throw new ServiceException(e.Message, e);
#endregion
}
}
public void AddInAppNotification(int employeeID, string header, string description, int calendarItemID, int createdBy)
{
// Same bell notification table the workflow module uses (EmployeeNotification).
EmployeeNotification notification = new EmployeeNotification(employeeID, header, description, DateTime.Now, createdBy)
{
Link = "/calendar/my-calendar",
ReferenceID = calendarItemID,
IsRead = 0
};
new EmployeeNotificationService().Insert(notification);
}
#endregion
#region Helpers: loading
private static void RequireUser(CurrentUser user)
{
if (user == null || user.UserID <= 0)
throw new UnauthorizedAccessException("Please log in again.");
}
/// HR / admin: any login that is not a self-service (employee) login.
private static bool IsHr(CurrentUser user)
{
return user.UserType != EnumUserType.Employee;
}
/// Schedule jobs are for HR / admin logins, and only while Calendar:ScheduleJobsEnabled is on.
private void CheckCanUseScheduleJobs(CurrentUser user)
{
if (!IsHr(user))
throw new UnauthorizedAccessException("Only HR can set up schedule jobs.");
if (!_settings.ScheduleJobsEnabled)
throw new ArgumentException("Schedule jobs are turned off.");
}
///
/// Schedule jobs and schedule emails are both HR's set-up that runs by itself on set dates: targets kept as
/// departments, a next run instead of reminders, and never shown to the people they target.
///
private static bool IsScheduled(EnumCalendarItemType itemType)
{
return itemType == EnumCalendarItemType.ScheduleJob || itemType == EnumCalendarItemType.ScheduleEmail;
}
///
/// The check of CheckCanUseScheduleJobs for either kind. Schedule emails (while Calendar:ScheduleEmailsEnabled is
/// on) are for HR / admin logins and for self-service employees, who may send them only to their own team
/// (CheckEmailRecipientPermission).
///
private void CheckCanUseScheduled(CurrentUser user, EnumCalendarItemType itemType)
{
if (itemType == EnumCalendarItemType.ScheduleJob)
{
CheckCanUseScheduleJobs(user);
return;
}
if (!IsHr(user) && !user.EmployeeID.HasValue)
throw new UnauthorizedAccessException("Only HR or an employee can set up schedule emails.");
if (!_settings.ScheduleEmailsEnabled)
throw new ArgumentException("Schedule emails are turned off.");
}
/// Whether the user may set up schedule emails (HR / admin, or a self-service employee), while they are on.
private bool CanUseScheduleEmails(CurrentUser user)
{
return _settings.ScheduleEmailsEnabled && (IsHr(user) || user.EmployeeID.HasValue);
}
/// "schedule job" or "schedule email", for messages.
private static string ScheduledTypeText(EnumCalendarItemType itemType)
{
return itemType == EnumCalendarItemType.ScheduleEmail ? "schedule email" : "schedule job";
}
///
/// The organizer and HR may change or cancel an item. The organizer is recognised by the login that created the
/// item or by their own Organizer row (), so the same person can manage it from both their
/// admin and self-service logins.
///
private static bool CanManage(CurrentUser user, CalendarItem oItem, CalendarItemAttendee me)
{
return oItem.CreatedBy == user.UserID || (me != null && me.Role == EnumAttendeeRole.Organizer) || IsHr(user);
}
private void CheckCanChange(TransactionContext tc, CurrentUser user, CalendarItem oItem)
{
if (!CanManage(user, oItem, LoadMyAttendee(tc, user, oItem.ID)))
throw new UnauthorizedAccessException("Only the organizer or HR can change this calendar item.");
if (oItem.Status != EnumCalendarItemStatus.Active)
throw new ArgumentException("A cancelled or completed calendar item cannot be changed.");
}
/// The different own start dates the attendees of a one-off item have.
private static List GetOwnStarts(TransactionContext tc, int calendarItemID)
{
List starts = new List();
DataReader dr = new DataReader(CalendarItemAttendeeDA.GetOverrideStarts(tc, calendarItemID));
while (dr.Read())
{
DateTime? start = dr.GetDateTime("FromOverride");
if (start.HasValue)
starts.Add(start.Value);
}
dr.Close();
return starts;
}
private CalendarItem LoadItem(TransactionContext tc, int id)
{
CalendarItem oItem = null;
DataReader dr = new DataReader(CalendarItemDA.Get(tc, id));
if (dr.Read())
{
oItem = this.CreateObject(dr);
oItem.OrganizerName = dr.GetString("OrganizerName");
}
dr.Close();
if (oItem == null)
throw new ArgumentException("The calendar item was not found.");
return oItem;
}
private CalendarItemAttendee LoadMyAttendee(TransactionContext tc, CurrentUser user, int calendarItemID)
{
DataReader dr = new DataReader(CalendarItemAttendeeDA.GetMine(tc, calendarItemID, user.EmployeeID ?? 0, user.UserID));
List rows = CreateAttendees(dr, false);
dr.Close();
return rows.FirstOrDefault();
}
private sealed class EmployeeInfo
{
public int EmployeeID;
public string Name;
public string EmployeeNo;
public string Email;
public int? LineManagerID;
public int? DepartmentID;
public int? LocationID;
public int Status;
public int PayrollTypeID;
}
private static EmployeeInfo ReadEmployee(DataReader dr)
{
return new EmployeeInfo
{
EmployeeID = dr.GetInt32("EMPLOYEEID", 0),
Name = dr.GetString("NAME", string.Empty),
EmployeeNo = dr.GetString("EMPLOYEENO"),
Email = dr.GetString("EMAILADDRESS"),
LineManagerID = dr.GetInt32("LINEMANAGERID"),
DepartmentID = dr.GetInt32("DEPARTMENTID"),
LocationID = dr.GetInt32("LOCATIONID"),
Status = dr.GetInt32("STATUS", 0),
PayrollTypeID = dr.GetInt32("PAYROLLTYPEID", 0)
};
}
private sealed class UserInfo
{
public int UserID;
public string Name;
public int Status;
public int UserType;
public int? EmployeeID;
public string Email;
}
/// Active (or approved) accounts can be added; not-yet-approved, locked, archived or inactive ones cannot.
private static bool IsUsableUserStatus(int status)
{
return status == (int)EnumAuthStatus.Active || status == (int)EnumAuthStatus.Approved;
}
///
/// Loads and checks the user accounts picked as participants: only admin logins may add users, and each one
/// must exist, be an admin-side account (not a self-service login) and be usable.
///
private static Dictionary GetPickedUsers(TransactionContext tc, CurrentUser user, List picked)
{
List userIDs = picked.Where(a => a.AttendeeType == EnumAttendeeType.User)
.Select(a => a.UserID.Value).Distinct().ToList();
Dictionary users = new Dictionary();
if (userIDs.Count == 0)
return users;
if (user.UserType == EnumUserType.Employee)
throw new UnauthorizedAccessException("Only admin users can add users as participants.");
DataReader dr = new DataReader(CalendarItemDA.GetUserBasics(tc, string.Join(",", userIDs)));
while (dr.Read())
{
UserInfo info = new UserInfo
{
UserID = dr.GetInt32("USERID", 0),
Name = dr.GetString("USERNAME", string.Empty),
Status = dr.GetInt32("STATUS", 0),
UserType = dr.GetInt32("USERTYPE", 0),
EmployeeID = dr.GetInt32("EMPLOYEEID"),
Email = dr.GetString("Email")
};
if (info.EmployeeID.HasValue && info.EmployeeID.Value <= 0)
info.EmployeeID = null;
users[info.UserID] = info;
}
dr.Close();
foreach (int userID in userIDs)
{
if (!users.TryGetValue(userID, out UserInfo info) || info.UserType == (int)EnumUserType.Employee)
throw new ArgumentException("A selected user was not found.");
if (!IsUsableUserStatus(info.Status))
throw new ArgumentException(info.Name + " is not an active user.");
}
return users;
}
/// The organizer's e-mail: the employee's address, or the user account's address for a non-employee.
private static string GetOrganizerEmail(TransactionContext tc, CalendarItemAttendee organizer)
{
if (organizer.EmployeeID.HasValue)
return GetEmployees(tc, new List { organizer.EmployeeID.Value }).FirstOrDefault()?.Email;
if (!organizer.UserID.HasValue)
return null;
string email = null;
DataReader dr = new DataReader(CalendarItemDA.GetUserBasics(tc, organizer.UserID.Value.ToString()));
if (dr.Read())
email = dr.GetString("Email");
dr.Close();
return email;
}
private static List GetEmployees(TransactionContext tc, List employeeIDs)
{
List employees = new List();
if (employeeIDs.Count == 0)
return employees;
DataReader dr = new DataReader(CalendarItemDA.GetEmployeeBasics(tc, string.Join(",", employeeIDs.Distinct())));
while (dr.Read())
employees.Add(ReadEmployee(dr));
dr.Close();
return employees;
}
#endregion
#region Helpers: validation, attendees, permissions
/// Checks and normalizes the fields the user typed. Throws ArgumentException on bad input.
private static void ValidateItem(CalendarItem item)
{
if (item == null)
throw new ArgumentException("Nothing to save.");
if (!Enum.IsDefined(typeof(EnumCalendarItemType), item.ItemType))
throw new ArgumentException("The type of the calendar item is not valid.");
// a schedule email's title is the e-mail's subject and its description the e-mail's body
bool isEmail = item.ItemType == EnumCalendarItemType.ScheduleEmail;
string titleName = isEmail ? "Subject" : "Title";
item.Title = (item.Title ?? string.Empty).Trim();
if (item.Title.Length == 0)
throw new ArgumentException(titleName + " is required.");
if (item.Title.Length > MaxTitleLength)
throw new ArgumentException(titleName + " can be at most " + MaxTitleLength + " characters.");
int maxDescription = isEmail ? MaxEmailBodyLength : MaxDescriptionLength;
item.Description = string.IsNullOrWhiteSpace(item.Description) ? null : item.Description.Trim();
if (isEmail && item.Description == null)
throw new ArgumentException("Email body is required.");
if (item.Description != null && item.Description.Length > maxDescription)
throw new ArgumentException((isEmail ? "Email body" : "Description") + " can be at most " + maxDescription + " characters.");
item.Location = string.IsNullOrWhiteSpace(item.Location) ? null : item.Location.Trim();
if (item.Location != null && item.Location.Length > MaxLocationLength)
throw new ArgumentException("Location can be at most " + MaxLocationLength + " characters.");
item.Color = string.IsNullOrWhiteSpace(item.Color) ? null : item.Color.Trim();
if (item.Color != null && !ColorPattern.IsMatch(item.Color))
throw new ArgumentException("Color is not valid.");
if (item.Priority.HasValue && !Enum.IsDefined(typeof(EnumCalendarPriority), item.Priority.Value))
throw new ArgumentException("Priority is not valid.");
if (item.IsAllDay)
{
item.StartDateTime = item.StartDateTime.Date;
item.EndDateTime = item.EndDateTime.Date;
}
if (item.StartDateTime.Year < 1900 || item.EndDateTime.Year < 1900)
throw new ArgumentException("Start and end are required.");
if (item.EndDateTime < item.StartDateTime)
throw new ArgumentException("End must not be before start.");
if ((item.EndDateTime - item.StartDateTime).TotalDays > MaxItemDays)
throw new ArgumentException("A calendar item can last at most " + MaxItemDays + " days.");
// Repeat rule (RRULE) and skipped days: checked, written in canonical form, series end worked out.
CalendarRecurrence.Normalize(item);
List offsets = item.GetReminderOffsetMinutes();
if (offsets.Count > MaxReminders)
throw new ArgumentException("At most " + MaxReminders + " reminders can be set.");
if (offsets.Any(m => m > MaxReminderMinutes))
throw new ArgumentException("A reminder can be at most one year before the start.");
item.ReminderOffsets = offsets.Count == 0 ? null : string.Join(",", offsets);
if (item.ReminderChannel.HasValue && !Enum.IsDefined(typeof(EnumReminderChannel), item.ReminderChannel.Value))
throw new ArgumentException("Reminder channel is not valid.");
if (offsets.Count == 0)
item.ReminderChannel = null;
else if (!item.ReminderChannel.HasValue)
item.ReminderChannel = EnumReminderChannel.Both;
if (item.Attendees == null)
item.Attendees = new List();
}
///
/// The organizer's own attendee row, for the organizer given by employee (or, for a non-employee, by user account).
/// The organizer gets a task status when the task lists them among the assignees; on a schedule email the same
/// mark means the organizer is one of its recipients (the organizer row is the only row a person can have on an
/// item, so it carries both).
///
private static CalendarItemAttendee BuildOrganizer(int? employeeID, int? userID, CurrentUser user, CalendarItem item, DateTime now)
{
bool organizerIsMe = employeeID.HasValue ? employeeID == user.EmployeeID : userID == user.UserID;
bool selfAssigned = (item.ItemType == EnumCalendarItemType.Task || item.ItemType == EnumCalendarItemType.ScheduleEmail)
&& item.Attendees.Any(a =>
a.Role != EnumAttendeeRole.Organizer
&& ((employeeID.HasValue && a.AttendeeType == EnumAttendeeType.Employee && a.EmployeeID == employeeID)
|| (!employeeID.HasValue && a.AttendeeType == EnumAttendeeType.User && a.UserID == userID)
// my own user account picked from the users list while I am the organizer as an employee
|| (employeeID.HasValue && organizerIsMe && a.AttendeeType == EnumAttendeeType.User && a.UserID == user.UserID)));
return new CalendarItemAttendee
{
AttendeeType = employeeID.HasValue ? EnumAttendeeType.Employee : EnumAttendeeType.User,
EmployeeID = employeeID,
UserID = employeeID.HasValue ? (int?)null : userID,
Role = EnumAttendeeRole.Organizer,
ResponseStatus = EnumResponseStatus.Accepted,
TaskStatus = selfAssigned ? EnumCalendarTaskStatus.NotStarted : (EnumCalendarTaskStatus?)null,
IsRead = true,
ReadDate = now,
Status = EnumAttendeeStatus.Active,
CreatedBy = user.UserID,
CreatedDate = now
};
}
/// A fresh organizer row for an existing item, for the person stored as its organizer.
private static CalendarItemAttendee BuildOrganizerOf(List current, CurrentUser user, CalendarItem item, DateTime now)
{
CalendarItemAttendee stored = current.FirstOrDefault(a => a.Role == EnumAttendeeRole.Organizer);
if (stored == null)
throw new ArgumentException("The organizer of this calendar item was not found.");
return BuildOrganizer(stored.EmployeeID, stored.UserID, user, item, now);
}
///
/// Turns what the user picked into attendee rows: departments are expanded into their live employees,
/// employees and users are checked to exist, duplicates and the organizer are dropped. A schedule job keeps its
/// departments as Department rows instead: they are expanded each time the job runs, so new joiners are included.
///
private List ResolveAttendees(TransactionContext tc, CurrentUser user, CalendarItem item,
CalendarItemAttendee organizer, DateTime now)
{
bool isTask = item.ItemType == EnumCalendarItemType.Task;
// schedule jobs and schedule emails keep departments and plain targets alike
bool isJob = IsScheduled(item.ItemType);
List picked = item.Attendees.Where(a => a != null && a.Role != EnumAttendeeRole.Organizer).ToList();
if (picked.Any(a => !Enum.IsDefined(typeof(EnumAttendeeType), a.AttendeeType)
|| (a.AttendeeType == EnumAttendeeType.Employee && !a.EmployeeID.HasValue)
|| (a.AttendeeType == EnumAttendeeType.User && !a.UserID.HasValue)
|| (a.AttendeeType == EnumAttendeeType.Department && !a.DepartmentID.HasValue)))
throw new ArgumentException("An attendee is not valid.");
// Users first: an account that belongs to an employee is stored as that employee, so the person sees the
// item in both their admin and self-service logins and cannot be on the list twice.
Dictionary users = GetPickedUsers(tc, user, picked);
picked = picked.Select(a =>
{
if (a.AttendeeType != EnumAttendeeType.User || !users[a.UserID.Value].EmployeeID.HasValue)
return a;
return new CalendarItemAttendee
{
AttendeeType = EnumAttendeeType.Employee,
EmployeeID = users[a.UserID.Value].EmployeeID,
Role = a.Role,
TitleOverride = a.TitleOverride,
SubjectOverride = a.SubjectOverride,
FromOverride = a.FromOverride,
ToOverride = a.ToOverride
};
}).ToList();
List departmentIDs = picked.Where(a => a.AttendeeType == EnumAttendeeType.Department && a.DepartmentID.HasValue)
.Select(a => a.DepartmentID.Value).Distinct().ToList();
List employeeIDs = picked.Where(a => a.AttendeeType == EnumAttendeeType.Employee && a.EmployeeID.HasValue)
.Select(a => a.EmployeeID.Value).Distinct().ToList();
Dictionary employees = GetEmployees(tc, employeeIDs).ToDictionary(e => e.EmployeeID);
foreach (int employeeID in employeeIDs)
{
if (!employees.TryGetValue(employeeID, out EmployeeInfo employee))
throw new ArgumentException("A selected employee was not found.");
if (employee.Status != (int)EnumEmployeeStatus.Live)
throw new ArgumentException(employee.Name + " is not an active employee.");
}
if (departmentIDs.Count > 0 && !isJob)
{
DataReader dr = new DataReader(CalendarItemDA.GetLiveEmployeesOfDepartments(tc, string.Join(",", departmentIDs), user.PayrollTypeID.Value));
while (dr.Read())
{
EmployeeInfo employee = ReadEmployee(dr);
if (!employees.ContainsKey(employee.EmployeeID))
employees.Add(employee.EmployeeID, employee);
}
dr.Close();
}
string organizerKey = AttendeeKey(organizer);
Dictionary result = new Dictionary();
// Individually picked people first, so their per-person title / dates win over a department pick.
foreach (CalendarItemAttendee choice in picked.Where(a => a.AttendeeType != EnumAttendeeType.Department))
{
CalendarItemAttendee row = NewAttendeeRow(user, isTask, choice, now);
if (row.AttendeeType == EnumAttendeeType.Employee)
row.Email = employees[row.EmployeeID.Value].Email;
else if (row.AttendeeType == EnumAttendeeType.User)
row.Email = users[row.UserID.Value].Email;
string key = AttendeeKey(row);
if (key != organizerKey && !result.ContainsKey(key))
result.Add(key, row);
}
foreach (EmployeeInfo employee in employees.Values.Where(e => !employeeIDs.Contains(e.EmployeeID)))
{
CalendarItemAttendee row = NewAttendeeRow(user, isTask,
new CalendarItemAttendee { AttendeeType = EnumAttendeeType.Employee, EmployeeID = employee.EmployeeID }, now);
row.Email = employee.Email;
string key = AttendeeKey(row);
if (key != organizerKey && !result.ContainsKey(key))
result.Add(key, row);
}
if (isJob)
AddJobTargets(tc, user, result, departmentIDs, now);
if (result.Count > MaxAttendees)
throw new ArgumentException("A calendar item can have at most " + MaxAttendees + " attendees.");
return result.Values.ToList();
}
private int MaxAttendees
{
get { return _settings.MaxAttendees > 0 ? _settings.MaxAttendees : 500; }
}
///
/// Turns a schedule job's picks into target rows: people become plain targets (no own title or dates, no e-mail:
/// the job itself never goes to Outlook) and each department, once checked to exist, becomes a Department row.
///
private static void AddJobTargets(TransactionContext tc, CurrentUser user, Dictionary result,
List departmentIDs, DateTime now)
{
foreach (CalendarItemAttendee row in result.Values)
{
row.Role = EnumAttendeeRole.Assignee;
row.TaskStatus = null;
row.TitleOverride = null;
row.SubjectOverride = null;
row.FromOverride = null;
row.ToOverride = null;
row.Email = null;
}
if (departmentIDs.Count == 0)
return;
HashSet found = new HashSet();
DataReader dr = new DataReader(CalendarItemDA.GetDepartments(tc, string.Join(",", departmentIDs)));
while (dr.Read())
found.Add(dr.GetInt32("DEPARTMENTID", 0));
dr.Close();
foreach (int departmentID in departmentIDs)
{
if (!found.Contains(departmentID))
throw new ArgumentException("A selected department was not found.");
CalendarItemAttendee row = new CalendarItemAttendee
{
AttendeeType = EnumAttendeeType.Department,
DepartmentID = departmentID,
Role = EnumAttendeeRole.Assignee,
ResponseStatus = EnumResponseStatus.Pending,
IsRead = false,
Status = EnumAttendeeStatus.Active,
CreatedBy = user.UserID,
CreatedDate = now
};
result[AttendeeKey(row)] = row;
}
}
private static CalendarItemAttendee NewAttendeeRow(CurrentUser user, bool isTask, CalendarItemAttendee choice, DateTime now)
{
string titleOverride = string.IsNullOrWhiteSpace(choice.TitleOverride) ? null : choice.TitleOverride.Trim();
string subjectOverride = string.IsNullOrWhiteSpace(choice.SubjectOverride) ? null : choice.SubjectOverride.Trim();
if ((titleOverride != null && titleOverride.Length > MaxTitleLength)
|| (subjectOverride != null && subjectOverride.Length > MaxTitleLength))
throw new ArgumentException("A personal title or subject can be at most " + MaxTitleLength + " characters.");
if (choice.FromOverride.HasValue && choice.ToOverride.HasValue && choice.ToOverride < choice.FromOverride)
throw new ArgumentException("A personal end date must not be before its start date.");
EnumAttendeeRole role = isTask
? EnumAttendeeRole.Assignee
: (choice.Role == EnumAttendeeRole.Optional ? EnumAttendeeRole.Optional : EnumAttendeeRole.Required);
return new CalendarItemAttendee
{
AttendeeType = choice.AttendeeType,
EmployeeID = choice.AttendeeType == EnumAttendeeType.Employee ? choice.EmployeeID : null,
UserID = choice.AttendeeType == EnumAttendeeType.User ? choice.UserID : null,
Role = role,
TitleOverride = titleOverride,
SubjectOverride = subjectOverride,
FromOverride = choice.FromOverride,
ToOverride = choice.ToOverride,
ResponseStatus = EnumResponseStatus.Pending,
TaskStatus = isTask ? EnumCalendarTaskStatus.NotStarted : (EnumCalendarTaskStatus?)null,
IsRead = false,
Status = EnumAttendeeStatus.Active,
CreatedBy = user.UserID,
CreatedDate = now
};
}
///
/// HR (any non-self-service login) may assign tasks to anyone. A self-service user may assign tasks
/// only to employees whose line manager they are (and to themselves). The assignee list never contains the organizer.
///
private static void CheckTaskAssignPermission(TransactionContext tc, CurrentUser user, List assignees)
{
if (IsHr(user) || assignees.Count == 0)
return;
int myEmployeeID = user.EmployeeID.Value;
if (assignees.Any(a => a.AttendeeType != EnumAttendeeType.Employee))
throw new UnauthorizedAccessException("You can assign tasks only to your own team.");
List employeeIDs = assignees.Select(a => a.EmployeeID.Value).ToList();
List employees = GetEmployees(tc, employeeIDs);
EmployeeInfo outsider = employees.FirstOrDefault(e => e.LineManagerID != myEmployeeID);
if (outsider != null)
throw new UnauthorizedAccessException("You can assign tasks only to your own team. " + outsider.Name + " is not in your team.");
}
///
/// HR (any non-self-service login) may send a schedule email to anyone. A self-service user may send it only to
/// employees whose line manager they are: no user accounts and no whole departments.
///
private static void CheckEmailRecipientPermission(TransactionContext tc, CurrentUser user, List recipients)
{
if (IsHr(user) || recipients.Count == 0)
return;
int myEmployeeID = user.EmployeeID.Value;
if (recipients.Any(a => a.AttendeeType != EnumAttendeeType.Employee))
throw new UnauthorizedAccessException("You can send schedule emails only to your own team.");
List employees = GetEmployees(tc, recipients.Select(a => a.EmployeeID.Value).ToList());
EmployeeInfo outsider = employees.FirstOrDefault(e => e.LineManagerID != myEmployeeID);
if (outsider != null)
throw new UnauthorizedAccessException("You can send schedule emails only to your own team. " + outsider.Name
+ " is not in your team.");
}
private static string AttendeeKey(CalendarItemAttendee attendee)
{
switch (attendee.AttendeeType)
{
case EnumAttendeeType.Employee: return "E" + attendee.EmployeeID;
case EnumAttendeeType.User: return "U" + attendee.UserID;
default: return "D" + attendee.DepartmentID;
}
}
///
/// The next moment a reminder is due (for a schedule job: its next run): the earliest "occurrence start minus offset" that is still in the future,
/// across all occurrences of a repeating item, or across the item's start and the attendees' own start dates
/// of a one-off item. Null when there is no reminder left.
///
private static DateTime? ComputeNextTrigger(CalendarItem item, IEnumerable attendees, DateTime now)
{
// a schedule job's (or schedule email's) trigger is its next run; a job's reminders belong to the tasks it creates
if (IsScheduled(item.ItemType))
return CalendarRecurrence.NextStart(item, now);
IEnumerable ownStarts = (attendees ?? Enumerable.Empty())
.Where(a => a.Status == EnumAttendeeStatus.Active && a.FromOverride.HasValue)
.Select(a => a.FromOverride.Value);
return CalendarRecurrence.NextTrigger(item, item.GetReminderOffsetMinutes(), now, ownStarts);
}
#endregion
}
}