Пример #1
0
        /// <summary>
        /// Maks a listusermodel object from a user profile object
        /// </summary>
        /// <param name="userProfile"></param>
        /// <param name="currentCity"></param>
        /// <returns></returns>
        private ListUserModel MakeListUserModel(UserProfile userProfile, PemsCity currentCity)
        {
            var userModel = new ListUserModel
            {
                CreationDate  = userProfile.CreatedDate,
                FirstName     = userProfile.FirstName,
                LastLoginDate = GetLastLoginTime(userProfile.UserId),
                LastName      = userProfile.LastName,
                MiddleInitial = userProfile.MiddleName,
                Username      = userProfile.UserName,
                UserId        = userProfile.UserId,
                Active        = false,
                BadLoginCount = 0
            };

            //update memebership information
            if (userProfile.Membership != null)
            {
                userModel.Active        = userProfile.Membership.IsActive.HasValue && userProfile.Membership.IsActive.Value;
                userModel.BadLoginCount = userProfile.Membership.PasswordFailuresSinceLastSuccess;
            }
            //role
            userModel.Role = SecurityMgr.GetGroupForUser(currentCity, userModel.Username);

            //status
            userModel.Status = GetStatus(userModel.Active, userModel.Username);



            return(userModel);
        }
Пример #2
0
        private void AddTechnicianToMaintenanceGroup(UserModel userModel, PemsCity mainGroup, int userId)
        {
            //make sure the user has access to the maintenance group. Add them as a _maint mmeber and to the caching table
            (new UserCustomerAccessManager()).AddCustomerAccess(userId, mainGroup.Id);
            var mgAuthMgr = new AuthorizationManager(mainGroup.InternalName);

            mgAuthMgr.AddGroupMember(Constants.Security.DefaultMaintenanceGroupName, userModel.Username);

            //add them to all discinct pems conn strings
            foreach (
                var maintCustomer in
                mainGroup.MaintenanceCustomers)
            {
                var maintCustomerPemsConnString = maintCustomer.PemsConnectionStringName;

                //create the technician. only do this if they dont exist already, otherwise update
                using (var pemsEntities = new PEMEntities(maintCustomerPemsConnString))
                {
                    SetMaintenanceGroupTechnician(userModel, pemsEntities, userId);
                    //add user to _maintenance group here for the specific customer
                    var authorizationManager = new AuthorizationManager(maintCustomer.InternalName);
                    authorizationManager.AddGroupMember(Constants.Security.DefaultMaintenanceGroupName, userModel.Username);

                    //now add them to caching table for this customer
                    //not sure if we need this or not

                    (new UserCustomerAccessManager()).AddCustomerAccess(userId, maintCustomer.Id);
                }
            }
        }
        public MaintenanceGroupCustomersModel GetMaintenanceGroupCustomersModel(int maintGroupId)
        {
            var model = new MaintenanceGroupCustomersModel {
                CustomerId = maintGroupId
            };
            var mainGroup = RbacEntities.CustomerProfiles.SingleOrDefault(m => m.CustomerId == maintGroupId);

            if (mainGroup != null)
            {
                //get assigned customers: the pems city based on the maintGroupId passed it, it will build all the customers

                var mainGroupCity = new PemsCity(maintGroupId.ToString());
                model.Customers = mainGroupCity.MaintenanceCustomers.Select(x => new MaintenanceGroupCustomerModel {
                    Id = x.Id, DisplayName = x.DisplayName, NewCustomer = false
                }).ToList();

                //get possible customers: add the default item as well
                model.AvailableCustomers = new List <SelectListItem>
                {
                    new SelectListItem {
                        Text = ResourceTypes.DropDownDefault, Value = "-1"
                    }
                };

                //go grab all the customers
                model.AvailableCustomers.AddRange(GetMaintenanceCustomerListItems(maintGroupId));

                GetCustomerBaseModel(maintGroupId, model);
                model.Status      = GetCustomerStatusModel(maintGroupId);
                model.DisplayName = mainGroup.DisplayName;
            }

            return(model);
        }
Пример #4
0
 /// <summary>
 /// Sets the user to a technican if they havent done so already. This is only a set, never a remove, since this will break existing data
 /// This forces a user to use  a specific connection string, so when we are looping through customers and adding the tech to all pems DBs, they will be persisted to all pems dbs.
 /// //individual customers will just use the otheer non connection string specific method (so it used the pemsentities from teh constructor) so their db context stays up to date (when adding users, etc)
 /// </summary>
 /// <param name="userModel"></param>
 /// <param name="currentCity">pems city that holds all of the maintenance customers. used mostly by passing in the currentcity set on the framework.</param>
 public void SetTechnician(UserModel userModel, PemsCity currentCity = null)
 {
     //if they are
     if (userModel.IsTechnician)
     {
         int userId = (new UserFactory()).GetUserId(userModel.Username);
         //loop through each mg customer and add the technian
         if (currentCity != null && currentCity.CustomerType == CustomerProfileType.MaintenanceGroup)
         {
             AddTechnicianToMaintenanceGroup(userModel, currentCity, userId);
         }
         //if they are a customer and being set as a technician, this means that the customer is part of a maintenance group (otherwise the check box wont show up)
         //find the maint group and add the tech to that maint gorup (and all of its customers)
         else
         {
             //go find the maint group
             var existingMGCustomer = RbacEntities.MaintenanceGroupCustomers.FirstOrDefault(x => x.CustomerId == currentCity.Id);
             if (existingMGCustomer != null)
             {
                 var maintGroup = new PemsCity(existingMGCustomer.MaintenanceGroupId.ToString());
                 AddTechnicianToMaintenanceGroup(userModel, maintGroup, userId);
             }
         }
     }
 }
Пример #5
0
        /// <summary>
        /// Gets a list of all user models in the system
        /// </summary>
        /// <returns></returns>
        public List <ListUserModel> GetUsersListModels(PemsCity currentCity)
        {
            //create a list of user models for the city passed in
            var userNamesForThisCity = SecurityMgr.GetUsersForCity(currentCity.InternalName);
            var userProfiles         = RbacEntities.UserProfiles.Where(x => userNamesForThisCity.Contains(x.UserName)).ToList();

            return(userProfiles.Select(x => MakeListUserModel(x, currentCity)).ToList());
        }
Пример #6
0
        /// <summary>
        /// Gets all of the possible asset tyeps for all customers in the current maintenance group
        /// </summary>
        /// <returns></returns>
        public JsonResult GetAssetTypes()
        {
            //get all of the unique asset types for each customer in the maintenance group
            //get the maintenance group
            var maintGroup = new PemsCity(Session[Constants.ViewData.CurrentCityId].ToString());
            var items      = (new DispatcherWorkOrderFactory(maintGroup)).GetWorkOrderAssetTypes();

            return(Json(items, JsonRequestBehavior.AllowGet));
        }
Пример #7
0
        /// <summary>
        /// Gets a check box list of groups for a user and city. Used for the user models
        /// </summary>
        public List <CheckBoxItem> GetGroups(string username, PemsCity currentCity)
        {
            var _secMgr    = new SecurityManager();
            var cityGroups = _secMgr.GetGroupsForUser(currentCity, username);

            //Add data in SelectList List
            return(cityGroups.Select(item => new CheckBoxItem {
                Text = item.Key, Selected = item.Value, Value = item.Key
            }).ToList());
        }
Пример #8
0
        /// <summary>
        /// Gets a work order ID for this asset. IF one does not exist, it will create it instead.
        /// </summary>
        /// <param name="activeAlarmResponse"></param>
        /// <returns></returns>
        private string GetWorkOrderId(DataResponseActiveAlarmsActiveAlarm activeAlarmResponse)
        {
            const int defaultValue = -1;
            //first, parse the ids
            int customeId   = int.TryParse(activeAlarmResponse.cid, out customeId) ? customeId : defaultValue;
            int meterId     = int.TryParse(activeAlarmResponse.mid, out meterId) ? meterId : defaultValue;
            int areaId      = int.TryParse(activeAlarmResponse.aid, out areaId) ? areaId : defaultValue;
            int eventSource = int.TryParse(activeAlarmResponse.EventSource, out eventSource)
                                  ? eventSource
                                  : defaultValue;
            int  eventCode   = int.TryParse(activeAlarmResponse.EventCode, out eventCode) ? eventCode : defaultValue;
            long eventUID    = long.TryParse(activeAlarmResponse.EventUID, out eventUID) ? eventUID : defaultValue;
            long workOrderId = defaultValue;

            //check ot make sure all the ids were parsed correctly
            if (customeId > defaultValue && meterId > defaultValue && areaId > defaultValue &&
                eventCode > defaultValue && eventSource > defaultValue && eventUID > defaultValue)
            {
                var currentCustomer = new PemsCity(customeId.ToString());
                //go get the customer so we can get the correct connection string
                using (
                    var maintenanceEntities = new MaintenanceEntities(currentCustomer.MaintenanceConnectionStringName))
                {
                    //first we have to go to PEMS db to get the asset
                    //return nothing if the asset doesnt exist.
                    var assetFactory = (new AssetFactory(currentCustomer.PemsConnectionStringName));
                    var asset        = assetFactory.GetAsset(customeId, areaId, meterId);
                    //fail state - work order or work orde3r event will not be created
                    if (asset == null)
                    {
                        return(string.Empty);
                    }

                    //now create the work order/ or get the exisitng one
                    var fmWorkOrder = CreateWorkOrder(activeAlarmResponse, areaId, currentCustomer, customeId, asset,
                                                      meterId, maintenanceEntities);
                    workOrderId = fmWorkOrder.WorkOrderId;

                    //now that we have our work order id (exisitng or new), we haev to create the event for this work order.
                    //first, we have to get the vlaues we need ot create an event (tier, etc)
                    //get event code

                    CreateWorkOrderEvent(activeAlarmResponse, currentCustomer, customeId, eventSource, eventCode,
                                         eventUID, workOrderId, maintenanceEntities);

                    //every time a event is created, resolved , etc, we have to update the sladue and highest severity, so lets do that now
                    var mobileWorkOrderFactory =
                        (new TechnicianWorkOrderFactory(currentCustomer.MaintenanceConnectionStringName,
                                                        currentCustomer.PemsConnectionStringName));
                    mobileWorkOrderFactory.UpdateEventAggregateInfo(workOrderId);
                    return(workOrderId.ToString());
                }
            }
            return(string.Empty);
        }
Пример #9
0
        /// <summary>
        /// Creates a work order in the system
        /// </summary>
        /// <param name="activeAlarmResponse"></param>
        /// <param name="areaId"></param>
        /// <param name="currentCustomer"></param>
        /// <param name="customeId"></param>
        /// <param name="asset"></param>
        /// <param name="meterId"></param>
        /// <param name="maintenanceEntities"></param>
        /// <returns></returns>
        private static FMWorkOrder CreateWorkOrder(DataResponseActiveAlarmsActiveAlarm activeAlarmResponse, int areaId,
                                                   PemsCity currentCustomer, int customeId, Meter asset, int meterId,
                                                   MaintenanceEntities maintenanceEntities)
        {
            //we have to check to see if htey asset already has a work order. if it does, use that work order. This includes any open, incomplete or rejected work orders.
            //we add it to any open work order, even if it is assigned ot another technician (in practice this will almost never happen)
            var existingWorkOrder =
                maintenanceEntities.FMWorkOrders.FirstOrDefault(
                    x =>
                    x.MeterId == meterId && x.CustomerId == customeId && x.AreaId == areaId &&
                    (x.WorkOrderStatusId == (int)WorkOrderStatus.Open ||
                     x.WorkOrderStatusId == (int)WorkOrderStatus.Incomplete ||
                     x.WorkOrderStatusId == (int)WorkOrderStatus.Rejected));

            if (existingWorkOrder != null)
            {
                return(existingWorkOrder);
            }


            //we need to crate a new work order
            //create the work order now. commented out properties we ignore upon creation.
            var fmWorkOrder = new FMWorkOrder
            {
                AreaId            = areaId,
                CreateDateTime    = currentCustomer.LocalTime,
                CustomerId        = customeId, //cid
                HighestSeverity   = 0,
                Location          = asset.Location,
                Mechanism         = asset.MeterType,
                MeterGroup        = asset.MeterGroup ?? 1,
                MeterId           = meterId,
                Notes             = string.Empty,
                SLADue            = activeAlarmResponse.SLADue, //this gets reset anyways, jsut set it to
                WorkOrderStatusId = (int)WorkOrderStatus.Open,
                AssignmentState   = (int)AssignmentState.Unassigned,
                ZoneId            =
                    asset.MeterMaps.FirstOrDefault() != null?asset.MeterMaps.FirstOrDefault().ZoneId : (int?)null
            };

            maintenanceEntities.FMWorkOrders.Add(fmWorkOrder);
            maintenanceEntities.SaveChanges();

            //every time a event is created, resolved , etc, we have to update the sladue and highest severity, so lets do that now
            var mobileWorkOrderFactory =
                (new TechnicianWorkOrderFactory(currentCustomer.MaintenanceConnectionStringName,
                                                currentCustomer.PemsConnectionStringName));

            mobileWorkOrderFactory.UpdateEventAggregateInfo(fmWorkOrder.WorkOrderId);
            return(fmWorkOrder);
        }
Пример #10
0
        public Dictionary <string, bool> GetGroupsForUser(PemsCity city, string username, bool includeDefaultGroups = false)
        {
            //get all the groups
            var groups = _azManager.GetStoreGroupsForUser(city.InternalName, username);

            //include the default group
            if (includeDefaultGroups)
            {
                return(groups);
            }

            //remove the default group
            return(groups.Where(x => !x.Key.StartsWith(Constants.Security.DefaultGroupNamePrefix)).ToDictionary(x => x.Key, x => x.Value));
        }
Пример #11
0
        /// <summary>
        /// Gets a list of SelectListItems of roles for the customer ID passed in.
        /// </summary>
        public List <SelectListItem> GetRoleListItems(string customerId)
        {
            var items       = new List <SelectListItem>();
            var secMgr      = new SecurityManager();
            var city        = new PemsCity(customerId);
            var clientRoles = secMgr.GetGroups(city, false);

            items.AddRange(clientRoles.Select(clientRole => new SelectListItem
            {
                Text  = clientRole.Key,
                Value = clientRole.Value.ToString()
            }));
            return(items);
        }
Пример #12
0
        /// <summary>
        /// Gets a check box list of groups for a city. Used for the user models
        /// </summary>
        public List <CheckBoxItem> GetGroups(PemsCity currentCity)
        {
            var secMgr       = new SecurityManager();
            var cityGroups   = secMgr.GetGroups(currentCity);
            var checkBoxList = new List <CheckBoxItem>();

            //Add data in SelectList List
            foreach (var item in cityGroups)
            {
                var chk = new CheckBoxItem {
                    Text = item.Key, Selected = false, Value = item.Key
                };
                checkBoxList.Add(chk);
            }
            return(checkBoxList);
        }
Пример #13
0
        /// <summary>
        /// Creates a work order event if we need to.
        /// </summary>
        /// <param name="activeAlarmResponse"></param>
        /// <param name="currentCustomer"></param>
        /// <param name="customeId"></param>
        /// <param name="eventSource"></param>
        /// <param name="eventCode"></param>
        /// <param name="eventUID"></param>
        /// <param name="workOrderId"></param>
        /// <param name="maintenanceEntities"></param>
        private void CreateWorkOrderEvent(DataResponseActiveAlarmsActiveAlarm activeAlarmResponse,
                                          PemsCity currentCustomer,
                                          int customeId, int eventSource, int eventCode, long eventUID, long workOrderId,
                                          MaintenanceEntities maintenanceEntities)
        {
            //check to see if we need to crate the event first. the PK for it is workorderid, eventid, eventcode
            var existingWorkOrderEvent =
                maintenanceEntities.FMWorkOrderEvents.FirstOrDefault(
                    x =>
                    x.WorkOrderId == workOrderId && x.EventId == eventUID && x.EventCode == eventCode &&
                    x.Status == (int)WorkOrderEventStatus.Open);

            if (existingWorkOrderEvent != null)
            {
                return;
            }

            //if we got here, we have to creat the event.
            using (var pemsEntities = new PEMEntities(currentCustomer.PemsConnectionStringName))
            {
                var ec =
                    pemsEntities.EventCodes.FirstOrDefault(
                        x => x.CustomerID == customeId && x.EventSource == eventSource && x.EventCode1 == eventCode);
                if (ec != null)
                {
                    //we found the event code, continue. .
                    var fmWorkOrderEvent = new FMWorkOrderEvent();
                    fmWorkOrderEvent.AlarmTier     = ec.AlarmTier; // alarm tier of the event code
                    fmWorkOrderEvent.Automated     = true;
                    fmWorkOrderEvent.EventCode     = eventCode;
                    fmWorkOrderEvent.EventDateTime = activeAlarmResponse.TimeOfOccurrance;
                    fmWorkOrderEvent.EventDesc     = ec.EventDescVerbose;
                    fmWorkOrderEvent.EventId       = eventUID;
                    fmWorkOrderEvent.Notes         = activeAlarmResponse.Notes;
                    fmWorkOrderEvent.SLADue        = activeAlarmResponse.SLADue;
                    fmWorkOrderEvent.Status        = (int)WorkOrderEventStatus.Open;
                    fmWorkOrderEvent.Vandalism     = false;
                    fmWorkOrderEvent.WorkOrderId   = workOrderId;

                    maintenanceEntities.FMWorkOrderEvents.Add(fmWorkOrderEvent);
                    maintenanceEntities.SaveChanges();
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Adds an admin to the maintenance group. This DOES NOT create a technician out of the administrator
        /// this just gives the admin user access to the MG and its customers.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="mainGroup"></param>
        /// <param name="userId"></param>
        public void AddAdminTechnicianToMaintenanceGroup(string username, PemsCity mainGroup, int userId)
        {
            //make sure the user has access to the maintenance group. Add them as a _maint mmeber and to the caching table
            (new UserCustomerAccessManager()).AddCustomerAccess(userId, mainGroup.Id);

            var mgAuthMgr = new AuthorizationManager(mainGroup.InternalName);

            mgAuthMgr.AddGroupMember(Constants.Security.DefaultMaintenanceGroupName, username);
            //add them to all discinct pems conn strings
            foreach (var maintCustomer in mainGroup.MaintenanceCustomers)
            {
                //create the technician. only do this if they dont exist already, otherwise update
                //add user to _maintenance group here for the specific customer
                var authorizationManager = new AuthorizationManager(maintCustomer.InternalName);
                authorizationManager.AddGroupMember(Constants.Security.DefaultMaintenanceGroupName, username);
                //now add them to caching table for this customer
                (new UserCustomerAccessManager()).AddCustomerAccess(userId, maintCustomer.Id);
            }
        }
Пример #15
0
        /// <summary>
        /// Sets the current properties for city, controller and action based on the URL data coming in.
        /// </summary>
        private void SetProperties(ActionExecutingContext filterContext)
        {
            if (filterContext.RouteData.Values.ContainsKey("city"))
            {
                CurrentCity = new PemsCity(filterContext.RouteData.Values["city"].ToString());

                // Make sure CurrentCity points to a valid city/customer.
                if (CurrentCity.IsValid)
                {
                    // Populate our static CustomerId
                    //  SqlResourceHelper.CustomerId = CurrentCity.Id;
                }
                else
                {
                    CurrentCity = null;
                }
            }
            if (filterContext.RouteData.Values.ContainsKey("controller"))
            {
                CurrentController = filterContext.RouteData.Values["controller"].ToString();
            }

            if (filterContext.RouteData.Values.ContainsKey("action"))
            {
                CurrentAction = filterContext.RouteData.Values["action"].ToString();
            }

            if (filterContext.Controller.ControllerContext.RequestContext.RouteData.DataTokens.ContainsKey("area"))
            {
                CurrentArea = filterContext.Controller.ControllerContext.RequestContext.RouteData.DataTokens["area"].ToString();
            }

            CurrentAuthorizationManager = CurrentCity != null ? new AuthorizationManager(CurrentCity) : null;

            //
            filterContext.Controller.ViewData[Constants.ViewData.CurrentCity] = CurrentCity == null ? "-" : CurrentCity.DisplayName;
            filterContext.Controller.ViewData[Constants.ViewData.CurrentUser] = User.Identity.Name;
        }
        /// <summary>
        /// Gets a list of unique technicians for all the customers for a specific maintenance group.
        /// Filters by cutomer access as well.
        /// </summary>
        /// <param name="maintGroup"></param>
        /// <returns></returns>
        public List <Technician> GetMaintenanceGroupTechnicians(PemsCity maintGroup)
        {
            var allTechs   = new List <Technician>();
            var ucaManager = new UserCustomerAccessManager();

            foreach (var maintenanceCustomer in maintGroup.MaintenanceCustomers)
            {
                var allTechsForCustomer =
                    (new DispatcherWorkOrderFactory(maintenanceCustomer.PemsConnectionStringName,
                                                    maintGroup.MaintenanceConnectionStringName)).MakeAvailableTechnicians();
                foreach (var techForCustomer in allTechsForCustomer)
                {
                    if (allTechs.All(x => x.TechnicianID != techForCustomer.TechnicianID))
                    {
                        allTechs.Add(techForCustomer);
                    }
                }
            }

            //now that we have all the unique technicians for all the maintneannce customers,
            //we need to make sure they have access (since the techdetails brought back is for the data source and is not customer specific.
            //we do this by checking the UserCustomerAccess table
            //call the GetCustomersIds method and check to see if they have access to the maintenancecustomers for this maintneance group.
            var filteredTechsWithAccess = new List <Technician>();
            var maintCustomerIds        = maintGroup.MaintenanceCustomers.Select(x => x.Id).ToList();

            //assuming there is only unique techs in this list
            foreach (var technician in allTechs)
            {
                var  customerIds = ucaManager.GetCustomersIds(technician.TechnicianID);
                bool hasMatch    = customerIds.Any(x => maintCustomerIds.Any(y => y == x));
                if (hasMatch)
                {
                    filteredTechsWithAccess.Add(technician);
                }
            }
            return(filteredTechsWithAccess);
        }
Пример #17
0
        private string ClearAlarm(DataRequestHistoricalAlarm historicAlarmRequest)
        {
            //clear the work order event

            const int defaultValue = -1;
            //first, parse the ids
            int customeId   = int.TryParse(historicAlarmRequest.cid, out customeId) ? customeId : defaultValue;
            int meterId     = int.TryParse(historicAlarmRequest.mid, out meterId) ? meterId : defaultValue;
            int areaId      = int.TryParse(historicAlarmRequest.aid, out areaId) ? areaId : defaultValue;
            int eventSource = int.TryParse(historicAlarmRequest.EventSource, out eventSource)
                                  ? eventSource
                                  : defaultValue;
            int  eventCode   = int.TryParse(historicAlarmRequest.EventCode, out eventCode) ? eventCode : defaultValue;
            long eventUID    = long.TryParse(historicAlarmRequest.EventUID, out eventUID) ? eventUID : defaultValue;
            int  workOrderId = int.TryParse(historicAlarmRequest.WorkOrderId, out workOrderId)
                                  ? workOrderId
                                  : defaultValue;


            //check ot make sure all the ids were parsed correctly
            if (customeId > defaultValue && meterId > defaultValue && areaId > defaultValue &&
                eventCode > defaultValue && eventSource > defaultValue && eventUID > defaultValue &&
                workOrderId > defaultValue)
            {
                var currentCustomer = new PemsCity(customeId.ToString());
                //go get the customer so we can get the correct connection string
                using (
                    var maintenanceEntities = new MaintenanceEntities(currentCustomer.MaintenanceConnectionStringName))
                {
                    //first we have to go to PEMS db to get the asset
                    //return nothing if the asset doesnt exist.
                    var assetFactory = (new AssetFactory(currentCustomer.PemsConnectionStringName));
                    var asset        = assetFactory.GetAsset(customeId, areaId, meterId);
                    //fail state - work order or work order event will not be closed
                    if (asset == null)
                    {
                        return(((int)WorkOrderEventStatus.Open).ToString());
                    }

                    //close out the work order event
                    //go get the event
                    //check to see if the event exist first
                    var existingWorkOrderEvent =
                        maintenanceEntities.FMWorkOrderEvents.FirstOrDefault(
                            x => x.WorkOrderId == workOrderId && x.EventId == eventUID && x.EventCode == eventCode);
                    //if it doesnt exist, cant close it, just return closed
                    if (existingWorkOrderEvent == null)
                    {
                        return(((int)WorkOrderEventStatus.Closed).ToString());
                    }

                    //clear the event
                    existingWorkOrderEvent.Status = (int)WorkOrderEventStatus.Closed;
                    maintenanceEntities.SaveChanges();

                    //every time a event is created, resolved , etc, we have to update the sladue and highest severity, so lets do that now
                    var mobileWorkOrderFactory =
                        (new TechnicianWorkOrderFactory(currentCustomer.MaintenanceConnectionStringName,
                                                        currentCustomer.PemsConnectionStringName));
                    mobileWorkOrderFactory.UpdateEventAggregateInfo(workOrderId);

                    //then clear the work order (if its the last event that was open was just closed)
                    CloseWorkOrder(maintenanceEntities, workOrderId, currentCustomer.LocalTime);
                    return(((int)WorkOrderEventStatus.Closed).ToString());
                }
            }
            //cant find the itme the request was referencing, return closed.
            //return WorkOrderEventStatus enum representing if it were closed or not.
            return(((int)WorkOrderEventStatus.Closed).ToString());
        }
        public void SetMaintenanceGroupCustomersModel(int maintGroupId, MaintenanceGroupCustomersModel model)
        {
            // Save any new areas.
            if (model.NewCustomers != null)
            {
                var maintGroup = new PemsCity(maintGroupId.ToString());

                foreach (var newCustomerId in model.NewCustomers)
                {
                    //try to parse the id to make sure it came though correctly
                    int newCustID;
                    var parsed = int.TryParse(newCustomerId, out newCustID);

                    if (parsed)
                    {
                        //now lets check to see if this customer is in the system
                        var existingCustomer = RbacEntities.CustomerProfiles.FirstOrDefault(x => x.CustomerId == newCustID);
                        if (existingCustomer != null)
                        {
                            //only do it if it doesnt exist there already
                            var existing = RbacEntities.MaintenanceGroupCustomers.FirstOrDefault(x => x.MaintenanceGroupId == maintGroupId && x.CustomerId == newCustID);
                            if (existing != null)
                            {
                                continue;
                            }
                            RbacEntities.MaintenanceGroupCustomers.Add(new MaintenanceGroupCustomer
                            {
                                MaintenanceGroupId = maintGroupId,
                                CustomerId         = newCustID
                            });
                            RbacEntities.SaveChanges();

                            //roll thorugh all the ussers for the maint group and if htey are a technician, add them to the _main group for the customer.
                            //This way they will not be member, but will be part of a role so they have access log in to the maint for that cuity

                            //we do not need to roll thorugh the users for the customers, since they are not allowed to assign technicians until they are part of the maintenance group
                            //this means that the customer will not have any technicians, so we do not need to worry about adding those users as techs for the maint group,
                            //that will be done when the user is checked as a tech after the customer is assigned to the maint group.
                            //now add all of the users for this maintenance group that are technicians to the _maintenance role for the customer.

                            //we are also only doing this for new customers.

                            //get all the users for the maintenance group
                            var mainGroupMembersUsernames = (new SecurityManager()).GetUsersForCity(maintGroup.InternalName);

                            //get the customer and an auth manager for that customer
                            var customer             = new PemsCity(existingCustomer.CustomerId.ToString());
                            var authorizationManager = new AuthorizationManager(customer);

                            //check to see if they are a technician
                            foreach (var mainGroupMembersUsername in mainGroupMembersUsernames)
                            {
                                if (TechnicianFactory.IsUserTechnician(mainGroupMembersUsername))
                                {
                                    //if they are, add them to the _maint role for the customer
                                    authorizationManager.AddGroupMember(Constants.Security.DefaultMaintenanceGroupName,
                                                                        mainGroupMembersUsername);

                                    //go get the userid from the name
                                    var userId = (new UserFactory()).GetUserId(mainGroupMembersUsername);

                                    //we also need to update the caching table to give the technician access to see the site
                                    (new UserCustomerAccessManager()).AddCustomerAccess(userId, maintGroupId);
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #19
0
        /// <summary>
        /// Gets a users profile
        /// </summary>
        public ProfileModel GetProfileModel(string username, PemsCity CurrentCity)
        {
            //populate the fields from the database
            var profile = RbacEntities.UserProfiles.FirstOrDefault(u => u.UserName == username);

            if (profile != null)
            {
                var model = new ProfileModel
                {
                    Groups        = (new RoleFactory()).GetGroups(username, CurrentCity),
                    Username      = username,
                    EmailAddress  = profile.Email,
                    MiddleInitial = profile.MiddleName,
                    FirstName     = profile.FirstName,
                    LastName      = profile.LastName,
                    PhoneNumber   = profile.Phone,
                    Active        = false
                };

                //update memebership information
                if (profile.Membership != null)
                {
                    model.Active                 = profile.Membership.IsActive.HasValue && profile.Membership.IsActive.Value;
                    model.BadLoginCount          = profile.Membership.PasswordFailuresSinceLastSuccess;
                    model.CreationDate           = profile.Membership.CreateDate.HasValue ? profile.Membership.CreateDate.Value : DateTime.MinValue;
                    model.LastLoginFailure       = profile.Membership.LastPasswordFailureDate.HasValue ? profile.Membership.LastPasswordFailureDate.Value : DateTime.MinValue;
                    model.LastPasswordChangeDate = profile.Membership.PasswordChangedDate.HasValue ? profile.Membership.PasswordChangedDate.Value : DateTime.MinValue;
                    int daysPwValidFor;
                    var validForConfig = ConfigurationManager.AppSettings["DaysPWValidFor"];
                    int.TryParse(validForConfig, out daysPwValidFor);
                    if (daysPwValidFor == 0)
                    {
                        daysPwValidFor = 90;
                    }
                    model.PasswordExipration = profile.Membership.PasswordChangedDate != null?profile.Membership.PasswordChangedDate.Value.AddDays(daysPwValidFor) : DateTime.Now;
                }
                //role
                model.Role = SecurityMgr.GetGroupForUser(CurrentCity, model.Username);

                //status
                model.Status = GetStatus(model.Active, model.Username);

                //user settings
                var settingsFactory = new SettingsFactory();

                var lastLogin = settingsFactory.GetValue(profile.UserId, Constants.User.LastLoginTime);
                model.LastLoginDate = lastLogin != null?Convert.ToDateTime(lastLogin) : DateTime.MinValue;

                var orgName = settingsFactory.GetValue(profile.UserId, Constants.User.OrganizaitonNameField);
                model.OrganizationName = orgName ?? string.Empty;

                var secType = settingsFactory.GetValue(profile.UserId, Constants.User.SecondaryIDType);
                model.SecondaryIDType = secType ?? string.Empty;

                var secValue = settingsFactory.GetValue(profile.UserId, Constants.User.SecondaryIDValue);
                model.SecondaryIDValue = secValue ?? string.Empty;

                //is technician
                var isTech = settingsFactory.GetValue(profile.UserId, Constants.User.IsTechnician);
                model.IsTechnician = isTech != null && Convert.ToBoolean(isTech);

                //var techID = settingsFactory.GetValue(profile.UserId, Constants.User.TechnicianId);
                //model.TechnicianId = techID != null ? Convert.ToInt32(techID) : -1;

                //then fill in all the profile specific stuff
                var passwordManager = new PasswordManager(username);
                model.PasswordResetRequired = RequiresPasswordReset(username);

                List <PasswordQuestion> questions = passwordManager.GetQuestions();
                model.Question1 = questions.Count > 0 ? questions[0] : new PasswordQuestion(1);
                model.Question2 = questions.Count > 1 ? questions[1] : new PasswordQuestion(2);

                // Set in a dummy password
                model.Password = new ChangePasswordModel();

                return(model);
            }

            return(null);
        }
Пример #20
0
 public Dictionary <string, int> GetGroups(PemsCity city, bool includeDefaultGroups = false)
 {
     return(GetGroups(city.InternalName, includeDefaultGroups));
 }
Пример #21
0
        public bool CheckUserAccessForCity(string username, PemsCity city)
        {
            var cities = GetCitiesForUser(username);

            return(cities.Any(x => x.InternalName == city.InternalName));
        }
Пример #22
0
 public AuthorizationManager.AccessRights CheckAccess(PemsCity city, string controller, string action, string userName)
 {
     return(_azManager.CheckAccess(city, controller, action, userName));
 }
Пример #23
0
 public string GetGroupForUser(PemsCity city, string username)
 {
     //get all the groups
     return(_azManager.GetStoreGroupForUser(city.InternalName, username));
 }
 /// <summary>
 /// force this constructor, so they have to be working in the context of a specific city.
 ///  All work orders  should be city specific.
 /// this allows us to iterate through all the work orders for a entire group if we have to
 /// </summary>
 /// <param name="currentMaintenanceGroup"></param>
 public DispatcherWorkOrderFactory(PemsCity currentMaintenanceGroup)
 {
     MaintenanceGroup                = currentMaintenanceGroup;
     MaintenanceGroupCustomers       = currentMaintenanceGroup.MaintenanceCustomers;
     MaintenanceConnectionStringName = currentMaintenanceGroup.MaintenanceConnectionStringName;
 }
Пример #25
0
        public ActionResult CustomerRoles(string username)
        {
            //the first thing we have to do is check to see if this user is part of the current city. if it is not, send them back to the index page.
            var userFactory = new UserFactory();

            //now check to se if the requested user exist int he system
            if (!userFactory.DoesUserExist(username))
            {
                return(RedirectToAction("Index", "Users"));
            }

            //get the model
            var model = userFactory.GetProfileModel(username, CurrentCity);

            if (model == null)
            {
                return(RedirectToAction("Index", "Users"));
            }

            //now that we have the user prfile, lets build a list of customer role models that contain a list of customers that each have a list of roles
            var crm = new CustomerRoleModel {
                Username = model.Username, CustomerRoles = new List <CustomerRole>()
            };

            var secMgr        = new SecurityManager();
            var customerNames = secMgr.GetCities();

            foreach (var customerName in customerNames)
            {
                var pemCity = new PemsCity(customerName);
                if (pemCity.IsActive)
                {
                    //need to get the current role the user is assigned to for this city
                    var selectedGroupForCity = secMgr.GetGroupForUser(pemCity, model.Username);
                    if (selectedGroupForCity == "N/A")
                    {
                        selectedGroupForCity = "";
                    }
                    // var roles = secMgr.GetGroups(customerName);
                    var roles = new Dictionary <string, string> {
                        { (new ResourceFactory()).GetLocalizedTitle(ResourceTypes.DropDownDefault,
                                                                    "Select One"), "" }
                    };
                    //add the none option
                    var groups = secMgr.GetGroups(customerName);
                    foreach (var group in groups)
                    {
                        if (!roles.ContainsKey(group.Key))
                        {
                            roles.Add(group.Key, group.Key);
                        }
                    }
                    var custModel = new CustomerRole {
                        Customer = pemCity, Roles = roles, CurrentRole = selectedGroupForCity, CustomerInternalName = pemCity.InternalName
                    };
                    crm.CustomerRoles.Add(custModel);
                }
            }


            return(View(crm));
        }