public JsonResult AllEmployees(Request request)
 {
     return Json(GetEmployees(request, false), JsonRequestBehavior.AllowGet);
 }
        public JsonResult ManagersForEmployee(Request request)
        {
            //the request is a kendo one so uses its filters model - the value of the first filter should be the employeeID
            var employeeId = request.filter.filters[0].Value;

            //query raven, supplying the sort info plus take and skip for server side paging
            using (var orgSession = OrgStore.OpenSession())
            {
                try
                {

                    var managers = orgSession.Load<User>(employeeId)
                                             .Relationships.Where(r => r.RelationshipName == "LineManager")
                                             .Skip(request.skip)
                                             .Take(request.take)
                                             .Select(
                                                 manager =>
                                                 new Manager
                                                 {
                                                     ManagerName = manager.FullName,
                                                     ManagerEmployeeId = manager.UserId,
                                                     EmployeeId = employeeId
                                                 });


                    //put our results plus the total count in the view model and send it back as JSON
                    return Json(new AccountsManagersAdminViewModel
                    {
                        Managers = managers.ToArray(),
                        Count =
                            orgSession.Load<User>(employeeId)
                                      .Relationships.Count(r => r.RelationshipName == "LineManager")
                    }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    GetLogger()
                        .Error(
                            string.Format(
                                "Administration-ManagersForEmployee: Problem querying for users managers {0}",
                                employeeId), ex);
                    return JsonError("Cannot find user", JsonRequestBehavior.AllowGet);
                }
            }

        }
 public JsonResult AllManagers(Request request)
 {
     return Json(GetEmployees(request, true), JsonRequestBehavior.AllowGet);
 }
        /// <summary>
        /// Return employees to search on
        /// </summary>
        /// <param name="request"></param>
        /// <param name="onlyManagers"></param>
        /// <returns></returns>
        private AccountsAdminViewModel GetEmployees(Request request, bool onlyManagers)
        {
            //the default parameter to sort employees on if one isnt supplied by the client
            var order = string.Empty;

            //use the sort details in the request to construct a string to be used in the linq query (dynamic linq)
            if (request.sort != null && request.sort.Count > 0)
            {
                var sorts = new List<string>();
                request.sort.ForEach(
                    x =>
                    sorts.Add(x.field.ToLower() == "photo" ? string.Empty : string.Format("{0} {1}", x.field, x.dir)));
                order = string.Join(",", sorts.ToArray());
                order = order.Replace("Name", "LastName");
            }
            if (string.IsNullOrEmpty(order))
                order = "LastName";
            order = order.Trim(',');

            var startsWith = string.Empty;
            if (request.filter != null && request.filter.filters[0] != null && request.filter.filters[0].Field.ToLower() == "name" &&
                request.filter.filters[0].Operator.ToLower() == "startswith")
            {
                startsWith = request.filter.filters[0].Value;
            }
            //query raven, supplying the sort info plus take and skip for server side paging
            using (var orgSession = OrgStore.OpenSession())
            {
                var query =
                    orgSession.Query<User>()
                              .Where(user => !user.IsDeleted)
                              .Where(
                                  user =>
                                  user.LastName.StartsWith(startsWith, true, CultureInfo.CurrentCulture) ||
                                  user.FirstName.StartsWith(startsWith, true, CultureInfo.CurrentCulture) ||
                                  user.Name.StartsWith(startsWith, true, CultureInfo.CurrentCulture)
                        );
                if (onlyManagers)
                {
                    query = query.Where(user => user.Roles.Any(r => r.Name == Role.BuiltInRole.Manager.ToString()));
                }
                var accounts = query.Skip(request.skip)
                                    .Take(request.take)
                                    .OrderBy(order)
                                    .Select(user => new Account
                                    {
                                        Name = user.Name,
                                        PersonnelNumber = user.PersonnelNumber,
                                        Position = user.Position,
                                        EmailAddress = user.EmailAddress,
                                        DateOfBirth = user.DateOfBirth,
                                        Id = user.Id,
                                        PhotoId = user.Avatar.PublicID,
                                        Roles = user.Roles,
                                        MobilePhoneNumber = user.MobilePhoneNumber,
                                        //NeedsAD = user.NeedsAD
                                    }).ToArray();

                //in case some DOBs havent been set  - set them to a sensible value to make ir easier for the user
                foreach (var account in accounts.Where(a => a.DateOfBirth == DateTime.MinValue))
                {
                    account.DateOfBirth = DateTime.Now.Date.AddYears(-35);
                }

                //this is the safe way to get the total number of docs of a particaular type - we need this to make paging work
                RavenQueryStatistics stats;
                orgSession.Query<User>().Statistics(out stats).Where(user => !user.IsDeleted).ToArray();
                foreach (var account in accounts)
                {
                    account.IsManager = account.Roles.Any(r => r.Name == Role.BuiltInRole.Manager.ToString());
                    account.IsAdministrator = account.Roles.Any(r => r.Name == Role.BuiltInRole.Administrator.ToString());
                    account.IsAnalytics = account.Roles.Any(r => r.Name == Role.BuiltInRole.Analytics.ToString());
                }
                //put our results plus the total count in the view model and send it back as JSON
                var vm = new AccountsAdminViewModel { Accounts = accounts, Count = stats.TotalResults };
                return vm;
            }
        }
        /// <summary>
        /// Get some search terms based on the users input
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ActionResult SearchTerms(Request request)
        {
            const int numTerms = 10;
            
            var term = request.filter.filters[0].Value;
            
            using (var session = OrgStore.OpenSession())
            {
                //form the raven search request
                var searchRequest = session.Query<GlobalSearch.Result, GlobalSearch>()
                                           .Where(x => x.AllText == term && x.AllowedUsers.Any(au => au == UserId));

                // var terms= searchRequest.Suggest().Suggestions.Select(
                //                          r =>
                //                          new 
                //                          {
                //                              Term = r..ResultText
                //                          }).ToList();

                //.Search(x => x.AllText, wildcardTerm, escapeQueryOptions: EscapeQueryOptions.AllowPostfixWildcard)
                //.Take(numTerms)
                //.As<dynamic>();

                //now ask raven to give us some matching suggestions
                var suggestions = searchRequest.Suggest(new SuggestionQuery()
                {
                    Field = "AllText",
                    Term = term,
                }).Suggestions;
                //return all the suggestions
                var terms = suggestions.Take(numTerms)
                                         .Select(
                                             suggestion =>
                                             new
                                                 {
                                                     Term = suggestion
                                                 }).ToList();
                return Json(new {Terms = terms, Count = terms.Count}, JsonRequestBehavior.AllowGet);
            }
            //if (terms.Count < numTerms)
                //{
                //    var suggestionQueryResult = searchRequest.Suggest();

                //    terms.AddRange(suggestionQueryResult.Suggestions.Take(numTerms - terms.Count).Select(
                //        s =>
                //        new
                //            {
                //                Term = s
                //            }));
                    //terms.AddRange(session.Query<GlobalSearch.Result, GlobalSearch>()
                    //                          .Search(x => x.AllText, string.Join(" ", suggestions))
                    //                          .Take(numTerms - terms.Count).As<dynamic>().ToList()
                    //.OfType<ISearchResult>()
                    //                 .Select(
                    //                     r =>
                    //                     new 
                    //                     {
                    //                         Term = r.ResultText,
                    //                         Id=r.ResultId

                    //                     }));
                //}

                //var results = session.Query<GlobalSearch.Result>("GlobalSearch")
                //                     .Search(x => x.AllText, term,
                //                             escapeQueryOptions: EscapeQueryOptions.AllowPostfixWildcard)
                //                     .Search(x => x.UserText, term,
                //                             escapeQueryOptions: EscapeQueryOptions.AllowPostfixWildcard)
                //                     //.Where(o => o.AllowedUsers.Any(au => au == UserId))
                //                     .As<dynamic>()
                //                     .ToList()
                //                     .OfType<ISearchResult>()
                //                     .Select(
                //                         r =>
                //                         new SearchViewModel
                //                             {
                //                                 ResultText = r.ResultText,
                //                                 Id = r.ResultId,
                //                                 TypeName = r.TypeName
                //                             }).ToList();


        }
        public void AllEmployees()
        {
            
            var users = GetAndSaveTestUsers(10,OrgStore);


            
            //ARRANGE
            var controller = GetAuthenticatedControllerMock<AccountController>(Orguser);

            //set controller context. 
            controller.ControllerContext = new ControllerContext(GetContext(false), new RouteData(), controller);


            var request = new Request
            {
                
                page = 0,
                skip = 0,
                take = 5

            };
            var result = controller.AllEmployees(request);
            var jsonresponse = ValidateAndUnwrapJsonResult(result);

            var data = jsonresponse.Data as AccountsAdminViewModel;

            Assert.IsNull(jsonresponse.ErrorMessage);
            Assert.AreEqual(data.Count, 12);
            Assert.AreEqual(data.Accounts.Count(), 5);

            request = new Request
            {

                page = 0,
                skip = 5,
                take = 5

            };
             result = controller.AllEmployees(request);
             jsonresponse = ValidateAndUnwrapJsonResult(result);

             data = jsonresponse.Data as AccountsAdminViewModel;

            Assert.IsNull(jsonresponse.ErrorMessage);
            Assert.AreEqual(data.Count, 12);
            Assert.AreEqual(data.Accounts.Count(), 5);
            request = new Request
            {

                page = 0,
                skip = 10,
                take = 5

            };
            result = controller.AllEmployees(request);
            jsonresponse = ValidateAndUnwrapJsonResult(result);

            data = jsonresponse.Data as AccountsAdminViewModel;

            Assert.IsNull(jsonresponse.ErrorMessage);
            Assert.AreEqual(data.Count, 12);
            Assert.AreEqual(data.Accounts.Count(), 2);
        }
        public void ManagersForEmployeeNoManagers()
        {
            const string testEmployeeid = "testemployee";
            var testUser = new User()
            {
                Id = testEmployeeid,
                CreatedDate = DateTime.Now
            };
            

           
            using (var session = OrgStore.OpenSession())
            {
                session.Store(testUser);
                
                session.SaveChanges();
            }
            //ARRANGE
            var controller = GetAuthenticatedControllerMock<AdministrationController>(Orguser);

            //set controller context. 
            controller.ControllerContext = new ControllerContext(GetContext(false), new RouteData(), controller);


            var request = new Request
            {
                filter = new FilterLogic
                {
                    filters = new[]
                                                                 {
                                                                     new Filter { Value = testEmployeeid }
                                                                 }
                },
                page = 0,
                skip = 0,
                take = 10

            };
            var result = controller.ManagersForEmployee(request);
            var jsonresponse = ValidateAndUnwrapJsonResult(result);

            var data = jsonresponse.Data as AccountsManagersAdminViewModel;

            Assert.IsNull(jsonresponse.ErrorMessage);
            Assert.AreEqual(data.Count, testUser.Relationships.Count);
            
        }
        public void ManagersForEmployee()
        {
            const string testEmployeeid = "testemployee";
            var testUser = new User()
            {
                Id = testEmployeeid,
                CreatedDate = DateTime.Now
            };
            const string manager1Id = "manager1";
            var manager1 = new User()
            {
                Id = manager1Id,
                CreatedDate = DateTime.Now,
                FirstName = "Bill",
                LastName = "Bunter"
            };
            const string manager2Id = "manager2";
            var manager2= new User()
            {
                Id = manager2Id,
                CreatedDate = DateTime.Now,
                FirstName = "Bob",
                LastName = "Bonter"
            };
           
            manager1.Roles.Add(Role.GetRole( Role.BuiltInRole.Manager));
            manager2.Roles.Add(Role.GetRole(Role.BuiltInRole.Manager));
            testUser.AddManager(manager1);
            testUser.AddManager(manager2);
            using (var session = OrgStore.OpenSession())
            {
                session.Store(testUser);
                session.Store(manager1);
                session.Store(manager2);
                session.SaveChanges();
            }
            //ARRANGE
            var controller = GetAuthenticatedControllerMock<AdministrationController>(Orguser);

            //set controller context. 
            controller.ControllerContext = new ControllerContext(GetContext(false), new RouteData(), controller);

           
            var request = new Request
                              {
                                  filter = new FilterLogic
                                               {
                                                   filters = new []
                                                                 {
                                                                     new Filter { Value = testEmployeeid }
                                                                 }
                                               },
                                               page = 0,
                                               skip = 0,
                                               take = 10

                              };
            var result = controller.ManagersForEmployee(request);
            var jsonresponse = ValidateAndUnwrapJsonResult(result);

            var data = jsonresponse.Data as AccountsManagersAdminViewModel;
            
            Assert.IsNull(jsonresponse.ErrorMessage);
            Assert.AreEqual(data.Count,testUser.Relationships.Count);
            Assert.AreEqual(data.Managers.First().EmployeeId,testUser.Id);
            Assert.AreEqual(data.Managers.First().ManagerEmployeeId, manager1Id);
            Assert.AreEqual(data.Managers.First().ManagerName, manager1.Name);
            Assert.AreEqual(data.Managers.Last().EmployeeId, testUser.Id);
            Assert.AreEqual(data.Managers.Last().ManagerName, manager2.Name);
            Assert.AreEqual(data.Managers.Last().ManagerEmployeeId, manager2Id);
        }
        public void AllManagers()
        {

            var Orguser2 = new User { Id = IlluminateDatabase.GenerateId<User>(), NameIdentifier = "nameidentifier", OrgKey = Testorg.OrgKey, EmailAddress = "*****@*****.**", DateOfBirth = new DateTime(1990, 1, 1), FirstName = "Test", LastName = "User", Config = new Config { Settings = new Dictionary<string, object>() } };
            var Manager2 = new User { Id = IlluminateDatabase.GenerateId<User>(), NameIdentifier = "managernameidentifier", OrgKey = Testorg.OrgKey, EmailAddress = "*****@*****.**", DateOfBirth = new DateTime(1991, 1, 1), FirstName = "Test", LastName = "Manager", Config = new Config { Settings = new Dictionary<string, object>() } };
            //set as manager
            Manager2.Roles.Add(Role.GetRole(Role.BuiltInRole.Manager));
            Orguser2.AddManager(Manager);
            var Orguser3 = new User { Id = IlluminateDatabase.GenerateId<User>(), NameIdentifier = "nameidentifier2", OrgKey = Testorg.OrgKey, EmailAddress = "*****@*****.**", DateOfBirth = new DateTime(1990, 1, 1), FirstName = "Test2", LastName = "User2", Config = new Config { Settings = new Dictionary<string, object>() } };
            var Manager3 = new User { Id = IlluminateDatabase.GenerateId<User>(), NameIdentifier = "managernameidentifier2", OrgKey = Testorg.OrgKey, EmailAddress = "*****@*****.**", DateOfBirth = new DateTime(1991, 1, 1), FirstName = "Test2", LastName = "Manager2", Config = new Config { Settings = new Dictionary<string, object>() } };
            //set as manager
            Manager3.Roles.Add(Role.GetRole(Role.BuiltInRole.Manager));
            Orguser3.AddManager(Manager);
            using (var session = OrgStore.OpenSession())
            {
                session.Store(Orguser2);
                session.Store(Manager2);
                session.Store(Orguser3);
                session.Store(Manager3);
                session.SaveChanges();
                var check = session.Query<User>().ToList();
            }

            //var users = GetAndSaveTestUsers(10, OrgStore);



            //ARRANGE
            var controller = GetAuthenticatedControllerMock<AccountController>(Orguser);

            //set controller context. 
            controller.ControllerContext = new ControllerContext(GetContext(false), new RouteData(), controller);


            var request = new Request
            {

                page = 0,
                skip = 0,
                take = 5

            };
            //var result = controller.AllEmployees(request);
            //var jsonresponse = ValidateAndUnwrapJsonResult(result);

            //var data = jsonresponse.Data as AccountsAdminViewModel;

            //Assert.IsNull(jsonresponse.ErrorMessage);
            //Assert.AreEqual(data.Count, 12);
            //Assert.AreEqual(data.Accounts.Count(), 5);

            var result = controller.AllManagers(request);
            var jsonresponse = ValidateAndUnwrapJsonResult(result);
            var data = jsonresponse.Data as AccountsAdminViewModel;
            // var look = data.Accounts[0];

            Assert.IsNull(jsonresponse.ErrorMessage);
            Assert.AreEqual(data.Count, 6);
            Assert.AreEqual(data.Accounts.Count(), 3);

            //  add a load more users and check this doesn't mess it up
            //var users = GetAndSaveTestUsers(10, OrgStore);

            var request2 = new Request
            {

                page = 0,
                skip = 0,
                take = 0

            };

            var result2 = controller.AllManagers(request2);
            var jsonresponse2 = ValidateAndUnwrapJsonResult(result2);
            var data2 = jsonresponse.Data as AccountsAdminViewModel;

            Assert.IsNull(jsonresponse.ErrorMessage);
            Assert.AreEqual(data.Count, 6);
            Assert.AreEqual(data.Accounts.Count(), 3);

        }