Beispiel #1
0
        public IActionResult GetMembersForGroup(int groupId, bool includeAdmins = true, bool includeNormal = true)
        {
            var groupsJson = new List <GroupMemberJson>();
            var groups     = _departmentGroupsService.GetAllMembersForGroup(groupId);

            foreach (var group in groups)
            {
                var isAdmin = group.IsAdmin.GetValueOrDefault();

                if ((isAdmin && includeAdmins) || (!isAdmin && includeNormal))
                {
                    var groupJson = new GroupMemberJson();
                    groupJson.GroupMemberId     = group.DepartmentGroupMemberId;
                    groupJson.DepartmentGroupId = group.DepartmentGroupId;
                    groupJson.UserId            = group.UserId;
                    groupJson.IsAdmin           = isAdmin;
                    groupJson.Name = UserHelper.GetFullNameForUser(group.UserId);

                    groupsJson.Add(groupJson);
                }
            }

            return(Json(groupsJson));
        }
        public HttpResponseMessage SendMessage([FromBody] NewMessageInput newMessageInput)
        {
            if (newMessageInput.Rcps == null || newMessageInput.Rcps.Count <= 0)
            {
                throw HttpStatusCode.BadRequest.AsException();
            }

            try
            {
                var message = new Message();
                message.Subject       = newMessageInput.Ttl;
                message.Body          = System.Net.WebUtility.HtmlDecode(newMessageInput.Bdy);
                message.IsBroadcast   = true;
                message.SendingUserId = UserId;
                message.Type          = newMessageInput.Typ;
                message.SentOn        = DateTime.UtcNow;

                var usersToSendTo = new List <string>();

                if (newMessageInput.Rcps.Any(x => x.Nme == "Everyone"))
                {
                    var departmentUsers = _departmentsService.GetAllMembersForDepartment(DepartmentId);

                    foreach (var departmentMember in departmentUsers)
                    {
                        message.AddRecipient(departmentMember.UserId);
                    }
                }
                else
                {
                    // Add all the explict people
                    foreach (var person in newMessageInput.Rcps.Where(x => x.Typ == 1))
                    {
                        if (usersToSendTo.All(x => x != person.Id) && person.Id != UserId)
                        {
                            usersToSendTo.Add(person.Id);
                            message.AddRecipient(person.Id);
                        }
                    }

                    // Add all memebers of the group
                    foreach (var group in newMessageInput.Rcps.Where(x => x.Typ == 2))
                    {
                        if (!String.IsNullOrWhiteSpace(group.Id))
                        {
                            int groupId = 0;
                            if (int.TryParse(group.Id.Trim(), out groupId))
                            {
                                var members = _departmentGroupsService.GetAllMembersForGroup(groupId);

                                foreach (var member in members)
                                {
                                    if (usersToSendTo.All(x => x != member.UserId) && member.UserId != UserId)
                                    {
                                        usersToSendTo.Add(member.UserId);
                                        message.AddRecipient(member.UserId);
                                    }
                                }
                            }
                        }
                    }

                    // Add all the users of a specific role
                    foreach (var role in newMessageInput.Rcps.Where(x => x.Typ == 3))
                    {
                        var roleMembers = _personnelRolesService.GetAllMembersOfRole(int.Parse(role.Id));

                        foreach (var member in roleMembers)
                        {
                            if (usersToSendTo.All(x => x != member.UserId) && member.UserId != UserId)
                            {
                                usersToSendTo.Add(member.UserId);
                                message.AddRecipient(member.UserId);
                            }
                        }
                    }
                }

                var savedMessage = _messageService.SaveMessage(message);
                _messageService.SendMessage(savedMessage, "", DepartmentId, false);
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
                throw HttpStatusCode.InternalServerError.AsException();
            }

            return(Request.CreateResponse(HttpStatusCode.Created));
        }
Beispiel #3
0
        public IActionResult Compose(ComposeMessageModel model, IFormCollection collection)
        {
            var roles  = new List <string>();
            var groups = new List <string>();
            var users  = new List <string>();
            var shifts = new List <string>();

            if (collection.ContainsKey("roles"))
            {
                roles.AddRange(collection["roles"].ToString().Split(char.Parse(",")));
            }

            if (collection.ContainsKey("groups"))
            {
                groups.AddRange(collection["groups"].ToString().Split(char.Parse(",")));
            }

            if (collection.ContainsKey("users"))
            {
                users.AddRange(collection["users"].ToString().Split(char.Parse(",")));
            }

            if (collection.ContainsKey("exludedShifts"))
            {
                shifts.AddRange(collection["exludedShifts"].ToString().Split(char.Parse(",")));
            }

            if (!model.SendToAll && (roles.Count + groups.Count + users.Count) == 0)
            {
                ModelState.AddModelError("", "You must specify at least one Recipient.");
            }

            if (model.SendToMatchOnly && (roles.Count + groups.Count) == 0)
            {
                ModelState.AddModelError("", "You must specify at least one Group or Role to send to.");
            }

            if (ModelState.IsValid)
            {
                var excludedUsers = new List <string>();

                if (shifts.Any())
                {
                    foreach (var shiftId in shifts)
                    {
                        var shift = _shiftsService.GetShiftById(int.Parse(shiftId));
                        excludedUsers.AddRange(shift.Personnel.Select(x => x.UserId));
                    }
                }

                model.Message.Type = (int)model.MessageType;
                if (model.SendToAll)
                {
                    var allUsers = _departmentsService.GetAllUsersForDepartment(DepartmentId);
                    foreach (var user in allUsers)
                    {
                        if (user.UserId != UserId && (!excludedUsers.Any() || !excludedUsers.Contains(user.UserId)))
                        {
                            model.Message.AddRecipient(user.UserId);
                        }
                    }
                }
                else if (model.SendToMatchOnly)
                {
                    var usersInRoles = new Dictionary <int, List <string> >();

                    foreach (var role in roles)
                    {
                        var roleMembers = _personnelRolesService.GetAllMembersOfRole(int.Parse(role));
                        usersInRoles.Add(int.Parse(role), roleMembers.Select(x => x.UserId).ToList());
                    }

                    foreach (var group in groups)
                    {
                        var members = _departmentGroupsService.GetAllMembersForGroup(int.Parse(group));

                        foreach (var member in members)
                        {
                            bool isInRoles = false;
                            if (model.Message.GetRecipients().All(x => x != member.UserId) && member.UserId != UserId &&
                                (!excludedUsers.Any() || !excludedUsers.Contains(member.UserId)))
                            {
                                foreach (var key in usersInRoles)
                                {
                                    if (key.Value.Any(x => x == member.UserId))
                                    {
                                        isInRoles = true;
                                        break;
                                    }
                                }

                                if (isInRoles)
                                {
                                    model.Message.AddRecipient(member.UserId);
                                }
                            }
                        }
                    }
                }
                else
                {
                    foreach (var user in users)
                    {
                        model.Message.AddRecipient(user);
                    }

                    // Add all members of the group
                    foreach (var group in groups)
                    {
                        var members = _departmentGroupsService.GetAllMembersForGroup(int.Parse(group));

                        foreach (var member in members)
                        {
                            if (model.Message.GetRecipients().All(x => x != member.UserId) && member.UserId != UserId && (!excludedUsers.Any() || !excludedUsers.Contains(member.UserId)))
                            {
                                model.Message.AddRecipient(member.UserId);
                            }
                        }
                    }

                    // Add all the users of a specific role
                    foreach (var role in roles)
                    {
                        var roleMembers = _personnelRolesService.GetAllMembersOfRole(int.Parse(role));

                        foreach (var member in roleMembers)
                        {
                            if (model.Message.GetRecipients().All(x => x != member.UserId) && member.UserId != UserId && (!excludedUsers.Any() || !excludedUsers.Contains(member.UserId)))
                            {
                                model.Message.AddRecipient(member.UserId);
                            }
                        }
                    }
                }

                model.Message.SentOn        = DateTime.UtcNow;
                model.Message.SendingUserId = UserId;
                model.Message.Body          = System.Net.WebUtility.HtmlDecode(model.Message.Body);
                model.Message.IsBroadcast   = true;

                var savedMessage = _messageService.SaveMessage(model.Message);
                _messageService.SendMessage(savedMessage, "", DepartmentId, false);

                return(RedirectToAction("Inbox"));
            }

            model.Department = _departmentsService.GetDepartmentById(DepartmentId);
            model.User       = _usersService.GetUserById(UserId);
            model.Types      = model.MessageType.ToSelectList();

            var savedShifts = _shiftsService.GetAllShiftsByDepartment(DepartmentId);

            model.Shifts       = new SelectList(savedShifts, "ShiftId", "Name");
            model.Message.Body = System.Net.WebUtility.HtmlDecode(model.Message.Body);

            return(View(FillComposeMessageModel(model)));
        }
Beispiel #4
0
        public IActionResult New(NewTrainingModel model, IFormCollection form, ICollection <IFormFile> attachments)
        {
            model.Training.CreatedByUserId = UserId;

            if (attachments != null)
            {
                model.Training.Attachments = new Collection <TrainingAttachment>();
                foreach (var file in attachments)
                {
                    if (file != null && file.Length > 0)
                    {
                        var extenion = file.FileName.Substring(file.FileName.IndexOf(char.Parse(".")) + 1,
                                                               file.FileName.Length - file.FileName.IndexOf(char.Parse(".")) - 1);

                        if (!String.IsNullOrWhiteSpace(extenion))
                        {
                            extenion = extenion.ToLower();
                        }

                        if (extenion != "jpg" && extenion != "jpeg" && extenion != "png" && extenion != "gif" && extenion != "gif" &&
                            extenion != "pdf" && extenion != "doc" &&
                            extenion != "docx" && extenion != "ppt" && extenion != "pptx" && extenion != "pps" && extenion != "ppsx" &&
                            extenion != "odt" &&
                            extenion != "xls" && extenion != "xlsx" && extenion != "txt" && extenion != "mpg" && extenion != "avi" &&
                            extenion != "mpeg")
                        {
                            ModelState.AddModelError("fileToUpload", string.Format("File type ({0}) is not importable.", extenion));
                        }

                        if (file.Length > 30000000)
                        {
                            ModelState.AddModelError("fileToUpload", "Attachment is too large, must be smaller then 30MB.");
                        }

                        var attachment = new TrainingAttachment();
                        attachment.FileType = file.ContentType;
                        attachment.FileName = file.FileName;

                        var uploadedFile = new byte[file.OpenReadStream().Length];
                        file.OpenReadStream().Read(uploadedFile, 0, uploadedFile.Length);

                        attachment.Data = uploadedFile;
                        model.Training.Attachments.Add(attachment);
                    }
                }
            }

            var roles  = new List <string>();
            var groups = new List <string>();
            var users  = new List <string>();

            if (form.ContainsKey("rolesToAdd"))
            {
                roles.AddRange(form["rolesToAdd"].ToString().Split(char.Parse(",")));
            }

            if (form.ContainsKey("groupsToAdd"))
            {
                groups.AddRange(form["groupsToAdd"].ToString().Split(char.Parse(",")));
            }

            if (form.ContainsKey("usersToAdd"))
            {
                users.AddRange(form["usersToAdd"].ToString().Split(char.Parse(",")));
            }

            model.Training.Users = new List <TrainingUser>();

            if (model.SendToAll)
            {
                var allUsers = _departmentsService.GetAllUsersForDepartment(DepartmentId);
                foreach (var user in allUsers)
                {
                    var trainingUser = new TrainingUser();
                    trainingUser.UserId = user.UserId;

                    model.Training.Users.Add(trainingUser);
                }
            }
            else
            {
                foreach (var user in users)
                {
                    var trainingUser = new TrainingUser();
                    trainingUser.UserId = user;

                    model.Training.Users.Add(trainingUser);
                }

                foreach (var group in groups)
                {
                    var members = _departmentGroupsService.GetAllMembersForGroup(int.Parse(group));

                    foreach (var member in members)
                    {
                        var trainingUser = new TrainingUser();
                        trainingUser.UserId = member.UserId;

                        if (model.Training.Users.All(x => x.UserId != member.UserId))
                        {
                            model.Training.Users.Add(trainingUser);
                        }
                    }
                }

                foreach (var role in roles)
                {
                    var roleMembers = _personnelRolesService.GetAllMembersOfRole(int.Parse(role));

                    foreach (var member in roleMembers)
                    {
                        var trainingUser = new TrainingUser();
                        trainingUser.UserId = member.UserId;

                        if (model.Training.Users.All(x => x.UserId != member.UserId))
                        {
                            model.Training.Users.Add(trainingUser);
                        }
                    }
                }
            }

            if (!model.Training.Users.Any())
            {
                ModelState.AddModelError("", "You have not selected any personnel, roles or groups to assign this training to.");
            }

            if (ModelState.IsValid)
            {
                List <int> questions = (from object key in form.Keys where key.ToString().StartsWith("question_") select int.Parse(key.ToString().Replace("question_", ""))).ToList();

                if (questions.Count > 0)
                {
                    model.Training.Questions = new Collection <TrainingQuestion>();
                }

                model.Training.DepartmentId    = DepartmentId;
                model.Training.CreatedOn       = DateTime.UtcNow;
                model.Training.CreatedByUserId = UserId;
                model.Training.GroupsToAdd     = form["groupsToAdd"];
                model.Training.RolesToAdd      = form["rolesToAdd"];
                model.Training.UsersToAdd      = form["usersToAdd"];
                model.Training.Description     = System.Net.WebUtility.HtmlDecode(model.Training.Description);
                model.Training.TrainingText    = System.Net.WebUtility.HtmlDecode(model.Training.TrainingText);


                foreach (var i in questions)
                {
                    if (form.ContainsKey("question_" + i))
                    {
                        var questionText = form["question_" + i];
                        var question     = new TrainingQuestion();
                        question.Question = questionText;

                        List <int> answers = (from object key in form.Keys where key.ToString().StartsWith("answerForQuestion_" + i + "_") select int.Parse(key.ToString().Replace("answerForQuestion_" + i + "_", ""))).ToList();

                        if (answers.Count > 0)
                        {
                            question.Answers = new Collection <TrainingQuestionAnswer>();
                        }

                        foreach (var answer in answers)
                        {
                            var trainingQuestionAnswer = new TrainingQuestionAnswer();
                            var answerForQuestion      = form["answerForQuestion_" + i + "_" + answer];

                            var possibleAnswer = form["answer_" + i];
                            trainingQuestionAnswer.Answer = answerForQuestion;

                            if (!string.IsNullOrWhiteSpace(possibleAnswer))
                            {
                                if ("answerForQuestion_" + i + "_" + answer == possibleAnswer)
                                {
                                    trainingQuestionAnswer.Correct = true;
                                }
                            }

                            question.Answers.Add(trainingQuestionAnswer);
                        }

                        model.Training.Questions.Add(question);
                    }
                }

                _trainingService.Save(model.Training);

                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
        public List <ProcessedNotification> ProcessNotifications(List <ProcessedNotification> notifications, List <DepartmentNotification> settings)
        {
            if (notifications == null || notifications.Count < 0)
            {
                return(null);
            }

            //if (settings == null || settings.Count < 0)
            //	return null;

            var processNotifications = new List <ProcessedNotification>();

            foreach (var notification in notifications)
            {
                if (settings != null && settings.Any())
                {
                    var typeSettings = settings.Where(x => x.EventType == (int)notification.Type);

                    if (typeSettings != null && typeSettings.Any())
                    {
                        processNotifications.Add(notification);

                        foreach (var setting in typeSettings)
                        {
                            if (ValidateNotificationForProcessing(notification, setting))
                            {
                                if (setting.Everyone)                                 // Add Everyone
                                {
                                    notification.Users =
                                        _departmentsService.GetAllUsersForDepartment(notification.DepartmentId, true).Select(x => x.UserId).ToList();
                                }
                                else if (setting.DepartmentAdmins)                                 // Add Only Department Admins
                                {
                                    notification.Users =
                                        _departmentsService.GetAllAdminsForDepartment(notification.DepartmentId).Select(x => x.UserId).ToList();
                                }
                                else if (setting.LockToGroup && EventOptions.GroupEvents.Contains(notification.Type))
                                // We are locked to the source group
                                {
                                    var group = GetGroupForEvent(notification);
                                    if (group != null)
                                    {
                                        if (setting.SelectedGroupsAdminsOnly)                                         // Only add source group admins
                                        {
                                            var usersInGroup = _departmentGroupsService.GetAllAdminsForGroup(group.DepartmentGroupId);

                                            if (usersInGroup != null)
                                            {
                                                foreach (var user in usersInGroup)
                                                {
                                                    if (!notification.Users.Contains(user.UserId))
                                                    {
                                                        notification.Users.Add(user.UserId);
                                                    }
                                                }
                                            }
                                        }
                                        else                                         // Add source group users in selected roles
                                        {
                                            var usersInGroup = _departmentGroupsService.GetAllMembersForGroup(group.DepartmentGroupId)
                                                               .Select(x => x.UserId);
                                            var roles = setting.RolesToNotify.Split(char.Parse(","));

                                            foreach (var roleId in roles)
                                            {
                                                var usersInRole = _personnelRolesService.GetAllMembersOfRole(int.Parse(roleId));

                                                if (usersInRole != null)
                                                {
                                                    foreach (var user in usersInRole)
                                                    {
                                                        if (usersInGroup.Contains(user.UserId) && !notification.Users.Contains(user.UserId))
                                                        {
                                                            notification.Users.Add(user.UserId);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else                                 // Run through users, Roles and groups
                                {
                                    if (!String.IsNullOrWhiteSpace(setting.RolesToNotify))
                                    {
                                        var roles = setting.RolesToNotify.Split(char.Parse(","));
                                        foreach (var roleId in roles)                                         // Add all users in Roles
                                        {
                                            var usersInRole = _personnelRolesService.GetAllMembersOfRole(int.Parse(roleId));
                                            foreach (var user in usersInRole)
                                            {
                                                if (!notification.Users.Contains(user.UserId))
                                                {
                                                    notification.Users.Add(user.UserId);
                                                }
                                            }
                                        }
                                    }

                                    if (!String.IsNullOrWhiteSpace(setting.UsersToNotify))
                                    {
                                        var users = setting.UsersToNotify.Split(char.Parse(","));
                                        if (users != null)
                                        {
                                            foreach (var userId in users)                                             // Add all Users
                                            {
                                                if (!notification.Users.Contains(userId))
                                                {
                                                    notification.Users.Add(userId);
                                                }
                                            }
                                        }
                                    }

                                    if (!String.IsNullOrWhiteSpace(setting.GroupsToNotify))
                                    {
                                        var groups = setting.GroupsToNotify.Split(char.Parse(","));
                                        if (groups != null)
                                        {
                                            foreach (var groupId in groups)                                             // Add all users in Groups
                                            {
                                                if (setting.SelectedGroupsAdminsOnly)                                   // Only add group admins
                                                {
                                                    var usersInGroup = _departmentGroupsService.GetAllAdminsForGroup(int.Parse(groupId));

                                                    if (usersInGroup != null)
                                                    {
                                                        foreach (var user in usersInGroup)
                                                        {
                                                            if (!notification.Users.Contains(user.UserId))
                                                            {
                                                                notification.Users.Add(user.UserId);
                                                            }
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    var usersInGroup = _departmentGroupsService.GetAllMembersForGroup(int.Parse(groupId));

                                                    if (usersInGroup != null)
                                                    {
                                                        foreach (var user in usersInGroup)
                                                        {
                                                            if (!notification.Users.Contains(user.UserId))
                                                            {
                                                                notification.Users.Add(user.UserId);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (notification.Type == EventTypes.CalendarEventAdded)
                {
                    var calEvent = _calendarService.GetCalendarItemById(notification.ItemId);

                    if (calEvent != null)
                    {
                        if (calEvent.ItemType == 0 && !String.IsNullOrWhiteSpace(calEvent.Entities))                         // NONE: Notify based on entities
                        {
                            var items = calEvent.Entities.Split(char.Parse(","));

                            if (items.Any(x => x.StartsWith("D:")))
                            {
                                notification.Users =
                                    _departmentsService.GetAllUsersForDepartment(notification.DepartmentId, true).Select(x => x.UserId).ToList();
                            }
                            else
                            {
                                foreach (var val in items)
                                {
                                    int groupId = 0;
                                    if (int.TryParse(val.Replace("G:", ""), out groupId))
                                    {
                                        var usersInGroup = _departmentGroupsService.GetAllMembersForGroup(groupId);

                                        if (usersInGroup != null)
                                        {
                                            foreach (var user in usersInGroup)
                                            {
                                                if (!notification.Users.Contains(user.UserId))
                                                {
                                                    notification.Users.Add(user.UserId);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else if (calEvent.ItemType == 1)                         // ASSIGNED: Notify based on Required and Optional attendees
                        {
                        }
                        else if (calEvent.ItemType == 1)                         // RSVP: Notify entire department
                        {
                            notification.Users =
                                _departmentsService.GetAllUsersForDepartment(notification.DepartmentId, true).Select(x => x.UserId).ToList();
                        }
                    }
                }
                else if (notification.Type == EventTypes.CalendarEventUpdated)
                {
                    var calEvent = _calendarService.GetCalendarItemById(notification.ItemId);

                    if (calEvent != null)
                    {
                        if (calEvent.ItemType == 0 && !String.IsNullOrWhiteSpace(calEvent.Entities))                         // NONE: Notify based on entities
                        {
                            var items = calEvent.Entities.Split(char.Parse(","));

                            if (items.Any(x => x.StartsWith("D:")))
                            {
                                notification.Users =
                                    _departmentsService.GetAllUsersForDepartment(notification.DepartmentId, true).Select(x => x.UserId).ToList();
                            }
                            else
                            {
                                foreach (var val in items)
                                {
                                    int groupId = 0;
                                    if (int.TryParse(val.Replace("G:", ""), out groupId))
                                    {
                                        var usersInGroup = _departmentGroupsService.GetAllMembersForGroup(groupId);

                                        if (usersInGroup != null)
                                        {
                                            foreach (var user in usersInGroup)
                                            {
                                                if (!notification.Users.Contains(user.UserId))
                                                {
                                                    notification.Users.Add(user.UserId);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else if (calEvent.ItemType == 1)                         // ASSIGNED: Notify based on Required and Optional attendees
                        {
                        }
                        else if (calEvent.ItemType == 1 && calEvent.Attendees != null && calEvent.Attendees.Any())                         // RSVP: Notify people who've signed up
                        {
                            foreach (var attendee in calEvent.Attendees)
                            {
                                if (!notification.Users.Contains(attendee.UserId))
                                {
                                    notification.Users.Add(attendee.UserId);
                                }
                            }
                        }
                    }
                }
            }

            return(processNotifications);
        }
Beispiel #6
0
        public static void ProcessCallQueueItem(CallQueueItem cqi)
        {
            try
            {
                if (cqi != null && cqi.Call != null && cqi.Call.HasAnyDispatches())
                {
                    if (_communicationService == null)
                    {
                        _communicationService = Bootstrapper.GetKernel().Resolve <ICommunicationService>();
                    }

                    if (_callsService == null)
                    {
                        _callsService = Bootstrapper.GetKernel().Resolve <ICallsService>();
                    }

                    List <int> groupIds = new List <int>();

                    /* Trying to see if I can eek out a little perf here now that profiles are in Redis. Previously the
                     * the parallel operation would cause EF errors. This shouldn't be the case now because profiles are
                     * cached and GetProfileForUser operations will hit that first.
                     */
                    if (cqi.Profiles == null || !cqi.Profiles.Any())
                    {
                        if (_userProfilesService == null)
                        {
                            _userProfilesService = Bootstrapper.GetKernel().Resolve <IUserProfileService>();
                        }

                        cqi.Profiles = _userProfilesService.GetAllProfilesForDepartment(cqi.Call.DepartmentId).Select(x => x.Value).ToList();
                    }

                    if (cqi.CallDispatchAttachmentId > 0)
                    {
                        //var callsService = Bootstrapper.GetKernel().Resolve<ICallsService>();
                        cqi.Call.ShortenedAudioUrl = _callsService.GetShortenedAudioUrl(cqi.Call.CallId, cqi.CallDispatchAttachmentId);
                    }

                    cqi.Call.ShortenedCallUrl = _callsService.GetShortenedCallLinkUrl(cqi.Call.CallId);

                    try
                    {
                        cqi.Call.CallPriority = _callsService.GetCallPrioritesById(cqi.Call.DepartmentId, cqi.Call.Priority, false);
                    }
                    catch { /* Doesn't matter */ }

                    var dispatchedUsers = new HashSet <string>();

                    // Dispatch Personnel
                    if (cqi.Call.Dispatches != null && cqi.Call.Dispatches.Any())
                    {
                        Parallel.ForEach(cqi.Call.Dispatches, d =>
                        {
                            dispatchedUsers.Add(d.UserId);

                            try
                            {
                                var profile = cqi.Profiles.FirstOrDefault(x => x.UserId == d.UserId);

                                if (profile != null)
                                {
                                    _communicationService.SendCall(cqi.Call, d, cqi.DepartmentTextNumber, cqi.Call.DepartmentId, profile, cqi.Address);
                                }
                            }
                            catch (SocketException sex)
                            {
                            }
                        });
                    }

                    if (_departmentGroupsService == null)
                    {
                        _departmentGroupsService = Bootstrapper.GetKernel().Resolve <IDepartmentGroupsService>();
                    }

                    // Dispatch Groups
                    if (cqi.Call.GroupDispatches != null && cqi.Call.GroupDispatches.Any())
                    {
                        foreach (var d in cqi.Call.GroupDispatches)
                        {
                            if (!groupIds.Contains(d.DepartmentGroupId))
                            {
                                groupIds.Add(d.DepartmentGroupId);
                            }

                            var members = _departmentGroupsService.GetAllMembersForGroup(d.DepartmentGroupId);

                            foreach (var member in members)
                            {
                                if (!dispatchedUsers.Contains(member.UserId))
                                {
                                    dispatchedUsers.Add(member.UserId);
                                    try
                                    {
                                        var profile = cqi.Profiles.FirstOrDefault(x => x.UserId == member.UserId);
                                        _communicationService.SendCall(cqi.Call, new CallDispatch()
                                        {
                                            UserId = member.UserId
                                        }, cqi.DepartmentTextNumber, cqi.Call.DepartmentId, profile, cqi.Address);
                                    }
                                    catch (SocketException sex)
                                    {
                                    }
                                    catch (Exception ex)
                                    {
                                        Logging.LogException(ex);
                                    }
                                }
                            }
                        }
                    }

                    // Dispatch Units
                    if (cqi.Call.UnitDispatches != null && cqi.Call.UnitDispatches.Any())
                    {
                        if (_unitsService == null)
                        {
                            _unitsService = Bootstrapper.GetKernel().Resolve <IUnitsService>();
                        }

                        foreach (var d in cqi.Call.UnitDispatches)
                        {
                            var unit = _unitsService.GetUnitById(d.UnitId);

                            if (unit != null && unit.StationGroupId.HasValue)
                            {
                                if (!groupIds.Contains(unit.StationGroupId.Value))
                                {
                                    groupIds.Add(unit.StationGroupId.Value);
                                }
                            }

                            _communicationService.SendUnitCall(cqi.Call, d, cqi.DepartmentTextNumber, cqi.Address);

                            var unitAssignedMembers = _unitsService.GetCurrentRolesForUnit(d.UnitId);

                            if (unitAssignedMembers != null && unitAssignedMembers.Count() > 0)
                            {
                                foreach (var member in unitAssignedMembers)
                                {
                                    if (!dispatchedUsers.Contains(member.UserId))
                                    {
                                        dispatchedUsers.Add(member.UserId);
                                        try
                                        {
                                            var profile = cqi.Profiles.FirstOrDefault(x => x.UserId == member.UserId);
                                            _communicationService.SendCall(cqi.Call, new CallDispatch()
                                            {
                                                UserId = member.UserId
                                            }, cqi.DepartmentTextNumber, cqi.Call.DepartmentId, profile, cqi.Address);
                                        }
                                        catch (SocketException sex)
                                        {
                                        }
                                        catch (Exception ex)
                                        {
                                            Logging.LogException(ex);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (unit.StationGroupId.HasValue)
                                {
                                    var members = _departmentGroupsService.GetAllMembersForGroup(unit.StationGroupId.Value);

                                    foreach (var member in members)
                                    {
                                        if (!dispatchedUsers.Contains(member.UserId))
                                        {
                                            dispatchedUsers.Add(member.UserId);
                                            try
                                            {
                                                var profile = cqi.Profiles.FirstOrDefault(x => x.UserId == member.UserId);
                                                _communicationService.SendCall(cqi.Call, new CallDispatch()
                                                {
                                                    UserId = member.UserId
                                                }, cqi.DepartmentTextNumber, cqi.Call.DepartmentId, profile, cqi.Address);
                                            }
                                            catch (SocketException sex)
                                            {
                                            }
                                            catch (Exception ex)
                                            {
                                                Logging.LogException(ex);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Dispatch Roles
                    if (cqi.Call.RoleDispatches != null && cqi.Call.RoleDispatches.Any())
                    {
                        if (_rolesService == null)
                        {
                            _rolesService = Bootstrapper.GetKernel().Resolve <IPersonnelRolesService>();
                        }

                        foreach (var d in cqi.Call.RoleDispatches)
                        {
                            var members = _rolesService.GetAllMembersOfRole(d.RoleId);

                            foreach (var member in members)
                            {
                                if (!dispatchedUsers.Contains(member.UserId))
                                {
                                    dispatchedUsers.Add(member.UserId);
                                    try
                                    {
                                        var profile = cqi.Profiles.FirstOrDefault(x => x.UserId == member.UserId);
                                        _communicationService.SendCall(cqi.Call, new CallDispatch()
                                        {
                                            UserId = member.UserId
                                        }, cqi.DepartmentTextNumber, cqi.Call.DepartmentId, profile, cqi.Address);
                                    }
                                    catch (SocketException sex)
                                    {
                                    }
                                    catch (Exception ex)
                                    {
                                        Logging.LogException(ex);
                                    }
                                }
                            }
                        }
                    }

                    // Send Call Print to Printer
                    if (_printerProvider == null)
                    {
                        _printerProvider = Bootstrapper.GetKernel().Resolve <IPrinterProvider>();
                    }

                    Dictionary <int, DepartmentGroup> fetchedGroups = new Dictionary <int, DepartmentGroup>();
                    if (cqi.Call.Dispatches != null && cqi.Call.Dispatches.Any())
                    {
                        foreach (var d in cqi.Call.Dispatches)
                        {
                            var group = _departmentGroupsService.GetGroupForUser(d.UserId, cqi.Call.DepartmentId);

                            if (group != null)
                            {
                                if (!groupIds.Contains(group.DepartmentGroupId))
                                {
                                    groupIds.Add(group.DepartmentGroupId);
                                }

                                if (!fetchedGroups.ContainsKey(group.DepartmentGroupId))
                                {
                                    fetchedGroups.Add(group.DepartmentGroupId, group);
                                }
                            }
                        }
                    }

                    foreach (var groupId in groupIds)
                    {
                        try
                        {
                            DepartmentGroup group = null;

                            if (fetchedGroups.ContainsKey(groupId))
                            {
                                group = fetchedGroups[groupId];
                            }
                            else
                            {
                                group = _departmentGroupsService.GetGroupById(groupId);
                            }

                            if (!String.IsNullOrWhiteSpace(group.PrinterData) && group.DispatchToPrinter)
                            {
                                var printerData = JsonConvert.DeserializeObject <DepartmentGroupPrinter>(group.PrinterData);
                                var apiKey      = SymmetricEncryption.Decrypt(printerData.ApiKey, Config.SystemBehaviorConfig.ExternalLinkUrlParamPassphrase);
                                var callUrl     = _callsService.GetShortenedCallPdfUrl(cqi.Call.CallId, true, groupId);

                                var printJob = _printerProvider.SubmitPrintJob(apiKey, printerData.PrinterId, "CallPrint", callUrl);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                        }
                    }
                }
            }
            finally
            {
                _communicationService = null;
            }
        }