public JsonResult DeleteAccounts(Account[] accounts) { using (var orgSession = OrgStore.OpenSession()) { var errorBuilder = new StringBuilder(); foreach (var user in accounts.Select(account => orgSession.Load<User>(account.Id))) { if (user == null) errorBuilder.Append("Cannot find user"); if (user != null) user.IsDeleted = true; // flag the membership reboot acount as closed. var userAccountService = MvcApplication.UserAccountService; var account = userAccountService.GetByEmail(user.EmailAddress); userAccountService.DeleteAccount(account.Id); } if (errorBuilder.Length > 0) return JsonError(new AccountsAdminViewModel { ErrorMessage = errorBuilder.ToString() }, errorBuilder.ToString()); var vm = new AccountsAdminViewModel(); //save the changes to Raven and send a success message to the client try { orgSession.SaveChanges(); vm.SuccessMessage = string.Format("Succesfully soft deleted {0} employee accounts", accounts.Length); return JsonSuccess(vm, vm.SuccessMessage); } catch (Exception ex) { GetLogger().Error("Administration:Delete accounts:", ex); vm.ErrorMessage = "Cannot delete accounts"; return JsonError(vm, vm.ErrorMessage); } } }
// need to verify that e-mail address given doesn't exist already in database. //used to both edit existing employees and add new ones private JsonResult EditOrCreateAccounts(Account[] accounts, bool isEdit) { //check the all the details are correct and if not send message to client var errors = CheckAccounts(accounts); if (errors.Length > 0) return JsonError(new AccountsAdminViewModel { ErrorMessage = errors }, errors); var users = new List<IUser>(); var errorBuilder = new StringBuilder(); // create/edit the users foreach (var account in accounts) { var user = CreateOrEditUser(account, isEdit); if (user == null && isEdit)//cant find user in database { errorBuilder.Append("Cannot find user"); } using (var session = OrgStore.OpenSession()) { if (session.Query<User>().Any(u => u.EmailAddress == account.EmailAddress) && !isEdit) { GetLogger().Error("Admin:EditOrCreateAccounts: attempted to add a user with an e-mail address already in OrgDB"); errorBuilder.Append("Cannot add user with this e-mail address. E-mail address already registered to another user"); } else { //set the user details to that coming from the client AccountToUser(account, user);// only do this if account.EmailAddress is not in DB, check master or OrgDB? } } //user = UserADSettings(user); //if (isEdit) continue; // in original loop, user was saved here, but as only users being added are added to users, can loop through user list and add each one later. users.Add(user); } if (errorBuilder.Length > 0) return JsonError(new AccountsAdminViewModel { ErrorMessage = errorBuilder.ToString() }, errorBuilder.ToString()); var vm = new AccountsAdminViewModel(); // now open session here, first, store users using (var orgSession = OrgStore.OpenSession()) { foreach (var user in users) { orgSession.Store(user); } //save the changes to Raven and send a success message to the client try { var shouldSave = true; var editedAdded = "added"; if (isEdit) { editedAdded = "edited"; } else { shouldSave=AddUsersToMasterDB(users); } if (shouldSave) { orgSession.SaveChanges(); vm.SuccessMessage = string.Format("Succesfully {0} {1} employee accounts", editedAdded, accounts.Length); return JsonSuccess(vm, vm.SuccessMessage); } else { GetLogger().Error("Admin:EditOrCreateAccounts: attempted to add a user with an e-mail address already in MasterDB"); vm.ErrorMessage = "Cannot add user with this e-mail address. E-mail address already registered to another user"; return JsonError(vm, vm.ErrorMessage); } } catch (Exception ex) { GetLogger().Error(string.Format("Admin:EditOrCreateAccounts: Cannot save changes to Raven"), ex); vm.ErrorMessage = "Cannot save changes"; return JsonError(vm, vm.ErrorMessage); } } }
/// <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; } }