示例#1
0
        public async Task <IActionResult> Dashboard(bool firstRun = false)
        {
            var model = new DashboardModel();

            var staffingLevel = await _userStateService.GetLastUserStateByUserIdAsync(UserId);

            model.UserState = staffingLevel.State;
            model.StateNote = staffingLevel.Note;

            var staffingLevels = await _customStateService.GetActiveStaffingLevelsForDepartmentAsync(DepartmentId);

            if (staffingLevels == null)
            {
                model.UserStateTypes   = model.UserStateEnum.ToSelectList();
                ViewBag.UserStateTypes = model.UserStateEnum.ToSelectList();
            }
            else
            {
                model.CustomStaffingActive = true;
                var selected = staffingLevels.Details.FirstOrDefault(x => x.CustomStateDetailId == staffingLevel.State);
                model.UserStateTypes   = new SelectList(staffingLevels.GetActiveDetails(), "CustomStateDetailId", "ButtonText", selected);
                ViewBag.UserStateTypes = new SelectList(staffingLevels.GetActiveDetails(), "CustomStateDetailId", "ButtonText", selected);
            }

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

            model.FirstRun = firstRun;
            model.Number   = await _departmentSettingsService.GetTextToCallNumberForDepartmentAsync(DepartmentId);

            model.States = await _customStateService.GetActivePersonnelStateForDepartmentAsync(DepartmentId);

            return(View(model));
        }
示例#2
0
        public async Task <ActionResult <StatusResult> > GetCurrentUserStatus()
        {
            var action = await _actionLogsService.GetLastActionLogForUserAsync(UserId, DepartmentId);

            var userState = await _userStateService.GetLastUserStateByUserIdAsync(UserId);

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

            var statusResult = new StatusResult
            {
                Act = (int)ActionTypes.StandingBy,
                Uid = UserId.ToString(),
                Ste = userState.State,
                Sts = userState.Timestamp.TimeConverter(department)
            };

            if (action == null)
            {
                statusResult.Ats = DateTime.UtcNow.TimeConverter(department);
            }
            else
            {
                statusResult.Act = action.ActionTypeId;
                statusResult.Ats = action.Timestamp.TimeConverter(department);

                if (action.DestinationId.HasValue)
                {
                    if (action.ActionTypeId == (int)ActionTypes.RespondingToScene)
                    {
                        statusResult.Did = action.DestinationId.Value;
                    }
                    else if (action.ActionTypeId == (int)ActionTypes.RespondingToStation)
                    {
                        statusResult.Did = action.DestinationId.Value;
                    }
                    else if (action.ActionTypeId == (int)ActionTypes.AvailableStation)
                    {
                        statusResult.Did = action.DestinationId.Value;
                    }
                }
            }

            return(Ok(statusResult));
        }
示例#3
0
        public async Task <ActionResult <StaffingResult> > GetCurrentStaffing()
        {
            var profile = await _userProfileService.GetProfileByUserIdAsync(UserId);

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

            var userState = await _userStateService.GetLastUserStateByUserIdAsync(UserId);

            var result = new StaffingResult
            {
                Uid = UserId.ToString(),
                Nme = profile.FullName.AsFirstNameLastName,
                Typ = userState.State,
                Tms = userState.Timestamp.TimeConverter(await _departmentsService.GetDepartmentByIdAsync(DepartmentId, false)),
                Not = userState.Note
            };

            return(Ok(result));
        }
示例#4
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")));
        }
示例#5
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);
        }
示例#6
0
        public async Task <ActionResult <PersonnelInfoResult> > GetPersonnelInfo(string userId)
        {
            var result = new PersonnelInfoResult();
            var user   = _usersService.GetUserById(userId);


            if (user == null)
            {
                return(NotFound());
            }

            var department = await _departmentsService.GetDepartmentByUserIdAsync(user.UserId);

            if (department == null)
            {
                return(NotFound());
            }

            if (department.DepartmentId != DepartmentId)
            {
                return(Unauthorized());
            }

            var profile = await _userProfileService.GetProfileByUserIdAsync(user.UserId);

            var group = await _departmentGroupsService.GetGroupForUserAsync(user.UserId, DepartmentId);

            var roles = await _personnelRolesService.GetRolesForUserAsync(user.UserId, DepartmentId);

            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 = department.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)
                {
                    result.Roles.Add(role.Name);
                }
            }

            var action = await _actionLogsService.GetLastActionLogForUserAsync(user.UserId, DepartmentId);

            var userState = await _userStateService.GetLastUserStateByUserIdAsync(user.UserId);

            result.Ats = (int)ActionTypes.StandingBy;
            result.Stf = userState.State;
            result.Stm = userState.Timestamp.TimeConverter(department);

            if (action == null)
            {
                result.Stm = DateTime.UtcNow.TimeConverter(department);
            }
            else
            {
                result.Ats = action.ActionTypeId;
                result.Atm = action.Timestamp.TimeConverter(department);

                if (action.DestinationId.HasValue)
                {
                    if (action.ActionTypeId == (int)ActionTypes.RespondingToScene)
                    {
                        result.Did = action.DestinationId.Value;
                    }
                    else if (action.ActionTypeId == (int)ActionTypes.RespondingToStation)
                    {
                        result.Did = action.DestinationId.Value;
                    }
                    else if (action.ActionTypeId == (int)ActionTypes.AvailableStation)
                    {
                        result.Did = action.DestinationId.Value;
                    }
                }
            }

            return(Ok(result));
        }
示例#7
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));
        }