Exemple #1
0
        public async Task <IActionResult> Index()
        {
            DepartmentGroupsModel model = new DepartmentGroupsModel();

            model.Users = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId);

            model.Groups = await _departmentGroupsService.GetAllGroupsForDepartmentUnlimitedAsync(DepartmentId);

            model.CanAddNewGroup = await _limitsService.CanDepartmentAddNewGroup(DepartmentId);

            return(View(model));
        }
Exemple #2
0
        public async Task <IActionResult> NewList()
        {
            var model = new NewListView();

            model.List        = new DistributionList();
            model.List.Port   = 110;
            model.ListTypes   = model.Type.ToSelectList();
            model.List.UseSsl = false;
            model.List.Type   = (int)DistributionListTypes.Internal;

            model.Users = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId, true);

            return(View(model));
        }
        public async Task <ActionResult <DepartmentStatusResult> > GetDepartmentStatus()
        {
            var result = new DepartmentStatusResult();

            result.Lup = await _departmentSettingsService.GetDepartmentUpdateTimestampAsync(DepartmentId);

            result.Users = (await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId)).Select(x => x.UserId.ToString()).ToList();

            return(result);
        }
Exemple #4
0
        public async Task <List <UserState> > GetStatesForDepartmentAsync(int departmentId)
        {
            var states = new List <UserState>();
            var users  = await _departmentsService.GetAllUsersForDepartmentAsync(departmentId);

            foreach (var u in users)
            {
                states.Add(await GetLastUserStateByUserIdAsync(u.UserId));
            }

            return(states);
        }
Exemple #5
0
        public async Task <IActionResult> Settings()
        {
            var model = new OrderSetttingsView();

            var department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId);

            var settings = await _resourceOrdersService.GetSettingsByDepartmentIdAsync(DepartmentId);

            if (settings != null)
            {
                model.Settings = settings;
            }
            else
            {
                model.Settings = new ResourceOrderSetting();
                model.Settings.DefaultResourceOrderManagerUserId = department.ManagingUserId;
                model.Settings.Range = 500;
            }

            model.OrderVisibilities = model.Visibility.ToSelectListInt();

            var staffingLevels = await _customStateService.GetActiveStaffingLevelsForDepartmentAsync(DepartmentId);

            if (staffingLevels == null)
            {
                model.StaffingLevels = model.UserStateTypes.ToSelectListInt();
            }
            else
            {
                model.StaffingLevels = new SelectList(staffingLevels.GetActiveDetails(), "CustomStateDetailId", "ButtonText");
            }

            model.SetUsers(await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId, false, true), await _departmentsService.GetAllPersonnelNamesForDepartmentAsync(DepartmentId));
            ViewBag.Users = new SelectList(model.Users, "Key", "Value");

            return(View(model));
        }
Exemple #6
0
        public async Task <ActionResult> IncomingMessage([FromQuery] TwilioMessage request)
        {
            if (request == null || string.IsNullOrWhiteSpace(request.To) || string.IsNullOrWhiteSpace(request.From) || string.IsNullOrWhiteSpace(request.Body))
            {
                return(BadRequest());
            }

            var response = new MessagingResponse();

            var textMessage = new TextMessage();

            textMessage.To        = request.To.Replace("+", "");
            textMessage.Msisdn    = request.From.Replace("+", "");
            textMessage.MessageId = request.MessageSid;
            textMessage.Timestamp = DateTime.UtcNow.ToLongDateString();
            textMessage.Data      = request.Body;
            textMessage.Text      = request.Body;

            var messageEvent = new InboundMessageEvent();

            messageEvent.MessageType = (int)InboundMessageTypes.TextMessage;
            messageEvent.RecievedOn  = DateTime.UtcNow;
            messageEvent.Type        = typeof(InboundMessageEvent).FullName;
            messageEvent.Data        = JsonConvert.SerializeObject(textMessage);
            messageEvent.Processed   = false;
            messageEvent.CustomerId  = "";

            try
            {
                var departmentId = await _departmentSettingsService.GetDepartmentIdByTextToCallNumberAsync(textMessage.To);

                if (departmentId.HasValue)
                {
                    var department = await _departmentsService.GetDepartmentByIdAsync(departmentId.Value);

                    var textToCallEnabled = await _departmentSettingsService.GetDepartmentIsTextCallImportEnabledAsync(departmentId.Value);

                    var textCommandEnabled = await _departmentSettingsService.GetDepartmentIsTextCommandEnabledAsync(departmentId.Value);

                    var dispatchNumbers = await _departmentSettingsService.GetTextToCallSourceNumbersForDepartmentAsync(departmentId.Value);

                    var authroized = await _limitsService.CanDepartmentProvisionNumberAsync(departmentId.Value);

                    var customStates = await _customStateService.GetAllActiveCustomStatesForDepartmentAsync(departmentId.Value);

                    messageEvent.CustomerId = departmentId.Value.ToString();

                    if (authroized)
                    {
                        bool isDispatchSource = false;

                        if (!String.IsNullOrWhiteSpace(dispatchNumbers))
                        {
                            isDispatchSource = _numbersService.DoesNumberMatchAnyPattern(dispatchNumbers.Split(Char.Parse(",")).ToList(), textMessage.Msisdn);
                        }

                        // If we don't have dispatchNumbers and Text Command isn't enabled it's a dispatch text
                        if (!isDispatchSource && !textCommandEnabled)
                        {
                            isDispatchSource = true;
                        }

                        if (isDispatchSource && textToCallEnabled)
                        {
                            var c = new Call();
                            c.Notes            = textMessage.Text;
                            c.NatureOfCall     = textMessage.Text;
                            c.LoggedOn         = DateTime.UtcNow;
                            c.Name             = string.Format("TTC {0}", c.LoggedOn.TimeConverter(department).ToString("g"));
                            c.Priority         = (int)CallPriority.High;
                            c.ReportingUserId  = department.ManagingUserId;
                            c.Dispatches       = new Collection <CallDispatch>();
                            c.CallSource       = (int)CallSources.EmailImport;
                            c.SourceIdentifier = textMessage.MessageId;
                            c.DepartmentId     = departmentId.Value;

                            var users = await _departmentsService.GetAllUsersForDepartmentAsync(departmentId.Value, true);

                            foreach (var u in users)
                            {
                                var cd = new CallDispatch();
                                cd.UserId = u.UserId;

                                c.Dispatches.Add(cd);
                            }

                            var savedCall = await _callsService.SaveCallAsync(c);

                            var cqi = new CallQueueItem();
                            cqi.Call     = savedCall;
                            cqi.Profiles = await _userProfileService.GetSelectedUserProfilesAsync(users.Select(x => x.UserId).ToList());

                            cqi.DepartmentTextNumber = await _departmentSettingsService.GetTextToCallNumberForDepartmentAsync(cqi.Call.DepartmentId);

                            _queueService.EnqueueCallBroadcastAsync(cqi);

                            messageEvent.Processed = true;
                        }

                        if (!isDispatchSource && textCommandEnabled)
                        {
                            var profile = await _userProfileService.GetProfileByMobileNumberAsync(textMessage.Msisdn);

                            if (profile != null)
                            {
                                var payload        = _textCommandService.DetermineType(textMessage.Text);
                                var customActions  = customStates.FirstOrDefault(x => x.Type == (int)CustomStateTypes.Personnel);
                                var customStaffing = customStates.FirstOrDefault(x => x.Type == (int)CustomStateTypes.Staffing);

                                switch (payload.Type)
                                {
                                case TextCommandTypes.None:
                                    response.Message("Resgrid (https://resgrid.com) Automated Text System. Unknown command, text help for supported commands.");
                                    break;

                                case TextCommandTypes.Help:
                                    messageEvent.Processed = true;

                                    var help = new StringBuilder();
                                    help.Append("Resgrid Text Commands" + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);
                                    help.Append("These are the commands you can text to alter your status and staffing. Text help for help." + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);
                                    help.Append("Core Commands" + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);
                                    help.Append("STOP: To turn off all text messages" + Environment.NewLine);
                                    help.Append("HELP: This help text" + Environment.NewLine);
                                    help.Append("CALLS: List active calls" + Environment.NewLine);
                                    help.Append("C[CallId]: Get Call Detail i.e. C1445" + Environment.NewLine);
                                    help.Append("UNITS: List unit statuses" + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);
                                    help.Append("Status or Action Commands" + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);

                                    if (customActions != null && customActions.IsDeleted == false && customActions.GetActiveDetails() != null && customActions.GetActiveDetails().Any())
                                    {
                                        var activeDetails = customActions.GetActiveDetails();
                                        for (int i = 0; i < activeDetails.Count; i++)
                                        {
                                            help.Append($"{activeDetails[i].ButtonText.Trim().Replace(" ", "").Replace("-", "").Replace(":", "")} or {i + 1}: {activeDetails[i].ButtonText}" + Environment.NewLine);
                                        }
                                    }
                                    else
                                    {
                                        help.Append("responding or 1: Responding" + Environment.NewLine);
                                        help.Append("notresponding or 2: Not Responding" + Environment.NewLine);
                                        help.Append("onscene or 3: On Scene" + Environment.NewLine);
                                        help.Append("available or 4: Available" + Environment.NewLine);
                                    }
                                    help.Append("---------------------" + Environment.NewLine);
                                    help.Append("Staffing Commands" + Environment.NewLine);
                                    help.Append("---------------------" + Environment.NewLine);

                                    if (customStaffing != null && customStaffing.IsDeleted == false && customStaffing.GetActiveDetails() != null && customStaffing.GetActiveDetails().Any())
                                    {
                                        var activeDetails = customStaffing.GetActiveDetails();
                                        for (int i = 0; i < activeDetails.Count; i++)
                                        {
                                            help.Append($"{activeDetails[i].ButtonText.Trim().Replace(" ", "").Replace("-", "").Replace(":", "")} or S{i + 1}: {activeDetails[i].ButtonText}" + Environment.NewLine);
                                        }
                                    }
                                    else
                                    {
                                        help.Append("available or s1: Available Staffing" + Environment.NewLine);
                                        help.Append("delayed or s2: Delayed Staffing" + Environment.NewLine);
                                        help.Append("unavailable or s3: Unavailable Staffing" + Environment.NewLine);
                                        help.Append("committed or s4: Committed Staffing" + Environment.NewLine);
                                        help.Append("onshift or s4: On Shift Staffing" + Environment.NewLine);
                                    }

                                    response.Message(help.ToString());

                                    //_communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Help", help.ToString(), department.DepartmentId, textMessage.To, profile);
                                    break;

                                case TextCommandTypes.Action:
                                    messageEvent.Processed = true;
                                    await _actionLogsService.SetUserActionAsync(profile.UserId, department.DepartmentId, (int)payload.GetActionType());

                                    response.Message(string.Format("Resgrid received your text command. Status changed to: {0}", payload.GetActionType()));
                                    //_communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Status", string.Format("Resgrid recieved your text command. Status changed to: {0}", payload.GetActionType()), department.DepartmentId, textMessage.To, profile);
                                    break;

                                case TextCommandTypes.Staffing:
                                    messageEvent.Processed = true;
                                    await _userStateService.CreateUserState(profile.UserId, department.DepartmentId, (int)payload.GetStaffingType());

                                    response.Message(string.Format("Resgrid received your text command. Staffing level changed to: {0}", payload.GetStaffingType()));
                                    //_communicationService.SendTextMessage(profile.UserId, "Resgrid TCI Staffing", string.Format("Resgrid recieved your text command. Staffing level changed to: {0}", payload.GetStaffingType()), department.DepartmentId, textMessage.To, profile);
                                    break;

                                case TextCommandTypes.Stop:
                                    messageEvent.Processed = true;
                                    await _userProfileService.DisableTextMessagesForUserAsync(profile.UserId);

                                    response.Message("Text messages are now turned off for this user, to enable again log in to Resgrid and update your profile.");
                                    break;

                                case TextCommandTypes.CustomAction:
                                    messageEvent.Processed = true;
                                    await _actionLogsService.SetUserActionAsync(profile.UserId, department.DepartmentId, payload.GetCustomActionType());

                                    if (customActions != null && customActions.IsDeleted == false && customActions.GetActiveDetails() != null && customActions.GetActiveDetails().Any() && customActions.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomActionType()) != null)
                                    {
                                        var detail = customActions.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomActionType());
                                        response.Message(string.Format("Resgrid received your text command. Status changed to: {0}", detail.ButtonText));
                                    }
                                    else
                                    {
                                        response.Message("Resgrid received your text command and updated your status");
                                    }
                                    break;

                                case TextCommandTypes.CustomStaffing:
                                    messageEvent.Processed = true;
                                    await _userStateService.CreateUserState(profile.UserId, department.DepartmentId, payload.GetCustomStaffingType());

                                    if (customStaffing != null && customStaffing.IsDeleted == false && customStaffing.GetActiveDetails() != null && customStaffing.GetActiveDetails().Any() && customStaffing.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomStaffingType()) != null)
                                    {
                                        var detail = customStaffing.GetActiveDetails().FirstOrDefault(x => x.CustomStateDetailId == payload.GetCustomStaffingType());
                                        response.Message(string.Format("Resgrid received your text command. Staffing changed to: {0}", detail.ButtonText));
                                    }
                                    else
                                    {
                                        response.Message("Resgrid received your text command and updated your staffing");
                                    }
                                    break;

                                case TextCommandTypes.MyStatus:
                                    messageEvent.Processed = true;


                                    var userStatus = await _actionLogsService.GetLastActionLogForUserAsync(profile.UserId);

                                    var userStaffing = await _userStateService.GetLastUserStateByUserIdAsync(profile.UserId);

                                    var customStatusLevel = await _customStateService.GetCustomPersonnelStatusAsync(department.DepartmentId, userStatus);

                                    var customStaffingLevel = await _customStateService.GetCustomPersonnelStaffingAsync(department.DepartmentId, userStaffing);

                                    response.Message($"Hello {profile.FullName.AsFirstNameLastName} at {DateTime.UtcNow.TimeConverterToString(department)} your current status is {customStatusLevel.ButtonText} and your current staffing is {customStaffingLevel.ButtonText}.");
                                    break;

                                case TextCommandTypes.Calls:
                                    messageEvent.Processed = true;

                                    var activeCalls = await _callsService.GetActiveCallsByDepartmentAsync(department.DepartmentId);

                                    var activeCallText = new StringBuilder();
                                    activeCallText.Append($"Active Calls for {department.Name}" + Environment.NewLine);
                                    activeCallText.Append("---------------------" + Environment.NewLine);

                                    foreach (var activeCall in activeCalls)
                                    {
                                        activeCallText.Append($"CallId: {activeCall.CallId} Name: {activeCall.Name} Nature:{activeCall.NatureOfCall}" + Environment.NewLine);
                                    }


                                    response.Message(activeCallText.ToString());
                                    break;

                                case TextCommandTypes.Units:
                                    messageEvent.Processed = true;

                                    var unitStatus = await _unitsService.GetAllLatestStatusForUnitsByDepartmentIdAsync(department.DepartmentId);

                                    var unitStatusesText = new StringBuilder();
                                    unitStatusesText.Append($"Unit Statuses for {department.Name}" + Environment.NewLine);
                                    unitStatusesText.Append("---------------------" + Environment.NewLine);

                                    foreach (var unit in unitStatus)
                                    {
                                        var unitState = await _customStateService.GetCustomUnitStateAsync(unit);

                                        unitStatusesText.Append($"{unit.Unit.Name} is {unitState.ButtonText}" + Environment.NewLine);
                                    }

                                    response.Message(unitStatusesText.ToString());
                                    break;

                                case TextCommandTypes.CallDetail:
                                    messageEvent.Processed = true;

                                    var call = await _callsService.GetCallByIdAsync(int.Parse(payload.Data));

                                    var callText = new StringBuilder();
                                    callText.Append($"Call Information for {call.Name}" + Environment.NewLine);
                                    callText.Append("---------------------" + Environment.NewLine);
                                    callText.Append($"Id: {call.CallId}" + Environment.NewLine);
                                    callText.Append($"Number: {call.Number}" + Environment.NewLine);
                                    callText.Append($"Logged: {call.LoggedOn.TimeConverterToString(department)}" + Environment.NewLine);
                                    callText.Append("-----Nature-----" + Environment.NewLine);
                                    callText.Append(call.NatureOfCall + Environment.NewLine);
                                    callText.Append("-----Address-----" + Environment.NewLine);

                                    if (!String.IsNullOrWhiteSpace(call.Address))
                                    {
                                        callText.Append(call.Address + Environment.NewLine);
                                    }
                                    else if (!string.IsNullOrEmpty(call.GeoLocationData))
                                    {
                                        try
                                        {
                                            string[] points = call.GeoLocationData.Split(char.Parse(","));

                                            if (points != null && points.Length == 2)
                                            {
                                                callText.Append(_geoLocationProvider.GetAproxAddressFromLatLong(double.Parse(points[0]), double.Parse(points[1])) + Environment.NewLine);
                                            }
                                        }
                                        catch
                                        {
                                        }
                                    }

                                    response.Message(callText.ToString());
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (textMessage.To == "17753765253")                 // Resgrid master text number
                {
                    var profile = await _userProfileService.GetProfileByMobileNumberAsync(textMessage.Msisdn);

                    var payload = _textCommandService.DetermineType(textMessage.Text);

                    switch (payload.Type)
                    {
                    case TextCommandTypes.None:
                        response.Message("Resgrid (https://resgrid.com) Automated Text System. Unknown command, text help for supported commands.");
                        break;

                    case TextCommandTypes.Help:
                        messageEvent.Processed = true;

                        var help = new StringBuilder();
                        help.Append("Resgrid Text Commands" + Environment.NewLine);
                        help.Append("---------------------" + Environment.NewLine);
                        help.Append("This is the Resgrid system for first responders (https://resgrid.com) automated text system. Your department isn't signed up for inbound text messages, but you can send the following commands." + Environment.NewLine);
                        help.Append("---------------------" + Environment.NewLine);
                        help.Append("STOP: To turn off all text messages" + Environment.NewLine);
                        help.Append("HELP: This help text" + Environment.NewLine);

                        response.Message(help.ToString());

                        break;

                    case TextCommandTypes.Stop:
                        messageEvent.Processed = true;
                        await _userProfileService.DisableTextMessagesForUserAsync(profile.UserId);

                        response.Message("Text messages are now turned off for this user, to enable again log in to Resgrid and update your profile.");
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Framework.Logging.LogException(ex);
            }
            finally
            {
                await _numbersService.SaveInboundMessageEventAsync(messageEvent);
            }

            //Ok();

            //var response = new TwilioResponse();

            //return Request.CreateResponse(HttpStatusCode.OK, response.Element, new XmlMediaTypeFormatter());
            return(Ok(new StringContent(response.ToString(), Encoding.UTF8, "application/xml")));
        }
Exemple #7
0
        /// <summary>
        /// Adds a new call into Resgrid and Dispatches the call
        /// </summary>
        /// <param name="callInput">Call data to add into the system</param>
        /// <returns></returns>
        public async Task <AddCallInput> AddCall([FromBody] AddCallInput callInput)
        {
            try
            {
                var call = new Call
                {
                    DepartmentId     = DepartmentId,
                    ReportingUserId  = UserId,
                    Priority         = callInput.Priority,
                    Name             = callInput.Name,
                    NatureOfCall     = callInput.NatureOfCall,
                    Number           = callInput.Number,
                    IsCritical       = callInput.IsCritical,
                    IncidentNumber   = callInput.IncidentNumber,
                    MapPage          = callInput.MapPage,
                    Notes            = callInput.Notes,
                    CompletedNotes   = callInput.CompletedNotes,
                    Address          = callInput.Address,
                    GeoLocationData  = callInput.GeoLocationData,
                    LoggedOn         = callInput.LoggedOn,
                    ClosedByUserId   = callInput.ClosedByUserId,
                    ClosedOn         = callInput.ClosedOn,
                    State            = callInput.State,
                    IsDeleted        = callInput.IsDeleted,
                    CallSource       = callInput.CallSource,
                    DispatchCount    = callInput.DispatchCount,
                    LastDispatchedOn = callInput.LastDispatchedOn,
                    SourceIdentifier = callInput.SourceIdentifier,
                    W3W                = callInput.W3W,
                    ContactName        = callInput.ContactName,
                    ContactNumber      = callInput.ContactNumber,
                    Public             = callInput.Public,
                    ExternalIdentifier = callInput.ExternalIdentifier,
                    ReferenceNumber    = callInput.ReferenceNumber
                };

                if (string.IsNullOrWhiteSpace(call.GeoLocationData) && !string.IsNullOrWhiteSpace(call.Address))
                {
                    call.GeoLocationData = _geoLocationProvider.GetLatLonFromAddress(call.Address);
                }

                if (string.IsNullOrWhiteSpace(call.GeoLocationData) && !string.IsNullOrWhiteSpace(call.W3W))
                {
                    var coords = await _geoLocationProvider.GetCoordinatesFromW3WAsync(call.W3W);

                    if (coords != null)
                    {
                        call.GeoLocationData = $"{coords.Latitude},{coords.Longitude}";
                    }
                }

                call.LoggedOn = DateTime.UtcNow;

                if (!String.IsNullOrWhiteSpace(callInput.Type) && callInput.Type != "No Type")
                {
                    var callTypes = await _callsService.GetCallTypesForDepartmentAsync(DepartmentId);

                    var type = callTypes.FirstOrDefault(x => x.Type == callInput.Type);

                    if (type != null)
                    {
                        call.Type = type.Type;
                    }
                }

                call.Dispatches      = new List <CallDispatch>();
                call.GroupDispatches = new List <CallDispatchGroup>();
                call.RoleDispatches  = new List <CallDispatchRole>();

                List <string> groupUserIds = new List <string>();

                var users = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId);

                if (callInput.AllCall)
                {
                    foreach (var u in users)
                    {
                        var cd = new CallDispatch {
                            UserId = u.UserId
                        };

                        call.Dispatches.Add(cd);
                    }
                }
                else
                {
                    if (callInput.GroupCodesToDispatch != null && callInput.GroupCodesToDispatch.Count > 0)
                    {
                        var allGroups = await _departmentGroupsService.GetAllGroupsForDepartmentAsync(DepartmentId);

                        foreach (var groupCode in callInput.GroupCodesToDispatch)
                        {
                            var groupsToDispatch = allGroups.FirstOrDefault(x => x.DispatchEmail == groupCode);

                            if (groupsToDispatch != null)
                            {
                                var cd = new CallDispatchGroup {
                                    DepartmentGroupId = groupsToDispatch.DepartmentGroupId
                                };
                                call.GroupDispatches.Add(cd);

                                if (groupsToDispatch.Members != null && groupsToDispatch.Members.Any())
                                {
                                    foreach (var departmentGroupMember in groupsToDispatch.Members)
                                    {
                                        if (!groupUserIds.Contains(departmentGroupMember.UserId))
                                        {
                                            groupUserIds.Add(departmentGroupMember.UserId);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (callInput.Attachments != null && callInput.Attachments.Any())
                {
                    call.Attachments = new List <CallAttachment>();

                    foreach (var attachment in callInput.Attachments)
                    {
                        var newAttachment = new CallAttachment();
                        newAttachment.Data               = attachment.Data;
                        newAttachment.Timestamp          = DateTime.UtcNow;
                        newAttachment.FileName           = attachment.FileName;
                        newAttachment.Size               = attachment.Size;
                        newAttachment.CallAttachmentType = attachment.CallAttachmentType;

                        call.Attachments.Add(newAttachment);
                    }
                }

                var savedCall = _callsService.SaveCall(call);


                OutboundEventProvider.CallAddedTopicHandler handler = new OutboundEventProvider.CallAddedTopicHandler();
                handler.Handle(new CallAddedEvent()
                {
                    DepartmentId = DepartmentId, Call = savedCall
                });

                var cqi = new CallQueueItem();
                cqi.Call = savedCall;

                if (cqi.Call.Dispatches != null && cqi.Call.Dispatches.Any())
                {
                    cqi.Profiles =
                        await _userProfileService.GetSelectedUserProfilesAsync(cqi.Call.Dispatches.Select(x => x.UserId).ToList());
                }
                else
                {
                    if (groupUserIds.Any())
                    {
                        cqi.Profiles = await _userProfileService.GetSelectedUserProfilesAsync(groupUserIds);
                    }
                }

                _queueService.EnqueueCallBroadcast(cqi);

                callInput.CallId = savedCall.CallId;
                callInput.Number = savedCall.Number;
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);

                throw ex;
            }

            return(callInput);
        }
Exemple #8
0
        public async Task <ActionResult <List <PersonnelViewModel> > > GetPersonnelStatuses()
        {
            var department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId, false);

            var stations = await _departmentGroupsService.GetAllStationGroupsForDepartmentAsync(DepartmentId);

            var calls = await _callsService.GetActiveCallsByDepartmentAsync(DepartmentId);

            var allUsers = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId);

            var hideUnavailable = await _departmentSettingsService.GetBigBoardHideUnavailableDepartmentAsync(DepartmentId);

            //var lastUserActionlogs = await _actionLogsService.GetAllActionLogsForDepartmentAsync(DepartmentId);
            var lastUserActionlogs = await _actionLogsService.GetLastActionLogsForDepartmentAsync(DepartmentId);

            var departmentGroups = await _departmentGroupsService.GetAllGroupsForDepartmentAsync(DepartmentId);

            var lastUserStates = await _userStateService.GetLatestStatesForDepartmentAsync(DepartmentId);

            var personnelNames = await _departmentsService.GetAllPersonnelNamesForDepartmentAsync(DepartmentId);

            var names = new Dictionary <string, string>();

            var userStates = new List <UserState>();

            foreach (var u in allUsers)
            {
                var state = lastUserStates.FirstOrDefault(x => x.UserId == u.UserId);

                if (state != null)
                {
                    userStates.Add(state);
                }
                else
                {
                    userStates.Add(await _userStateService.GetLastUserStateByUserIdAsync(u.UserId));
                }

                var name = personnelNames.FirstOrDefault(x => x.UserId == u.UserId);
                if (name != null)
                {
                    names.Add(u.UserId, name.Name);
                }
            }

            var personnelViewModels = new List <PersonnelViewModel>();



            var sortedUngroupedUsers = from u in allUsers
                                       // let mu = Membership.GetUser(u.UserId)
                                       let userGroup = departmentGroups.FirstOrDefault(x => x.Members.Any(y => y.UserId == u.UserId))
                                                       let groupName = userGroup == null ? "" : userGroup.Name
                                                                       //let roles = _personnelRolesService.GetRolesForUserAsync(u.UserId, DepartmentId).Result
                                                                       //let name = (ProfileBase.Create(mu.UserName, true)).GetPropertyValue("Name").ToString()
                                                                       let name = names.ContainsKey(u.UserId) ? names[u.UserId] : "Unknown User"
                                                                                  let weight = lastUserActionlogs.Where(x => x.UserId == u.UserId).FirstOrDefault().GetWeightForAction()
                                                                                               orderby groupName, weight, name ascending
                select new
            {
                Name  = name,
                User  = u,
                Group = userGroup,
                Roles = new List <PersonnelRole>()
            };

            foreach (var u in sortedUngroupedUsers)
            {
                //var mu = Membership.GetUser(u.User.UserId);
                var al = lastUserActionlogs.Where(x => x.UserId == u.User.UserId).FirstOrDefault();
                var us = userStates.Where(x => x.UserId == u.User.UserId).FirstOrDefault();

                // if setting is such, ignore unavailable users.
                if (hideUnavailable.HasValue && hideUnavailable.Value && us.State != (int)UserStateTypes.Unavailable)
                {
                    continue;
                }

                u.Roles.AddRange(await _personnelRolesService.GetRolesForUserAsync(u.User.UserId, DepartmentId));

                string callNumber = "";
                if (al != null && al.ActionTypeId == (int)ActionTypes.RespondingToScene ||
                    (al != null && al.DestinationType.HasValue && al.DestinationType.Value == 2))
                {
                    if (al.DestinationId.HasValue)
                    {
                        var call = calls.FirstOrDefault(x => x.CallId == al.DestinationId.Value);

                        if (call != null)
                        {
                            callNumber = call.Number;
                        }
                    }
                }
                var respondingToDepartment =
                    stations.Where(s => al != null && s.DepartmentGroupId == al.DestinationId).FirstOrDefault();
                var personnelViewModel = await PersonnelViewModel.Create(u.Name, al, us, department, respondingToDepartment, u.Group,
                                                                         u.Roles, callNumber);

                personnelViewModels.Add(personnelViewModel);
            }

            return(personnelViewModels);
        }
Exemple #9
0
        public async Task <ActionResult <UnitAppPayloadResult> > GetCommandAppCoreData()
        {
            var results = new UnitAppPayloadResult();

            results.Personnel    = new List <PersonnelInfoResult>();
            results.Groups       = new List <GroupInfoResult>();
            results.Units        = new List <UnitInfoResult>();
            results.Roles        = new List <RoleInfoResult>();
            results.Statuses     = new List <CustomStatusesResult>();
            results.Calls        = new List <CallResultEx>();
            results.UnitStatuses = new List <UnitStatusCoreResult>();
            results.UnitRoles    = new List <UnitRoleResult>();

            var users = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId);

            var groups = await _departmentGroupsService.GetAllDepartmentGroupsForDepartmentAsync(DepartmentId);

            var rolesForUsersInDepartment = await _personnelRolesService.GetAllRolesForUsersInDepartmentAsync(DepartmentId);

            var allRoles = await _personnelRolesService.GetRolesForDepartmentAsync(DepartmentId);

            var allProfiles = await _userProfileService.GetAllProfilesForDepartmentAsync(DepartmentId);

            var allGroups = await _departmentGroupsService.GetAllGroupsForDepartmentAsync(DepartmentId);

            var units = await _unitsService.GetUnitsForDepartmentAsync(DepartmentId);

            var unitTypes = await _unitsService.GetUnitTypesForDepartmentAsync(DepartmentId);


            foreach (var user in users)
            {
                //var profile = _userProfileService.GetProfileByUserId(user.UserId);
                //var group = _departmentGroupsService.GetGroupForUser(user.UserId);

                UserProfile profile = null;
                if (allProfiles.ContainsKey(user.UserId))
                {
                    profile = allProfiles[user.UserId];
                }

                DepartmentGroup group = null;
                if (groups.ContainsKey(user.UserId))
                {
                    group = groups[user.UserId];
                }

                //var roles = _personnelRolesService.GetRolesForUser(user.UserId);

                List <PersonnelRole> roles = null;
                if (rolesForUsersInDepartment.ContainsKey(user.UserId))
                {
                    roles = rolesForUsersInDepartment[user.UserId];
                }

                var result = new PersonnelInfoResult();

                if (profile != null)
                {
                    result.Fnm = profile.FirstName;
                    result.Lnm = profile.LastName;
                    result.Id  = profile.IdentificationNumber;
                    result.Mnu = profile.MobileNumber;
                }
                else
                {
                    result.Fnm = "Unknown";
                    result.Lnm = "Check Profile";
                    result.Id  = "";
                    result.Mnu = "";
                }

                result.Eml = user.Email;
                result.Did = DepartmentId;
                result.Uid = user.UserId.ToString();

                if (group != null)
                {
                    result.Gid = group.DepartmentGroupId;
                    result.Gnm = group.Name;
                }

                result.Roles = new List <string>();
                if (roles != null && roles.Count > 0)
                {
                    foreach (var role in roles)
                    {
                        if (role != null)
                        {
                            result.Roles.Add(role.Name);
                        }
                    }
                }

                results.Personnel.Add(result);
            }


            results.Rights = new DepartmentRightsResult();
            var currentUser = await _usersService.GetUserByNameAsync(UserName);

            if (currentUser == null)
            {
                return(Unauthorized());
            }

            var department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId, false);

            results.Rights.Adm  = department.IsUserAnAdmin(currentUser.UserId);
            results.Rights.Grps = new List <GroupRight>();

            var currentGroup = await _departmentGroupsService.GetGroupForUserAsync(currentUser.UserId, DepartmentId);

            if (currentGroup != null)
            {
                var groupRight = new GroupRight();
                groupRight.Gid = currentGroup.DepartmentGroupId;
                groupRight.Adm = currentGroup.IsUserGroupAdmin(currentUser.UserId);

                results.Rights.Grps.Add(groupRight);
            }

            foreach (var group in allGroups)
            {
                var groupInfo = new GroupInfoResult();
                groupInfo.Gid = group.DepartmentGroupId;
                groupInfo.Nme = group.Name;

                if (group.Type.HasValue)
                {
                    groupInfo.Typ = group.Type.Value;
                }

                if (group.Address != null)
                {
                    groupInfo.Add = group.Address.FormatAddress();
                }

                results.Groups.Add(groupInfo);
            }

            foreach (var unit in units)
            {
                var unitResult = new UnitInfoResult();
                unitResult.Uid = unit.UnitId;
                unitResult.Did = DepartmentId;
                unitResult.Nme = unit.Name;
                unitResult.Typ = unit.Type;

                if (!string.IsNullOrWhiteSpace(unit.Type))
                {
                    var unitType = unitTypes.FirstOrDefault(x => x.Type == unit.Type);

                    if (unitType != null)
                    {
                        unitResult.Cid = unitType.CustomStatesId.GetValueOrDefault();
                    }
                }
                else
                {
                    unitResult.Cid = 0;
                }

                if (unit.StationGroup != null)
                {
                    unitResult.Sid = unit.StationGroup.DepartmentGroupId;
                    unitResult.Snm = unit.StationGroup.Name;
                }

                results.Units.Add(unitResult);

                // Add unit roles for this unit
                var roles = await _unitsService.GetRolesForUnitAsync(unit.UnitId);

                foreach (var role in roles)
                {
                    var roleResult = new UnitRoleResult();
                    roleResult.Name       = role.Name;
                    roleResult.UnitId     = role.UnitId;
                    roleResult.UnitRoleId = role.UnitRoleId;

                    results.UnitRoles.Add(roleResult);
                }
            }

            var unitStatuses = await _unitsService.GetAllLatestStatusForUnitsByDepartmentIdAsync(DepartmentId);

            foreach (var us in unitStatuses)
            {
                var unitStatus = new UnitStatusCoreResult();
                unitStatus.UnitId      = us.UnitId;
                unitStatus.StateType   = (UnitStateTypes)us.State;
                unitStatus.StateTypeId = us.State;
                unitStatus.Type        = us.Unit.Type;
                unitStatus.Timestamp   = us.Timestamp.TimeConverter(department);
                unitStatus.Name        = us.Unit.Name;

                if (us.DestinationId.HasValue)
                {
                    unitStatus.DestinationId = us.DestinationId.Value;
                }

                results.UnitStatuses.Add(unitStatus);
            }

            foreach (var role in allRoles)
            {
                var roleResult = new RoleInfoResult();
                roleResult.Rid = role.PersonnelRoleId;
                roleResult.Nme = role.Name;

                results.Roles.Add(roleResult);
            }

            var customStates = await _customStateService.GetAllActiveCustomStatesForDepartmentAsync(DepartmentId);

            foreach (var customState in customStates)
            {
                if (customState.IsDeleted)
                {
                    continue;
                }

                foreach (var stateDetail in customState.GetActiveDetails())
                {
                    if (stateDetail.IsDeleted)
                    {
                        continue;
                    }

                    var customStateResult = new CustomStatusesResult();
                    customStateResult.Id      = stateDetail.CustomStateDetailId;
                    customStateResult.Type    = customState.Type;
                    customStateResult.StateId = stateDetail.CustomStateId;
                    customStateResult.Text    = stateDetail.ButtonText;
                    customStateResult.BColor  = stateDetail.ButtonColor;
                    customStateResult.Color   = stateDetail.TextColor;
                    customStateResult.Gps     = stateDetail.GpsRequired;
                    customStateResult.Note    = stateDetail.NoteType;
                    customStateResult.Detail  = stateDetail.DetailType;

                    results.Statuses.Add(customStateResult);
                }
            }

            var calls = (await _callsService.GetActiveCallsByDepartmentAsync(DepartmentId)).OrderByDescending(x => x.LoggedOn);

            if (calls != null && calls.Any())
            {
                foreach (var c in calls)
                {
                    var call = new CallResultEx();

                    call.Cid = c.CallId;
                    call.Pri = c.Priority;
                    call.Ctl = c.IsCritical;
                    call.Nme = c.Name;
                    call.Noc = c.NatureOfCall;
                    call.Map = c.MapPage;
                    call.Not = c.Notes;

                    if (String.IsNullOrWhiteSpace(c.Address) && !String.IsNullOrWhiteSpace(c.GeoLocationData))
                    {
                        var geo = c.GeoLocationData.Split(char.Parse(","));

                        if (geo.Length == 2)
                        {
                            call.Add = await _geoLocationProvider.GetAddressFromLatLong(double.Parse(geo[0]), double.Parse(geo[1]));
                        }
                    }
                    else
                    {
                        call.Add = c.Address;
                    }

                    call.Add = c.Address;
                    call.Geo = c.GeoLocationData;
                    call.Lon = c.LoggedOn.TimeConverter(department);
                    call.Ste = c.State;
                    call.Num = c.Number;

                    results.Calls.Add(call);
                }
            }
            else
            {
                // This is a hack due to a bug in the current units app! -SJ 1-31-2016
                var call = new CallResultEx();
                call.Cid = 0;
                call.Pri = 0;
                call.Ctl = false;
                call.Nme = "No Call";
                call.Noc = "";
                call.Map = "";
                call.Not = "";
                call.Add = "";
                call.Geo = "";
                call.Lon = DateTime.UtcNow;
                call.Ste = 0;
                call.Num = "";

                results.Calls.Add(call);
            }


            return(Ok(results));
        }
Exemple #10
0
        public async Task <ActionResult> Receive(PostmarkInboundMessage message, CancellationToken cancellationToken)
        {
            if (message != null)
            {
                try
                {
                    var mailMessage = new MimeMessage();

                    if (message.FromFull != null && !String.IsNullOrWhiteSpace(message.FromFull.Email) && message.FromFull.Email.Trim() == "*****@*****.**")
                    {
                        return(CreatedAtAction(nameof(Receive), new { id = message.MessageID }, message));
                    }

                    if (message.FromFull != null && !String.IsNullOrWhiteSpace(message.FromFull.Email) && !String.IsNullOrWhiteSpace(message.FromFull.Name))
                    {
                        mailMessage.From.Add(new MailboxAddress(message.FromFull.Name.Trim(), message.FromFull.Email.Trim()));
                    }
                    else
                    {
                        mailMessage.From.Add(new MailboxAddress("Inbound Email Dispatch", "*****@*****.**"));
                    }

                    if (!String.IsNullOrWhiteSpace(message.Subject))
                    {
                        mailMessage.Subject = message.Subject;
                    }
                    else
                    {
                        mailMessage.Subject = "Dispatch Email";
                    }

                    var builder = new BodyBuilder();

                    if (!String.IsNullOrWhiteSpace(message.HtmlBody))
                    {
                        builder.HtmlBody = HttpUtility.HtmlDecode(message.HtmlBody);
                    }

                    if (!String.IsNullOrWhiteSpace(message.TextBody))
                    {
                        builder.TextBody = message.TextBody;
                    }

                    int    type         = 0;          // 1 = dispatch // 2 = email list // 3 = group dispatch // 4 = group message
                    string emailAddress = String.Empty;
                    string bounceEmail  = String.Empty;
                    string name         = String.Empty;

                    #region Trying to Find What type of email this is
                    if (message.ToFull != null)
                    {
                        foreach (var email in message.ToFull)
                        {
                            if (StringHelpers.ValidateEmail(email.Email))
                            {
                                if (email.Email.Contains($"@{Config.InboundEmailConfig.DispatchDomain}") || email.Email.Contains($"@{Config.InboundEmailConfig.DispatchTestDomain}"))
                                {
                                    type = 1;

                                    if (email.Email.Contains($"@{Config.InboundEmailConfig.DispatchDomain}"))
                                    {
                                        emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.DispatchDomain}", "");
                                    }
                                    else
                                    {
                                        emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.DispatchTestDomain}", "");
                                    }

                                    name = email.Name;
                                    mailMessage.To.Clear();
                                    mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));

                                    break;
                                }
                                else if (email.Email.Contains($"@{Config.InboundEmailConfig.ListsDomain}") || email.Email.Contains($"@{Config.InboundEmailConfig.ListsTestDomain}"))
                                {
                                    type = 2;

                                    if (email.Email.Contains($"@{Config.InboundEmailConfig.ListsDomain}"))
                                    {
                                        emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.ListsDomain}", "");
                                    }
                                    else
                                    {
                                        emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.ListsTestDomain}", "");
                                    }

                                    if (emailAddress.Contains("+") && emailAddress.Contains("="))
                                    {
                                        var tempBounceEmail = emailAddress.Substring(emailAddress.IndexOf("+") + 1);
                                        bounceEmail = tempBounceEmail.Replace("=", "@");

                                        emailAddress = emailAddress.Replace(tempBounceEmail, "");
                                        emailAddress = emailAddress.Replace("+", "");
                                    }

                                    name = email.Name;
                                    mailMessage.To.Clear();
                                    mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));

                                    break;
                                }
                                else if (email.Email.Contains($"@{Config.InboundEmailConfig.GroupsDomain}") || email.Email.Contains($"@{Config.InboundEmailConfig.GroupsTestDomain}"))
                                {
                                    type = 3;

                                    if (email.Email.Contains($"@{Config.InboundEmailConfig.GroupsDomain}"))
                                    {
                                        emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.GroupsDomain}", "");
                                    }
                                    else
                                    {
                                        emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.GroupsTestDomain}", "");
                                    }

                                    name = email.Name;
                                    mailMessage.To.Clear();
                                    mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));

                                    break;
                                }
                                else if (email.Email.Contains($"@{Config.InboundEmailConfig.GroupMessageDomain}") || email.Email.Contains($"@{Config.InboundEmailConfig.GroupTestMessageDomain}"))
                                {
                                    type = 4;

                                    if (email.Email.Contains($"@{Config.InboundEmailConfig.GroupMessageDomain}"))
                                    {
                                        emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.GroupMessageDomain}", "");
                                    }
                                    else
                                    {
                                        emailAddress = email.Email.Replace($"@{Config.InboundEmailConfig.GroupTestMessageDomain}", "");
                                    }

                                    name = email.Name;
                                    mailMessage.To.Clear();
                                    mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));

                                    break;
                                }
                            }
                        }
                    }

                    // Some providers aren't putting email address in the To line, process the CC line
                    if (type == 0 && message.CcFull != null)
                    {
                        foreach (var email in message.CcFull)
                        {
                            if (StringHelpers.ValidateEmail(email.Email))
                            {
                                var proccedEmailInfo = ProcessEmailAddress(email.Email);

                                if (proccedEmailInfo.Item1 > 0)
                                {
                                    type         = proccedEmailInfo.Item1;
                                    emailAddress = proccedEmailInfo.Item2;

                                    mailMessage.To.Clear();
                                    mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));
                                }
                            }
                        }
                    }

                    if (type == 0 && message.BccFull != null)
                    {
                        foreach (var email in message.BccFull)
                        {
                            if (StringHelpers.ValidateEmail(email.Email))
                            {
                                var proccedEmailInfo = ProcessEmailAddress(email.Email);

                                if (proccedEmailInfo.Item1 > 0)
                                {
                                    type         = proccedEmailInfo.Item1;
                                    emailAddress = proccedEmailInfo.Item2;

                                    mailMessage.To.Clear();
                                    mailMessage.To.Add(new MailboxAddress(email.Name, email.Email));
                                }
                            }
                        }
                    }

                    // If To and CC didn't work, try the header.
                    if (type == 0)
                    {
                        try
                        {
                            if (message.Headers != null && message.Headers.Count > 0)
                            {
                                var header = message.Headers.FirstOrDefault(x => x.Name == "Received-SPF");

                                if (header != null)
                                {
                                    var lastValue = header.Value.LastIndexOf(char.Parse("="));
                                    var newEmail  = header.Value.Substring(lastValue + 1, (header.Value.Length - (lastValue + 1)));

                                    newEmail = newEmail.Trim();

                                    if (StringHelpers.ValidateEmail(newEmail))
                                    {
                                        emailAddress = newEmail;
                                        var proccedEmailInfo = ProcessEmailAddress(newEmail);

                                        type         = proccedEmailInfo.Item1;
                                        emailAddress = proccedEmailInfo.Item2;

                                        mailMessage.To.Clear();
                                        mailMessage.To.Add(new MailboxAddress("Email Importer", newEmail));
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logging.LogException(ex);
                        }
                    }
                    #endregion Trying to Find What type of email this is

                    if (type == 1)                      // Dispatch
                    {
                        #region Dispatch Email
                        var departmentId = await _departmentSettingsService.GetDepartmentIdForDispatchEmailAsync(emailAddress);

                        if (departmentId.HasValue)
                        {
                            try
                            {
                                var emailSettings = await _departmentsService.GetDepartmentEmailSettingsAsync(departmentId.Value);

                                List <IdentityUser> departmentUsers = await _departmentsService.GetAllUsersForDepartmentAsync(departmentId.Value, true);

                                var callEmail = new CallEmail();

                                if (!String.IsNullOrWhiteSpace(message.Subject))
                                {
                                    callEmail.Subject = message.Subject;
                                }

                                else
                                {
                                    callEmail.Subject = "Dispatch Email";
                                }

                                if (!String.IsNullOrWhiteSpace(message.HtmlBody))
                                {
                                    callEmail.Body = HttpUtility.HtmlDecode(message.HtmlBody);
                                }
                                else
                                {
                                    callEmail.Body = message.TextBody;
                                }

                                callEmail.TextBody = message.TextBody;

                                foreach (var attachment in message.Attachments)
                                {
                                    try
                                    {
                                        if (Convert.ToInt32(attachment.ContentLength) > 0)
                                        {
                                            if (attachment.Name.Contains(".mp3") || attachment.Name.Contains(".amr"))
                                            {
                                                byte[] filebytes = Convert.FromBase64String(attachment.Content);

                                                callEmail.DispatchAudioFileName = attachment.Name;
                                                callEmail.DispatchAudio         = filebytes;
                                            }
                                        }
                                    }
                                    catch { }
                                }

                                if (emailSettings == null)
                                {
                                    emailSettings              = new DepartmentCallEmail();
                                    emailSettings.FormatType   = (int)CallEmailTypes.Generic;
                                    emailSettings.DepartmentId = departmentId.Value;
                                    emailSettings.Department   = await _departmentsService.GetDepartmentByIdAsync(departmentId.Value, false);
                                }
                                else if (emailSettings.Department == null)
                                {
                                    emailSettings.Department = await _departmentsService.GetDepartmentByIdAsync(departmentId.Value);
                                }

                                var activeCalls = await _callsService.GetLatest10ActiveCallsByDepartmentAsync(emailSettings.Department.DepartmentId);

                                var units = await _unitsService.GetUnitsForDepartmentAsync(emailSettings.Department.DepartmentId);

                                var priorities = await _callsService.GetActiveCallPrioritiesForDepartmentAsync(emailSettings.Department.DepartmentId);

                                int defaultPriority = (int)CallPriority.High;

                                if (priorities != null && priorities.Any())
                                {
                                    var defaultPrio = priorities.FirstOrDefault(x => x.IsDefault && x.IsDeleted == false);

                                    if (defaultPrio != null)
                                    {
                                        defaultPriority = defaultPrio.DepartmentCallPriorityId;
                                    }
                                }

                                var call = _callsService.GenerateCallFromEmail(emailSettings.FormatType, callEmail,
                                                                               emailSettings.Department.ManagingUserId,
                                                                               departmentUsers, emailSettings.Department, activeCalls, units, defaultPriority, priorities);

                                if (call != null && call.CallId <= 0)
                                {
                                    // New Call Dispatch as normal
                                    call.DepartmentId = departmentId.Value;

                                    if (!String.IsNullOrWhiteSpace(call.Address) && String.IsNullOrWhiteSpace(call.GeoLocationData))
                                    {
                                        call.GeoLocationData = await _geoLocationProvider.GetLatLonFromAddress(call.Address);
                                    }

                                    var savedCall = await _callsService.SaveCallAsync(call, cancellationToken);

                                    var cqi = new CallQueueItem();
                                    cqi.Call                 = savedCall;
                                    cqi.Profiles             = (await _userProfileService.GetAllProfilesForDepartmentAsync(call.DepartmentId)).Select(x => x.Value).ToList();
                                    cqi.DepartmentTextNumber = await _departmentSettingsService.GetTextToCallNumberForDepartmentAsync(cqi.Call.DepartmentId);

                                    await _queueService.EnqueueCallBroadcastAsync(cqi, cancellationToken);

                                    return(CreatedAtAction(nameof(Receive), new { id = savedCall.CallId }, savedCall));
                                }
                                else if (call != null && call.CallId > 0)
                                {
                                    // Existing Call, just update
                                    if (!String.IsNullOrWhiteSpace(call.Address) && String.IsNullOrWhiteSpace(call.GeoLocationData))
                                    {
                                        call.GeoLocationData = await _geoLocationProvider.GetLatLonFromAddress(call.Address);
                                    }

                                    var savedCall = await _callsService.SaveCallAsync(call, cancellationToken);

                                    // If our Dispatch Count changed, i.e. 2nd Alarm to 3rd Alarm, redispatch
                                    if (call.DidDispatchCountChange())
                                    {
                                        var cqi = new CallQueueItem();
                                        cqi.Call                 = savedCall;
                                        cqi.Profiles             = (await _userProfileService.GetAllProfilesForDepartmentAsync(call.DepartmentId)).Select(x => x.Value).ToList();
                                        cqi.DepartmentTextNumber = await _departmentSettingsService.GetTextToCallNumberForDepartmentAsync(cqi.Call.DepartmentId);

                                        await _queueService.EnqueueCallBroadcastAsync(cqi, cancellationToken);
                                    }

                                    return(CreatedAtAction(nameof(Receive), new { id = savedCall.CallId }, savedCall));
                                }
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                return(BadRequest(message));
                            }
                        }
                        #endregion Dispatch
                    }
                    else if (type == 2)                     // Email List
                    {
                        #region Distribution Email
                        var list = await _distributionListsService.GetDistributionListByAddressAsync(emailAddress);

                        if (list != null)
                        {
                            if (String.IsNullOrWhiteSpace(bounceEmail))
                            {
                                try
                                {
                                    List <Model.File> files = new List <Model.File>();

                                    try
                                    {
                                        if (message.Attachments != null && message.Attachments.Any())
                                        {
                                            foreach (var attachment in message.Attachments)
                                            {
                                                if (Convert.ToInt32(attachment.ContentLength) > 0)
                                                {
                                                    Model.File file = new Model.File();

                                                    byte[] filebytes = Convert.FromBase64String(attachment.Content);

                                                    file.Data         = filebytes;
                                                    file.FileName     = attachment.Name;
                                                    file.DepartmentId = list.DepartmentId;
                                                    file.ContentId    = attachment.ContentID;
                                                    file.FileType     = attachment.ContentType;
                                                    file.Timestamp    = DateTime.UtcNow;

                                                    files.Add(await _fileService.SaveFileAsync(file, cancellationToken));
                                                }
                                            }
                                        }
                                    }
                                    catch { }

                                    var dlqi = new DistributionListQueueItem();
                                    dlqi.List  = list;
                                    dlqi.Users = await _departmentsService.GetAllUsersForDepartmentAsync(list.DepartmentId);

                                    if (files != null && files.Any())
                                    {
                                        dlqi.FileIds = new List <int>();
                                        dlqi.FileIds.AddRange(files.Select(x => x.FileId).ToList());
                                    }

                                    dlqi.Message             = new InboundMessage();
                                    dlqi.Message.Attachments = new List <InboundMessageAttachment>();

                                    if (message.FromFull != null && !String.IsNullOrWhiteSpace(message.FromFull.Email) && !String.IsNullOrWhiteSpace(message.FromFull.Name))
                                    {
                                        dlqi.Message.FromEmail = message.FromFull.Email.Trim();
                                        dlqi.Message.FromName  = message.FromFull.Name.Trim();
                                    }

                                    dlqi.Message.Subject   = message.Subject;
                                    dlqi.Message.HtmlBody  = message.HtmlBody;
                                    dlqi.Message.TextBody  = message.TextBody;
                                    dlqi.Message.MessageID = message.MessageID;

                                    await _queueService.EnqueueDistributionListBroadcastAsync(dlqi, cancellationToken);
                                }
                                catch (Exception ex)
                                {
                                    Logging.LogException(ex);
                                    return(BadRequest(message));
                                }
                            }
                            else
                            {
                                return(CreatedAtAction(nameof(Receive), new { id = message.MessageID }, message));
                            }
                        }

                        return(CreatedAtAction(nameof(Receive), new { id = message.MessageID }, message));

                        #endregion Distribution Email
                    }
                    if (type == 3)                      // Group Dispatch
                    {
                        #region Group Dispatch Email
                        var departmentGroup = await _departmentGroupsService.GetGroupByDispatchEmailCodeAsync(emailAddress);

                        if (departmentGroup != null)
                        {
                            try
                            {
                                var emailSettings = await _departmentsService.GetDepartmentEmailSettingsAsync(departmentGroup.DepartmentId);

                                var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroupAndChildGroups(departmentGroup);

                                var callEmail = new CallEmail();
                                callEmail.Subject = message.Subject;

                                if (!String.IsNullOrWhiteSpace(message.HtmlBody))
                                {
                                    callEmail.Body = HttpUtility.HtmlDecode(message.HtmlBody);
                                }
                                else
                                {
                                    callEmail.Body = message.TextBody;
                                }

                                foreach (var attachment in message.Attachments)
                                {
                                    try
                                    {
                                        if (Convert.ToInt32(attachment.ContentLength) > 0)
                                        {
                                            if (attachment.Name.Contains(".mp3") || attachment.Name.Contains(".amr"))
                                            {
                                                byte[] filebytes = Convert.FromBase64String(attachment.Content);

                                                callEmail.DispatchAudioFileName = attachment.Name;
                                                callEmail.DispatchAudio         = filebytes;
                                            }
                                        }
                                    }
                                    catch { }
                                }

                                if (emailSettings == null)
                                {
                                    emailSettings              = new DepartmentCallEmail();
                                    emailSettings.FormatType   = (int)CallEmailTypes.Generic;
                                    emailSettings.DepartmentId = departmentGroup.DepartmentId;

                                    if (departmentGroup.Department != null)
                                    {
                                        emailSettings.Department = departmentGroup.Department;
                                    }
                                    else
                                    {
                                        emailSettings.Department = await _departmentsService.GetDepartmentByIdAsync(departmentGroup.DepartmentId);
                                    }
                                }

                                var activeCalls = await _callsService.GetActiveCallsByDepartmentAsync(emailSettings.Department.DepartmentId);

                                var units = await _unitsService.GetAllUnitsForGroupAsync(departmentGroup.DepartmentGroupId);

                                var priorities = await _callsService.GetActiveCallPrioritiesForDepartmentAsync(emailSettings.Department.DepartmentId);

                                int defaultPriority = (int)CallPriority.High;

                                if (priorities != null && priorities.Any())
                                {
                                    var defaultPrio = priorities.FirstOrDefault(x => x.IsDefault && x.IsDeleted == false);

                                    if (defaultPrio != null)
                                    {
                                        defaultPriority = defaultPrio.DepartmentCallPriorityId;
                                    }
                                }

                                var call = _callsService.GenerateCallFromEmail(emailSettings.FormatType, callEmail,
                                                                               emailSettings.Department.ManagingUserId,
                                                                               departmentGroupUsers.Select(x => x.User).ToList(), emailSettings.Department, activeCalls, units, defaultPriority, priorities);

                                if (call != null)
                                {
                                    call.DepartmentId = departmentGroup.DepartmentId;

                                    var savedCall = await _callsService.SaveCallAsync(call, cancellationToken);

                                    var cqi = new CallQueueItem();
                                    cqi.Call     = savedCall;
                                    cqi.Profiles = await _userProfileService.GetSelectedUserProfilesAsync(departmentGroupUsers.Select(x => x.UserId).ToList());

                                    cqi.DepartmentTextNumber = await _departmentSettingsService.GetTextToCallNumberForDepartmentAsync(cqi.Call.DepartmentId);

                                    await _queueService.EnqueueCallBroadcastAsync(cqi, cancellationToken);

                                    return(CreatedAtAction(nameof(Receive), new { id = savedCall.CallId }, savedCall));
                                }
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                return(BadRequest());
                            }
                        }
                        #endregion Group Dispatch Email
                    }
                    if (type == 4)                      // Group Message
                    {
                        #region Group Message
                        var departmentGroup = await _departmentGroupsService.GetGroupByMessageEmailCodeAsync(emailAddress);

                        if (departmentGroup != null)
                        {
                            try
                            {
                                var departmentGroupUsers = _departmentGroupsService.GetAllMembersForGroupAndChildGroups(departmentGroup);

                                var newMessage = new Message();
                                newMessage.SentOn          = DateTime.UtcNow;
                                newMessage.SendingUserId   = departmentGroup.Department.ManagingUserId;
                                newMessage.IsBroadcast     = true;
                                newMessage.Subject         = message.Subject;
                                newMessage.SystemGenerated = true;

                                if (!String.IsNullOrWhiteSpace(message.HtmlBody))
                                {
                                    newMessage.Body = HttpUtility.HtmlDecode(message.HtmlBody);
                                }
                                else
                                {
                                    newMessage.Body = message.TextBody;
                                }

                                foreach (var member in departmentGroupUsers)
                                {
                                    if (newMessage.GetRecipients().All(x => x != member.UserId))
                                    {
                                        newMessage.AddRecipient(member.UserId);
                                    }
                                }

                                var savedMessage = await _messageService.SaveMessageAsync(newMessage, cancellationToken);

                                await _messageService.SendMessageAsync(savedMessage, "", departmentGroup.DepartmentId, false, cancellationToken);

                                return(CreatedAtAction(nameof(Receive), new { id = savedMessage.MessageId }, savedMessage));
                            }
                            catch (Exception ex)
                            {
                                Logging.LogException(ex);
                                return(BadRequest());
                            }
                        }

                        #endregion Group Message
                    }

                    return(BadRequest());
                }
                catch (Exception ex)
                {
                    Framework.Logging.LogException(ex);
                    return(BadRequest(ex.ToString()));
                }
            }
            else
            {
                // If our message was null, we throw an exception
                return(BadRequest("Error parsing Inbound Message, message is null."));
            }
        }
Exemple #11
0
        public async Task <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 = await _departmentsService.GetAllUsersForDepartmentAsync(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 = await _departmentGroupsService.GetAllMembersForGroupAsync(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 = await _personnelRolesService.GetAllMembersOfRoleAsync(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);
                    }
                }

                await _trainingService.SaveAsync(model.Training);

                return(RedirectToAction("Index"));
            }

            return(View(model));
        }
Exemple #12
0
        public async Task <ActionResult <List <StationResult> > > GetStationResources()
        {
            var result = new List <StationResult>();

            var unitStatuses = await _unitsService.GetAllLatestStatusForUnitsByDepartmentIdAsync(DepartmentId);

            var actionLogs = await _actionLogsService.GetAllActionLogsForDepartmentAsync(DepartmentId);

            var userStates = await _userStateService.GetLatestStatesForDepartmentAsync(DepartmentId);

            var stations = await _departmentGroupsService.GetAllGroupsForDepartmentAsync(DepartmentId);

            var userGroups = await _departmentGroupsService.GetAllDepartmentGroupsForDepartmentAsync(DepartmentId);

            var users = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId);

            var units = await _unitsService.GetUnitsForDepartmentAsync(DepartmentId);

            Department department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId, false);

            Parallel.ForEach(users, u =>
            {
                var log = (from l in actionLogs
                           where l.UserId == u.UserId
                           select l).FirstOrDefault();

                var state = (from l in userStates
                             where l.UserId == u.UserId
                             select l).FirstOrDefault();

                var s = new StationResult();
                s.Id  = u.UserId.ToString();
                s.Typ = 1;

                if (log != null)
                {
                    s.Sts = log.ActionTypeId;
                    s.Stm = log.Timestamp.TimeConverter(department);

                    if (log.DestinationId.HasValue)
                    {
                        if (log.ActionTypeId == (int)ActionTypes.RespondingToStation)
                        {
                            s.Did = log.DestinationId.GetValueOrDefault();

                            var group = stations.First(x => x.DepartmentGroupId == log.DestinationId.Value);
                            s.Dnm     = group.Name;
                        }
                        else if (log.ActionTypeId == (int)ActionTypes.AvailableStation)
                        {
                            s.Did = log.DestinationId.GetValueOrDefault();

                            var group = stations.First(x => x.DepartmentGroupId == log.DestinationId.Value);
                            s.Dnm     = group.Name;
                        }
                    }
                }
                else
                {
                    s.Sts = (int)ActionTypes.StandingBy;
                    s.Stm = DateTime.UtcNow.TimeConverter(department);
                }

                if (s.Did == 0)
                {
                    if (userGroups.ContainsKey(u.UserId))
                    {
                        var homeGroup = userGroups[u.UserId];
                        if (homeGroup != null && homeGroup.Type.HasValue &&
                            ((DepartmentGroupTypes)homeGroup.Type) == DepartmentGroupTypes.Station)
                        {
                            s.Did = homeGroup.DepartmentGroupId;
                            s.Dnm = homeGroup.Name;
                        }
                    }
                }

                if (state != null)
                {
                    s.Ste = state.State;
                    s.Stt = state.Timestamp.TimeConverter(department);
                }
                else
                {
                    s.Ste = (int)UserStateTypes.Available;
                    s.Stt = DateTime.UtcNow.TimeConverter(department);
                }

                if (!String.IsNullOrWhiteSpace(s.Dnm))
                {
                    result.Add(s);
                }
            });

            Parallel.ForEach(unitStatuses, unit =>
            {
                var unitResult = new StationResult();
                var savedUnit  = units.FirstOrDefault(x => x.UnitId == unit.UnitId);

                if (savedUnit != null)
                {
                    unitResult.Id = savedUnit.UnitId.ToString();
                    //unitResult.Nme = savedUnit.Name;
                    unitResult.Typ = 2;
                    unitResult.Sts = unit.State;
                    unitResult.Stm = unit.Timestamp.TimeConverter(department);

                    if (savedUnit.StationGroupId.HasValue)
                    {
                        unitResult.Did = savedUnit.StationGroupId.Value;
                        unitResult.Dnm = stations.First(x => x.DepartmentGroupId == savedUnit.StationGroupId.Value).Name;

                        result.Add(unitResult);
                    }
                }
            });

            return(Ok(result));
        }
Exemple #13
0
        public async Task <ActionResult <NewCallPayloadResult> > GetNewCallData()
        {
            var results = new NewCallPayloadResult();

            results.Personnel    = new List <PersonnelInfoResult>();
            results.Groups       = new List <GroupInfoResult>();
            results.Units        = new List <UnitInfoResult>();
            results.Roles        = new List <RoleInfoResult>();
            results.Statuses     = new List <CustomStatusesResult>();
            results.UnitStatuses = new List <UnitStatusCoreResult>();
            results.UnitRoles    = new List <UnitRoleResult>();
            results.Priorities   = new List <CallPriorityResult>();
            results.CallTypes    = new List <CallTypeResult>();

            var department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId, false);

            var users = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId);

            var groups = await _departmentGroupsService.GetAllDepartmentGroupsForDepartmentAsync(DepartmentId);

            var rolesForUsersInDepartment = await _personnelRolesService.GetAllRolesForUsersInDepartmentAsync(DepartmentId);

            var allRoles = await _personnelRolesService.GetRolesForDepartmentAsync(DepartmentId);

            var allProfiles = await _userProfileService.GetAllProfilesForDepartmentAsync(DepartmentId);

            var allGroups = await _departmentGroupsService.GetAllGroupsForDepartmentAsync(DepartmentId);

            var units = await _unitsService.GetUnitsForDepartmentAsync(DepartmentId);

            var unitTypes = await _unitsService.GetUnitTypesForDepartmentAsync(DepartmentId);

            var callPriorites = await _callsService.GetActiveCallPrioritiesForDepartmentAsync(DepartmentId);

            var callTypes = await _callsService.GetCallTypesForDepartmentAsync(DepartmentId);


            foreach (var user in users)
            {
                //var profile = _userProfileService.GetProfileByUserId(user.UserId);
                //var group = _departmentGroupsService.GetGroupForUser(user.UserId);

                UserProfile profile = null;
                if (allProfiles.ContainsKey(user.UserId))
                {
                    profile = allProfiles[user.UserId];
                }

                DepartmentGroup group = null;
                if (groups.ContainsKey(user.UserId))
                {
                    group = groups[user.UserId];
                }

                //var roles = _personnelRolesService.GetRolesForUser(user.UserId);

                List <PersonnelRole> roles = null;
                if (rolesForUsersInDepartment.ContainsKey(user.UserId))
                {
                    roles = rolesForUsersInDepartment[user.UserId];
                }

                var result = new PersonnelInfoResult();

                if (profile != null)
                {
                    result.Fnm = profile.FirstName;
                    result.Lnm = profile.LastName;
                    result.Id  = profile.IdentificationNumber;
                    result.Mnu = profile.MobileNumber;
                }
                else
                {
                    result.Fnm = "Unknown";
                    result.Lnm = "Check Profile";
                    result.Id  = "";
                    result.Mnu = "";
                }

                result.Eml = user.Email;
                result.Did = DepartmentId;
                result.Uid = user.UserId.ToString();

                if (group != null)
                {
                    result.Gid = group.DepartmentGroupId;
                    result.Gnm = group.Name;
                }

                result.Roles = new List <string>();
                if (roles != null && roles.Count > 0)
                {
                    foreach (var role in roles)
                    {
                        if (role != null)
                        {
                            result.Roles.Add(role.Name);
                        }
                    }
                }

                results.Personnel.Add(result);
            }

            foreach (var group in allGroups)
            {
                var groupInfo = new GroupInfoResult();
                groupInfo.Gid = group.DepartmentGroupId;
                groupInfo.Nme = group.Name;

                if (group.Type.HasValue)
                {
                    groupInfo.Typ = group.Type.Value;
                }

                if (group.Address != null)
                {
                    groupInfo.Add = group.Address.FormatAddress();
                }

                results.Groups.Add(groupInfo);
            }

            foreach (var unit in units)
            {
                var unitResult = new UnitInfoResult();
                unitResult.Uid = unit.UnitId;
                unitResult.Did = DepartmentId;
                unitResult.Nme = unit.Name;
                unitResult.Typ = unit.Type;

                if (!string.IsNullOrWhiteSpace(unit.Type))
                {
                    var unitType = unitTypes.FirstOrDefault(x => x.Type == unit.Type);

                    if (unitType != null)
                    {
                        unitResult.Cid = unitType.CustomStatesId.GetValueOrDefault();
                    }
                }
                else
                {
                    unitResult.Cid = 0;
                }

                if (unit.StationGroup != null)
                {
                    unitResult.Sid = unit.StationGroup.DepartmentGroupId;
                    unitResult.Snm = unit.StationGroup.Name;
                }

                results.Units.Add(unitResult);

                // Add unit roles for this unit
                var roles = await _unitsService.GetRolesForUnitAsync(unit.UnitId);

                foreach (var role in roles)
                {
                    var roleResult = new UnitRoleResult();
                    roleResult.Name       = role.Name;
                    roleResult.UnitId     = role.UnitId;
                    roleResult.UnitRoleId = role.UnitRoleId;

                    results.UnitRoles.Add(roleResult);
                }
            }

            var unitStatuses = await _unitsService.GetAllLatestStatusForUnitsByDepartmentIdAsync(DepartmentId);

            foreach (var us in unitStatuses)
            {
                var unitStatus = new UnitStatusCoreResult();
                unitStatus.UnitId      = us.UnitId;
                unitStatus.StateType   = (UnitStateTypes)us.State;
                unitStatus.StateTypeId = us.State;
                unitStatus.Type        = us.Unit.Type;
                unitStatus.Timestamp   = us.Timestamp.TimeConverter(department);
                unitStatus.Name        = us.Unit.Name;
                unitStatus.Note        = us.Note;

                if (us.DestinationId.HasValue)
                {
                    unitStatus.DestinationId = us.DestinationId.Value;
                }

                if (us.LocalTimestamp.HasValue)
                {
                    unitStatus.LocalTimestamp = us.LocalTimestamp.Value;
                }

                if (us.Latitude.HasValue)
                {
                    unitStatus.Latitude = us.Latitude.Value;
                }

                if (us.Longitude.HasValue)
                {
                    unitStatus.Longitude = us.Longitude.Value;
                }

                results.UnitStatuses.Add(unitStatus);
            }

            foreach (var role in allRoles)
            {
                var roleResult = new RoleInfoResult();
                roleResult.Rid = role.PersonnelRoleId;
                roleResult.Nme = role.Name;

                results.Roles.Add(roleResult);
            }

            var customStates = await _customStateService.GetAllActiveCustomStatesForDepartmentAsync(DepartmentId);

            foreach (var customState in customStates)
            {
                if (customState.IsDeleted)
                {
                    continue;
                }

                foreach (var stateDetail in customState.GetActiveDetails())
                {
                    if (stateDetail.IsDeleted)
                    {
                        continue;
                    }

                    var customStateResult = new CustomStatusesResult();
                    customStateResult.Id      = stateDetail.CustomStateDetailId;
                    customStateResult.Type    = customState.Type;
                    customStateResult.StateId = stateDetail.CustomStateId;
                    customStateResult.Text    = stateDetail.ButtonText;
                    customStateResult.BColor  = stateDetail.ButtonColor;
                    customStateResult.Color   = stateDetail.TextColor;
                    customStateResult.Gps     = stateDetail.GpsRequired;
                    customStateResult.Note    = stateDetail.NoteType;
                    customStateResult.Detail  = stateDetail.DetailType;

                    results.Statuses.Add(customStateResult);
                }
            }

            foreach (var priority in callPriorites)
            {
                var priorityResult = new CallPriorityResult();
                priorityResult.Id           = priority.DepartmentCallPriorityId;
                priorityResult.DepartmentId = priority.DepartmentId;
                priorityResult.Name         = priority.Name;
                priorityResult.Color        = priority.Color;
                priorityResult.Sort         = priority.Sort;
                priorityResult.IsDeleted    = priority.IsDeleted;
                priorityResult.IsDefault    = priority.IsDefault;

                results.Priorities.Add(priorityResult);
            }

            if (callTypes != null && callTypes.Any())
            {
                foreach (var callType in callTypes)
                {
                    var type = new CallTypeResult();
                    type.Id   = callType.CallTypeId;
                    type.Name = callType.Type;

                    results.CallTypes.Add(type);
                }
            }


            return(results);
        }
Exemple #14
0
        public async Task <ActionResult <CoreDataResult> > GetCoreData()
        {
            var results = new CoreDataResult();

            results.Personnel   = new List <PersonnelInfoResult>();
            results.Groups      = new List <GroupInfoResult>();
            results.Units       = new List <UnitInfoResult>();
            results.Roles       = new List <RoleInfoResult>();
            results.Statuses    = new List <CustomStatusesResult>();
            results.Priorities  = new List <CallPriorityResult>();
            results.Departments = new List <JoinedDepartmentResult>();
            results.PersonnelListStatusOrders = new List <PersonnelListStatusOrder>();

            var users = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId);

            var groups = await _departmentGroupsService.GetAllDepartmentGroupsForDepartmentAsync(DepartmentId);

            var rolesForUsersInDepartment = await _personnelRolesService.GetAllRolesForUsersInDepartmentAsync(DepartmentId);

            var allRoles = await _personnelRolesService.GetRolesForDepartmentAsync(DepartmentId);

            var allProfiles = await _userProfileService.GetAllProfilesForDepartmentAsync(DepartmentId);

            var allGroups = await _departmentGroupsService.GetAllGroupsForDepartmentAsync(DepartmentId);

            var units = await _unitsService.GetUnitsForDepartmentAsync(DepartmentId);

            var unitTypes = await _unitsService.GetUnitTypesForDepartmentAsync(DepartmentId);

            var callPriorites = await _callsService.GetCallPrioritiesForDepartmentAsync(DepartmentId);

            var personnelListStatusOrderings = await _departmentSettingsService.GetDepartmentPersonnelListStatusSortOrderAsync(DepartmentId);

            var personnelListSortOrder = await _departmentSettingsService.GetDepartmentPersonnelSortOrderAsync(DepartmentId);


            if (personnelListStatusOrderings != null)
            {
                results.PersonnelListStatusOrders = personnelListStatusOrderings;
            }

            results.PersonnelNameSorting = (int)personnelListSortOrder;

            foreach (var user in users)
            {
                UserProfile profile = null;
                if (allProfiles.ContainsKey(user.UserId))
                {
                    profile = allProfiles[user.UserId];
                }

                DepartmentGroup group = null;
                if (groups.ContainsKey(user.UserId))
                {
                    group = groups[user.UserId];
                }

                List <PersonnelRole> roles = null;
                if (rolesForUsersInDepartment.ContainsKey(user.UserId))
                {
                    roles = rolesForUsersInDepartment[user.UserId];
                }

                var result = new PersonnelInfoResult();

                if (profile != null)
                {
                    result.Fnm = profile.FirstName;
                    result.Lnm = profile.LastName;
                    result.Id  = profile.IdentificationNumber;


                    result.Mnu = profile.MobileNumber;
                }
                else
                {
                    result.Fnm = "Unknown";
                    result.Lnm = "Check Profile";
                    result.Id  = "";
                    result.Mnu = "";
                }

                if (user != null)
                {
                    result.Eml = user.Email;
                }

                result.Did = DepartmentId;
                result.Uid = user.UserId.ToString();

                if (group != null)
                {
                    result.Gid = group.DepartmentGroupId;
                    result.Gnm = group.Name;
                }

                result.Roles = new List <string>();
                if (roles != null && roles.Count > 0)
                {
                    foreach (var role in roles)
                    {
                        if (role != null)
                        {
                            result.Roles.Add(role.Name);
                        }
                    }
                }

                results.Personnel.Add(result);
            }


            results.Rights = new DepartmentRightsResult();
            var currentUser = await _usersService.GetUserByNameAsync(UserName);

            if (currentUser == null)
            {
                return(Unauthorized());
            }

            var department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId, false);

            results.Rights.Adm  = department.IsUserAnAdmin(currentUser.UserId);
            results.Rights.Grps = new List <GroupRight>();

            var currentGroup = await _departmentGroupsService.GetGroupForUserAsync(currentUser.UserId, DepartmentId);

            if (currentGroup != null)
            {
                var groupRight = new GroupRight();
                groupRight.Gid = currentGroup.DepartmentGroupId;
                groupRight.Adm = currentGroup.IsUserGroupAdmin(currentUser.UserId);

                results.Rights.Grps.Add(groupRight);
            }

            foreach (var group in allGroups)
            {
                var groupInfo = new GroupInfoResult();
                groupInfo.Gid = group.DepartmentGroupId;
                groupInfo.Nme = group.Name;

                if (group.Type.HasValue)
                {
                    groupInfo.Typ = group.Type.Value;
                }

                if (group.Address != null)
                {
                    groupInfo.Add = group.Address.FormatAddress();
                }

                results.Groups.Add(groupInfo);
            }

            foreach (var unit in units)
            {
                var unitResult = new UnitInfoResult();
                unitResult.Uid = unit.UnitId;
                unitResult.Did = DepartmentId;
                unitResult.Nme = unit.Name;
                unitResult.Typ = unit.Type;

                if (!string.IsNullOrWhiteSpace(unit.Type))
                {
                    var unitType = unitTypes.FirstOrDefault(x => x.Type == unit.Type);

                    if (unitType != null)
                    {
                        unitResult.Cid = unitType.CustomStatesId.GetValueOrDefault();
                    }
                }
                else
                {
                    unitResult.Cid = 0;
                }

                if (unit.StationGroup != null)
                {
                    unitResult.Sid = unit.StationGroup.DepartmentGroupId;
                    unitResult.Snm = unit.StationGroup.Name;
                }

                results.Units.Add(unitResult);
            }

            foreach (var role in allRoles)
            {
                var roleResult = new RoleInfoResult();
                roleResult.Rid = role.PersonnelRoleId;
                roleResult.Nme = role.Name;

                results.Roles.Add(roleResult);
            }

            var customStates = await _customStateService.GetAllActiveCustomStatesForDepartmentAsync(DepartmentId);

            foreach (var customState in customStates)
            {
                if (customState != null)
                {
                    if (customState.IsDeleted || customState.Details == null)
                    {
                        continue;
                    }

                    foreach (var stateDetail in customState.Details)
                    {
                        if (stateDetail == null || stateDetail.IsDeleted)
                        {
                            continue;
                        }

                        var customStateResult = new CustomStatusesResult();
                        customStateResult.Id      = stateDetail.CustomStateDetailId;
                        customStateResult.Type    = customState.Type;
                        customStateResult.StateId = stateDetail.CustomStateId;
                        customStateResult.Text    = stateDetail.ButtonText;
                        customStateResult.BColor  = stateDetail.ButtonColor;
                        customStateResult.Color   = stateDetail.TextColor;
                        customStateResult.Gps     = stateDetail.GpsRequired;
                        customStateResult.Note    = stateDetail.NoteType;
                        customStateResult.Detail  = stateDetail.DetailType;

                        if (customState.IsDeleted)
                        {
                            customStateResult.IsDeleted = true;
                        }
                        else
                        {
                            customStateResult.IsDeleted = stateDetail.IsDeleted;
                        }

                        results.Statuses.Add(customStateResult);
                    }
                }
            }

            foreach (var priority in callPriorites)
            {
                var priorityResult = new CallPriorityResult();
                priorityResult.Id           = priority.DepartmentCallPriorityId;
                priorityResult.DepartmentId = priority.DepartmentId;
                priorityResult.Name         = priority.Name;
                priorityResult.Color        = priority.Color;
                priorityResult.Sort         = priority.Sort;
                priorityResult.IsDeleted    = priority.IsDeleted;
                priorityResult.IsDefault    = priority.IsDefault;

                results.Priorities.Add(priorityResult);
            }

            var members = await _departmentsService.GetAllDepartmentsForUserAsync(UserId);

            foreach (var member in members)
            {
                if (member.IsDeleted)
                {
                    continue;
                }

                if (member.IsDisabled.GetValueOrDefault())
                {
                    continue;
                }

                var depRest = new JoinedDepartmentResult();
                depRest.Did = member.DepartmentId;
                depRest.Nme = member.Department.Name;

                results.Departments.Add(depRest);
            }

            return(Ok(results));
        }
Exemple #15
0
        public async Task <ActionResult <List <PersonnelStatusResult> > > GetPersonnelStatusesForLink(int linkId)
        {
            var link = await _departmentLinksService.GetLinkByIdAsync(linkId);

            if (link.DepartmentId != DepartmentId && link.LinkedDepartmentId != DepartmentId)
            {
                return(new List <PersonnelStatusResult>());
            }

            var results = new List <PersonnelStatusResult>();

            var actionLogs = await _actionLogsService.GetAllActionLogsForDepartmentAsync(link.DepartmentId);

            var userStates = await _userStateService.GetLatestStatesForDepartmentAsync(link.DepartmentId);

            var users = await _departmentsService.GetAllUsersForDepartmentAsync(link.DepartmentId);

            Department department = await _departmentsService.GetDepartmentByIdAsync(link.DepartmentId, false);

            foreach (var u in users)
            {
                var log = (from l in actionLogs
                           where l.UserId == u.UserId
                           select l).FirstOrDefault();

                var state = (from l in userStates
                             where l.UserId == u.UserId
                             select l).FirstOrDefault();

                var s = new PersonnelStatusResult();
                s.Uid = u.UserId.ToString();

                if (log != null)
                {
                    s.Atp = log.ActionTypeId;
                    s.Atm = log.Timestamp.TimeConverter(department);

                    if (log.DestinationId.HasValue)
                    {
                        if (log.ActionTypeId == (int)ActionTypes.RespondingToScene)
                        {
                            s.Did = log.DestinationId.Value.ToString();
                        }
                        else if (log.ActionTypeId == (int)ActionTypes.RespondingToStation)
                        {
                            s.Did = log.DestinationId.Value.ToString();
                        }
                        else if (log.ActionTypeId == (int)ActionTypes.AvailableStation)
                        {
                            s.Did = log.DestinationId.Value.ToString();
                        }
                    }
                }
                else
                {
                    s.Atp = (int)ActionTypes.StandingBy;
                    s.Atm = DateTime.UtcNow.TimeConverter(department);
                }

                if (state != null)
                {
                    s.Ste = state.State;
                    s.Stm = state.Timestamp.TimeConverter(department);
                }
                else
                {
                    s.Ste = (int)UserStateTypes.Available;
                    s.Stm = DateTime.UtcNow.TimeConverter(department);
                }
                results.Add(s);
            }


            return(Ok(results));
        }
Exemple #16
0
        public async Task <Tuple <bool, string> > Process(CallEmailQueueItem item)
        {
            bool   success = true;
            string result  = "";

            _callEmailProvider = Bootstrapper.GetKernel().Resolve <ICallEmailProvider>();

            if (!String.IsNullOrWhiteSpace(item?.EmailSettings?.Hostname))
            {
                CallEmailsResult emailResult = _callEmailProvider.GetAllCallEmailsFromServer(item.EmailSettings);

                if (emailResult?.Emails != null && emailResult.Emails.Count > 0)
                {
                    var calls = new List <Call>();

                    _callsService              = Bootstrapper.GetKernel().Resolve <ICallsService>();
                    _queueService              = Bootstrapper.GetKernel().Resolve <IQueueService>();
                    _departmentsService        = Bootstrapper.GetKernel().Resolve <IDepartmentsService>();
                    _userProfileService        = Bootstrapper.GetKernel().Resolve <IUserProfileService>();
                    _departmentSettingsService = Bootstrapper.GetKernel().Resolve <IDepartmentSettingsService>();
                    _unitsService              = Bootstrapper.GetKernel().Resolve <IUnitsService>();

                    // Ran into an issue where the department users didn't come back. We can't put the email back in the POP
                    // email box so just added some simple retry logic here.
                    List <IdentityUser> departmentUsers = await _departmentsService.GetAllUsersForDepartmentAsync(item.EmailSettings.DepartmentId, true);

                    var profiles = await _userProfileService.GetAllProfilesForDepartmentAsync(item.EmailSettings.DepartmentId);

                    int retry = 0;
                    while (retry < 3 && departmentUsers == null)
                    {
                        Thread.Sleep(150);
                        departmentUsers = await _departmentsService.GetAllUsersForDepartmentAsync(item.EmailSettings.DepartmentId, true);

                        retry++;
                    }

                    foreach (var email in emailResult.Emails)
                    {
                        var activeCalls = await _callsService.GetActiveCallsByDepartmentAsync(item.EmailSettings.Department.DepartmentId);

                        var units = await _unitsService.GetUnitsForDepartmentAsync(item.EmailSettings.Department.DepartmentId);

                        var priorities = await _callsService.GetActiveCallPrioritiesForDepartmentAsync(item.EmailSettings.Department.DepartmentId);

                        int defaultPriority = (int)CallPriority.High;

                        if (priorities != null && priorities.Any())
                        {
                            var defaultPrio = priorities.FirstOrDefault(x => x.IsDefault && x.IsDeleted == false);

                            if (defaultPrio != null)
                            {
                                defaultPriority = defaultPrio.DepartmentCallPriorityId;
                            }
                        }

                        var call = _callsService.GenerateCallFromEmail(item.EmailSettings.FormatType, email,
                                                                       item.EmailSettings.Department.ManagingUserId, departmentUsers, item.EmailSettings.Department, activeCalls, units, defaultPriority, priorities);

                        if (call != null)
                        {
                            call.DepartmentId = item.EmailSettings.DepartmentId;

                            if (!calls.Any(x => x.Name == call.Name && x.NatureOfCall == call.NatureOfCall))
                            {
                                calls.Add(call);
                            }
                        }
                    }

                    if (calls.Any())
                    {
                        var departmentTextNumber = await _departmentSettingsService.GetTextToCallNumberForDepartmentAsync(item.EmailSettings.DepartmentId);

                        foreach (var call in calls)
                        {
                            try
                            {
                                // Adding this in here to try and fix the error below with ObjectContext issues.
                                var newCall = CreateNewCallFromCall(call);

                                if (newCall.Dispatches != null && newCall.Dispatches.Any())
                                {
                                    // We've been having this error here:
                                    //      The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
                                    // So I'm wrapping this in a try catch to prevent all calls form being dropped.
                                    var savedCall = await _callsService.SaveCallAsync(newCall);

                                    var cqi = new CallQueueItem();
                                    cqi.Call = savedCall;

                                    cqi.Profiles             = profiles.Values.ToList();
                                    cqi.DepartmentTextNumber = departmentTextNumber;

                                    await _queueService.EnqueueCallBroadcastAsync(cqi);
                                }
                            }
                            catch (Exception ex)
                            {
                                result = ex.ToString();
                                Logging.LogException(ex);
                            }
                        }
                    }

                    await _departmentsService.SaveDepartmentEmailSettingsAsync(emailResult.EmailSettings);

                    _callsService              = null;
                    _queueService              = null;
                    _departmentsService        = null;
                    _callEmailProvider         = null;
                    _userProfileService        = null;
                    _departmentSettingsService = null;
                }
            }

            return(new Tuple <bool, string>(success, result));
        }
Exemple #17
0
        public async Task <IActionResult> Compose(ComposeMessageModel model, IFormCollection collection, CancellationToken cancellationToken)
        {
            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 = await _shiftsService.GetShiftByIdAsync(int.Parse(shiftId));

                        excludedUsers.AddRange(shift.Personnel.Select(x => x.UserId));
                    }
                }

                model.Message.Type = (int)model.MessageType;
                if (model.SendToAll)
                {
                    var allUsers = await _departmentsService.GetAllUsersForDepartmentAsync(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 = await _personnelRolesService.GetAllMembersOfRoleAsync(int.Parse(role));

                        usersInRoles.Add(int.Parse(role), roleMembers.Select(x => x.UserId).ToList());
                    }

                    foreach (var group in groups)
                    {
                        var members = await _departmentGroupsService.GetAllMembersForGroupAsync(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 = await _departmentGroupsService.GetAllMembersForGroupAsync(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 = await _personnelRolesService.GetAllMembersOfRoleAsync(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 = await _messageService.SaveMessageAsync(model.Message, cancellationToken);

                await _messageService.SendMessageAsync(savedMessage, "", DepartmentId, false, cancellationToken);

                return(RedirectToAction("Inbox"));
            }

            model.Department = await _departmentsService.GetDepartmentByIdAsync(DepartmentId);

            model.User  = _usersService.GetUserById(UserId);
            model.Types = model.MessageType.ToSelectList();

            var savedShifts = await _shiftsService.GetAllShiftsByDepartmentAsync(DepartmentId);

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

            return(View(await FillComposeMessageModel(model)));
        }
Exemple #18
0
        public async Task <IActionResult> GetPersonnelList(int linkId)
        {
            var link = await _departmentLinksService.GetLinkByIdAsync(linkId);

            if (link.DepartmentId != DepartmentId && link.LinkedDepartmentId != DepartmentId)
            {
                Unauthorized();
            }

            var department = await _departmentsService.GetDepartmentByIdAsync(link.DepartmentId);

            var allUsers = await _departmentsService.GetAllUsersForDepartmentAsync(link.DepartmentId);

            var lastUserActionlogs = await _actionLogsService.GetAllActionLogsForDepartmentAsync(link.DepartmentId);

            var departmentGroups = await _departmentGroupsService.GetAllGroupsForDepartmentAsync(link.DepartmentId);

            var lastUserStates = await _userStateService.GetLatestStatesForDepartmentAsync(link.DepartmentId);

            var personnelNames = await _departmentsService.GetAllPersonnelNamesForDepartmentAsync(link.DepartmentId);

            var calls = await _callsService.GetActiveCallsByDepartmentAsync(link.DepartmentId);

            var stations = await _departmentGroupsService.GetAllStationGroupsForDepartmentAsync(link.DepartmentId);

            var names = new Dictionary <string, string>();

            var userStates = new List <UserState>();

            foreach (var u in allUsers)
            {
                var state = lastUserStates.FirstOrDefault(x => x.UserId == u.UserId);

                if (state != null)
                {
                    userStates.Add(state);
                }
                else
                {
                    userStates.Add(await _userStateService.GetLastUserStateByUserIdAsync(u.UserId));
                }

                var name = personnelNames.FirstOrDefault(x => x.UserId == u.UserId);
                if (name != null)
                {
                    names.Add(u.UserId, name.Name);
                }
                else
                {
                    names.Add(u.UserId, await UserHelper.GetFullNameForUser(u.UserId));
                }
            }

            var personnelViewModels = new List <Models.BigBoardX.PersonnelViewModel>();

            var sortedUngroupedUsers = from u in allUsers
                                       // let mu = Membership.GetUser(u.UserId)
                                       //let userGroup = await _departmentGroupsService.GetGroupForUserAsync(u.UserId, DepartmentId)
                                       //let groupName = userGroup == null ? "" : userGroup.Name
                                       //let roles = await _personnelRolesService.GetRolesForUserAsync(u.UserId, DepartmentId)
                                       //let name = (ProfileBase.Create(mu.UserName, true)).GetPropertyValue("Name").ToString()
                                       let name = names[u.UserId]
                                                  let weight = lastUserActionlogs.Where(x => x.UserId == u.UserId).FirstOrDefault().GetWeightForAction()
                                                               orderby weight, name ascending
                select new
            {
                Name = name,
                User = u,
                //Group = userGroup,
                Roles = new List <PersonnelRole>()
            };



            foreach (var u in sortedUngroupedUsers)
            {
                //var mu = Membership.GetUser(u.User.UserId);
                var al = lastUserActionlogs.Where(x => x.UserId == u.User.UserId).FirstOrDefault();
                var us = userStates.Where(x => x.UserId == u.User.UserId).FirstOrDefault();
                u.Roles.AddRange(await _personnelRolesService.GetRolesForUserAsync(u.User.UserId, DepartmentId));
                var group = await _departmentGroupsService.GetGroupForUserAsync(u.User.UserId, DepartmentId);

                string callNumber = "";
                if (al != null && al.ActionTypeId == (int)ActionTypes.RespondingToScene || (al != null && al.DestinationType.HasValue && al.DestinationType.Value == 2))
                {
                    if (al.DestinationId.HasValue)
                    {
                        var call = calls.FirstOrDefault(x => x.CallId == al.DestinationId.Value);

                        if (call != null)
                        {
                            callNumber = call.Number;
                        }
                    }
                }
                var respondingToDepartment = stations.Where(s => al != null && s.DepartmentGroupId == al.DestinationId).FirstOrDefault();
                var personnelViewModel     = await Models.BigBoardX.PersonnelViewModel.Create(u.Name, al, us, department, respondingToDepartment, group, u.Roles, callNumber);

                personnelViewModels.Add(personnelViewModel);
            }

            return(Json(personnelViewModels));
        }