public void OrderApproved(Order order, Approval approval) { var queues = new List <EmailQueueV2>(); // go through all the tracking history foreach (var appr in order.OrderTrackings.Where(a => a.StatusCode.Level < approval.StatusCode.Level).Select(a => new { User = a.User, StatusCode = a.StatusCode }).Distinct()) { var user = appr.User; var preference = GetEmailPreferences(user.Id); if (IsMailRequested(preference, appr.StatusCode, approval.StatusCode, EventCode.Approval)) { var currentUser = _userRepository.GetNullableById(_userIdentity.Current); //var emailQueue = new EmailQueue(order, preference.NotificationType, string.Format(ApprovalMessage, GenerateLink(_serverLink.Address, order.OrderRequestNumber()), order.Vendor == null ? "Unspecified Vendor" : order.Vendor.Name, currentUser.FullName, approval.StatusCode.Name), user); var emailQueue2 = new EmailQueueV2(order, preference.NotificationType, "Approved", string.Format("By {0} at {1} review.", currentUser.FullName, approval.StatusCode.Name), user); AddToQueue(queues, emailQueue2); } } AddQueuesToOrder(order, queues); // is the current level complete? if (!order.Approvals.Where(a => a.StatusCode.Level == order.StatusCode.Level && !a.Completed).Any()) { // look forward to the next level var level = order.StatusCode.Level + 1; ProcessArrival(order, approval, level); } }
public List <OrderTracking> SetupOrderTracking(Order order) { var whenApproved = DateTime.UtcNow.ToPacificTime().AddDays(-10); var orderTracking = new List <OrderTracking>(); var tracking = new OrderTracking(); tracking.DateCreated = whenApproved; tracking.Description = "Description1"; tracking.Order = order; tracking.StatusCode = OrderStatusCodeRepository.GetNullableById(OrderStatusCode.Codes.Requester); tracking.User = order.CreatedBy; orderTracking.Add(tracking); Order order1 = order; var count = 1; var approvals = ApprovalRepository.Queryable.Where(a => a.Order.Id == order1.Id && a.Completed).OrderBy(b => b.StatusCode.Level); foreach (var approval in approvals) { tracking = new OrderTracking(); tracking.DateCreated = whenApproved.AddDays(count); tracking.Description = "Description" + count; tracking.Order = order; tracking.StatusCode = approval.StatusCode; tracking.User = approval.User; orderTracking.Add(tracking); count++; } return(orderTracking); }
public void SetupDateForIndex1() { var organizations = new List <Organization>(); var users = new List <User>(); for (int i = 0; i < 3; i++) { users.Add(CreateValidEntities.User(i + 1)); users[i].Organizations = new List <Organization>(); for (int j = 0; j < 4; j++) { var organization = CreateValidEntities.Organization((i * 4) + (j + 1)); organization.Name = "O" + organization.Name; organization.SetIdTo(((i * 4) + (j + 1)).ToString()); users[i].Organizations.Add(organization); organizations.Add(organization); } } users.Add(CreateValidEntities.User(4)); new FakeUsers(0, UserRepository, users, false); new FakeOrganizations(0, OrganizationRepository, organizations, true); var workgroups = new List <Workgroup>(); for (int i = 0; i < 6; i++) { workgroups.Add(CreateValidEntities.Workgroup(i + 1)); workgroups[i].Name = "W" + workgroups[i].Name; workgroups[i].Organizations = new List <Organization>(); workgroups[i].Organizations.Add(OrganizationRepository.GetNullableById(((i * 2) + 1).ToString())); workgroups[i].Organizations.Add(OrganizationRepository.GetNullableById(((i * 2) + 2).ToString())); } workgroups[5].Organizations.Add(OrganizationRepository.GetNullableById("6")); new FakeWorkgroups(0, WorkgroupRepository, workgroups); var conditionalApprovals = new List <ConditionalApproval>(); for (int i = 0; i < 6; i++) { conditionalApprovals.Add(CreateValidEntities.ConditionalApproval(i + 1)); conditionalApprovals[i].Workgroup = WorkgroupRepository.GetNullableById(i + 1); } for (int i = 6; i < 18; i++) { conditionalApprovals.Add(CreateValidEntities.ConditionalApproval(i + 1)); conditionalApprovals[i].Workgroup = null; conditionalApprovals[i].Organization = OrganizationRepository.GetNullableById((i - 5).ToString()); } conditionalApprovals[0].PrimaryApprover = CreateValidEntities.User(99); conditionalApprovals[6].PrimaryApprover = CreateValidEntities.User(99); conditionalApprovals[6].SecondaryApprover = CreateValidEntities.User(88); new FakeConditionalApprovals(0, ConditionalApprovalRepository, conditionalApprovals); }
//// //// GET: /Employee/Create //public ActionResult Create() //{ // var viewModel = EmployeeSalaryComparisonViewModel.Create(Repository); // return View(viewModel); //} //// //// POST: /Employee/Create //[HttpPost] //public ActionResult Create(Employee employee) //{ // var employeeToCreate = new Employee(); // TransferValues(employee, employeeToCreate); // if (ModelState.IsValid) // { // _employeeRepository.EnsurePersistent(employeeToCreate); // Message = "Employee Created Successfully"; // return RedirectToAction("Index"); // } // else // { // var viewModel = EmployeeSalaryComparisonViewModel.Create(Repository); // viewModel.Employee = employee; // return View(viewModel); // } //} //// //// GET: /Employee/Edit/5 //public ActionResult Edit(int id) //{ // var employee = _employeeRepository.GetNullableById(id); // if (employee == null) return RedirectToAction("Index"); // var viewModel = EmployeeSalaryComparisonViewModel.Create(Repository); // viewModel.Employee = employee; // return View(viewModel); //} //// //// POST: /Employee/Edit/5 //[HttpPost] //public ActionResult Edit(int id, Employee employee) //{ // var employeeToEdit = _employeeRepository.GetNullableById(id); // if (employeeToEdit == null) return RedirectToAction("Index"); // TransferValues(employee, employeeToEdit); // if (ModelState.IsValid) // { // _employeeRepository.EnsurePersistent(employeeToEdit); // Message = "Employee Edited Successfully"; // return RedirectToAction("Index"); // } // else // { // var viewModel = EmployeeSalaryComparisonViewModel.Create(Repository); // viewModel.Employee = employee; // return View(viewModel); // } //} // // GET: /Employee/Delete/5 public ActionResult Delete(string id) { var employee = _employeeRepository.GetNullableById(id); if (employee == null) { return(RedirectToAction("Index")); } return(View(employee)); }
/// <summary> /// Common Code moved to service /// </summary> /// <param name="source"></param> /// <param name="destination">Note, this is a ref so tests work</param> public void TransferValues(WorkgroupVendor source, ref WorkgroupVendor destination) { Mapper.Map(source, destination); // existing vendor, set the values if (!string.IsNullOrWhiteSpace(source.VendorId) && !string.IsNullOrWhiteSpace(source.VendorAddressTypeCode)) { var vendor = _vendorRepository.GetNullableById(source.VendorId); var vendorAddress = _vendorAddressRepository.Queryable.FirstOrDefault(a => a.Vendor == vendor && a.TypeCode == source.VendorAddressTypeCode); if (vendor != null && vendorAddress != null) { destination.Name = vendor.Name; destination.Line1 = vendorAddress.Line1; destination.Line2 = vendorAddress.Line2; destination.Line3 = vendorAddress.Line3; destination.City = vendorAddress.City; destination.State = vendorAddress.State ?? "XX"; // If vendor is in another Country like Australia, the State may/is null destination.Zip = vendorAddress.Zip ?? "XXXXX"; destination.CountryCode = vendorAddress.CountryCode; destination.Phone = vendorAddress.PhoneNumber; destination.Fax = vendorAddress.FaxNumber; destination.Email = vendorAddress.Email; destination.Url = vendorAddress.Url; } } }
public ActionResult Create(AutoApproval autoApproval, bool showAll = false) { autoApproval.Equal = !autoApproval.LessThan; //only one can be true, the other must be false autoApproval.User = _userRepository.GetNullableById(CurrentUser.Identity.Name); ModelState.Clear(); autoApproval.TransferValidationMessagesTo(ModelState); if (autoApproval.Expiration.HasValue && autoApproval.Expiration.Value.Date <= DateTime.UtcNow.ToPacificTime().Date) { ModelState.AddModelError("AutoApproval.Expiration", "Expiration date has already passed"); } autoApproval.IsActive = true; if (ModelState.IsValid) { _autoApprovalRepository.EnsurePersistent(autoApproval); Message = "AutoApproval Created Successfully"; if (autoApproval.Expiration.HasValue && autoApproval.Expiration.Value.Date <= DateTime.UtcNow.ToPacificTime().Date.AddDays(5)) { Message = Message + " Warning, will expire in 5 days or less"; } return(this.RedirectToAction(a => a.Index(showAll))); } else { var viewModel = AutoApprovalViewModel.Create(Repository, CurrentUser.Identity.Name); viewModel.AutoApproval = autoApproval; ViewBag.ShowAll = showAll; ViewBag.IsCreate = true; return(View(viewModel)); } }
/// <summary> /// Return the attachment associated with the given attachmentId, with contents populated /// </summary> /// <param name="id">attachmentID</param> /// <returns></returns> public Attachment GetAttachment(Guid id) { var file = _attachmentRepository.GetNullableById(id); if (file == null) { return(null); } if (file.IsBlob) { //Get file from blob storage and populate the contents var blob = _container.GetBlockBlobReference(id.ToString()); using (var stream = new MemoryStream()) { blob.DownloadToStream(stream); using (var reader = new BinaryReader(stream)) { stream.Position = 0; file.Contents = reader.ReadBytes((int)stream.Length); } } } return(file); }
/// <summary> /// Create an account from Information Request /// </summary> /// <param name="id">Information Request Id</param> /// <returns></returns> public ActionResult CreatePerson(int id) { var ir = _informationrequestRepository.GetNullableById(id); if (ir == null) { Message = string.Format(Messages.NotFound, "information request", id); return(this.RedirectToAction(a => a.Index())); } var viewModel = PersonViewModel.Create(Repository, _firmService, Site); viewModel.Person.FirstName = ir.FirstName.Trim(); viewModel.Person.LastName = ir.LastName.Trim(); viewModel.Email = ir.Email; viewModel.UserName = string.Format("{0}.{1}", ir.FirstName.Trim(), ir.LastName.Trim()); // fake phone number viewModel.Person.Phone = ir.Phone; var atype = _addressTypeRepository.GetNullableById((char)StaticIndexes.Address_Business[0]); var address = viewModel.Addresses.FirstOrDefault(a => a.AddressType == atype); if (address != null) { address.Line1 = ir.AddressLine1; address.Line2 = ir.AddressLine2; address.City = ir.City; address.State = ir.State; address.Zip = ir.Zip; address.Country = ir.Country; } if (ir.Site.CollectExtended) { // get the assistant contact var ctype = RepositoryFactory.ContactTypeRepsitory.GetNullableById((char)StaticIndexes.Contact_Assistant[0]); var assistant = viewModel.Contacts.FirstOrDefault(a => a.ContactType == ctype); if (assistant != null) { assistant.FirstName = ir.AssistantFirstName; assistant.LastName = ir.AssistantLastName; assistant.Email = ir.AssistantEmail; assistant.Phone = ir.AssistantPhone; var comoption = RepositoryFactory.CommunicationOptionRepository.GetNullableById(StaticIndexes.Communication_Assistant); viewModel.Person.CommunicationOption = comoption; } } else { var comoption = RepositoryFactory.CommunicationOptionRepository.GetNullableById(StaticIndexes.Communication_Directly); viewModel.Person.CommunicationOption = comoption; } return(View(viewModel)); }
// // GET: /School/Details/5 public ActionResult Details(string id) { var school = _schoolRepository.GetNullableById(id); if (school == null) { return(RedirectToAction("Index")); } var unitsForSchool = _unitRepository.Queryable.Where(x => x.School.Id == id).ToList(); var model = SchoolViewModel.Create(Repository); model.School = school; model.Units = unitsForSchool; return(View(model)); }
public ActionResult EmailPreferences(string id) { var userEmailPreferences = _emailPreferencesRepository.GetNullableById(id) ?? new EmailPreferences(id); var user = _userRepository.Queryable.Single(a => a.Id.ToLower() == id.ToLower()); ViewBag.IsConditionalApprover = Repository.OfType <ConditionalApproval>().Queryable.Any( a => a.PrimaryApprover == user || a.SecondaryApprover == user); return(View(userEmailPreferences)); }
private EmailPreferences GetEmailPreferences(string userId) { var pref = _emailPreferenceRepository.GetNullableById(userId); if (pref == null) { var log = Log.ForContext("userId", userId); //Log email pref not found log.Information("Email Preference not found with GetNullable"); pref = _emailPreferenceRepository.Queryable.FirstOrDefault(a => a.Id == userId.Trim().ToLower()); if (pref == null) { //Log that this failed too log.Information("Email Preference not found with FirstOrDefault and Trim.ToLower"); pref = new EmailPreferences(userId); } } return(pref); }
/// <summary> /// List of Custom Fields for the organization /// </summary> /// <param name="id">Organization Id</param> /// <returns></returns> public ActionResult Index(string id) { var org = string.IsNullOrWhiteSpace(id) ? null : _organizationRepository.GetNullableById(id); if (org == null) { Message = "Organization not found."; return(this.RedirectToAction <OrganizationController>(a => a.Index())); } var message = string.Empty; if (!_securityService.HasWorkgroupOrOrganizationAccess(null, org, out message)) { Message = message; return(this.RedirectToAction <ErrorController>(a => a.NotAuthorized())); } return(View(org)); }
public ActionResult ModifyAdmin(User user) { if (!ModelState.IsValid) { return(View(user)); } var userToSave = _userRepository.GetNullableById(user.Id) ?? new User(user.Id); //user.Organizations = userToSave.Organizations; //Transfer the orgs and roles since they aren't managed on this page //user.Roles = userToSave.Roles; userToSave.FirstName = user.FirstName; userToSave.LastName = user.LastName; userToSave.Email = user.Email; userToSave.IsActive = user.IsActive; //Mapper.Map(user, userToSave); var isAdmin = userToSave.Roles.Any(x => x.Id == Role.Codes.Admin); if (!isAdmin) { userToSave.Roles.Add(_roleRepository.GetById(Role.Codes.Admin)); } _userRepository.EnsurePersistent(userToSave); // invalid the cache for the user that was just given permissions _userIdentity.RemoveUserRoleFromCache(Resources.Role_CacheId, userToSave.Id); if (_emailPreferencesRepository.GetNullableById(userToSave.Id) == null) { _emailPreferencesRepository.EnsurePersistent(new EmailPreferences(userToSave.Id)); } Message = string.Format("{0} was edited under the administrator role", user.FullNameAndId); return(this.RedirectToAction(a => a.Index())); }
public void SetupDataForVendors2() { new FakeWorkgroups(3, WorkgroupRepository); var vendors = new List <Vendor>(); vendors.Add(CreateValidEntities.Vendor(9)); vendors[0].SetIdTo("VendorId9"); new FakeVendors(0, VendorRepository, vendors, true); var vendorAddresses = new List <VendorAddress>(); for (int i = 0; i < 3; i++) { var vendorAddress = CreateValidEntities.VendorAddress(i + 1); vendorAddress.Vendor = VendorRepository.GetNullableById("VendorId9"); vendorAddresses.Add(vendorAddress); } vendorAddresses[1].TypeCode = "tc9"; vendorAddresses[1].Line2 = "Line2"; vendorAddresses[1].Line3 = "Line3"; new FakeVendorAddresses(0, VendorAddressRepository, vendorAddresses, false); }
public ActionResult AdminEdit(Guid id, int?seminarId, bool?allList) { var user = _userRepository.GetNullableById(id); if (user == null) { Message = string.Format(Messages.NotFound, "user", id); return(this.RedirectToAction <PersonController>(a => a.SiteList())); } ViewBag.AllList = allList ?? false; var viewModel = AdminPersonViewModel.Create(Repository, _firmService, Site, seminarId, user.Person, user.Email); if (viewModel.PersonViewModel.SeminarPerson == null) { viewModel.SeminarId = null; } return(View(viewModel)); }
public Order SetupData1(string userId, OrderStatusCode currentLevel) { var approvals = new List <Approval>(); var order = CreateValidEntities.Order(1); order.SetIdTo(1); order.CreatedBy = UserRepository.GetNullableById(userId); Assert.IsNotNull(order.CreatedBy); order.StatusCode = currentLevel; CreateApprovals(approvals, currentLevel, order); new FakeApprovals(0, ApprovalRepository, approvals); order.OrderTrackings = SetupOrderTracking(order); order.Organization = CreateValidEntities.Organization(9); order.Organization.SetIdTo("testOrg"); return(order); }
/// <summary> /// #2 /// </summary> /// <returns></returns> public ActionResult Create() { var request = _departmentalAdminRequestRepository.GetNullableById(CurrentUser.Identity.Name); var ldap = _directorySearchService.FindUser(CurrentUser.Identity.Name); Check.Require(ldap != null, "Person requesting Departmental Access ID not found. ID = " + CurrentUser.Identity.Name); var model = DepartmentalAdminRequestViewModel.Create(); model.DepartmentalAdminRequest = request ?? new DepartmentalAdminRequest(ldap.LoginId.ToLower()); model.DepartmentalAdminRequest.FirstName = ldap.FirstName; model.DepartmentalAdminRequest.LastName = ldap.LastName; model.DepartmentalAdminRequest.Email = ldap.EmailAddress; model.DepartmentalAdminRequest.PhoneNumber = ldap.PhoneNumber; if (model.DepartmentalAdminRequest.Organizations != null && model.DepartmentalAdminRequest.Organizations.Any()) { foreach (var orgId in model.DepartmentalAdminRequest.Organizations.Split(',')) { var org = _repositoryFactory.OrganizationRepository.GetNullableById(orgId); if (org != null) { model.Organizations.Add(org); } } } return(View(model)); }
public virtual void CanGetEntityUsingGetByNullableWithValidId() { if (typeof(IdT) == typeof(int)) { Assert.IsTrue(EntriesAdded >= 2, "There are not enough entries to complete this test."); var foundEntity = _intRepository.GetNullableById(2); FoundEntityComparison(foundEntity, 2); } else if (typeof(IdT) == typeof(Guid)) { Assert.IsTrue(EntriesAdded >= 2, "There are not enough entries to complete this test."); var guidFor2 = _guidRepository.GetAll()[1].Id.ToString(); var foundEntity = _guidRepository.GetNullableById(new Guid(guidFor2)); FoundEntityComparison(foundEntity, 2); } else { Assert.IsTrue(EntriesAdded >= 2, "There are not enough entries to complete this test."); var foundEntity = _stringRepository.GetNullableById("2"); FoundEntityComparison(foundEntity, 2); } }
public ActionResult UpdateRoles(int personId, int seminarId, List <string> roles) { // just catch if no roles roles = roles ?? new List <string>(); var person = _personRepository.GetNullableById(personId); if (person == null) { Message = string.Format(Messages.NotFound, "Person", personId); return(this.RedirectToAction(a => a.SiteList())); } // merge the roles var reg = person.GetLatestRegistration(Site); var seminar = SiteService.GetLatestSeminar(Site); // check if user is registered for the current seminar if (reg.Seminar.Id != seminar.Id) { Message = "User is not a part of the current seminar. Roles cannot be assigned."; return(this.RedirectToAction(a => a.AdminEdit(person.User.Id, seminarId, null))); } var existingRoles = reg.SeminarRoles.Select(a => a.Id).ToList(); // add the roles foreach (var a in roles) { var role = _seminarRoleRepository.GetNullableById(a); if (role != null && !existingRoles.Contains(a)) { reg.SeminarRoles.Add(role); } } // remove the ones they shouldn't have var remove = reg.SeminarRoles.Where(a => !roles.ToList().Contains(a.Id)).ToList(); foreach (var a in remove) { reg.SeminarRoles.Remove(a); } Repository.OfType <SeminarPerson>().EnsurePersistent(reg); Message = string.Format(Messages.Saved, "Seminar Roles"); var url = Url.Action("AdminEdit", new { id = person.User.Id, seminarId = seminarId }); return(Redirect(string.Format("{0}#roles", url))); }
public ActionResult ColumnPreferences(string id, bool fromList = false) { var columnPreferences = _columnPreferencesRepository.GetNullableById(id) ?? new ColumnPreferences(id); if (fromList) { ViewBag.FromList = true; } else { ViewBag.FromList = false; } return(View(columnPreferences)); }
public JsonNetResult SetAwayStatus(string userId, DateTime awayUntil) { var user = _userRepository.GetNullableById(userId); if (user == null) { return(new JsonNetResult(null)); } user.AwayUntil = awayUntil; _userRepository.EnsurePersistent(user); return(new JsonNetResult(awayUntil.Date > DateTime.UtcNow.ToPacificTime().Date)); }
public ActionResult SteeringCommittee() { var seminar = SiteService.GetLatestSeminar(Site); var role = _seminarRoleRepository.GetNullableById(StaticIndexes.Role_SteeringCommittee); if (seminar != null && role != null) { var committee = seminar.SeminarPeople.Where(a => a.SeminarRoles.Contains(role)).OrderBy(a => a.Person.LastName); return(View(committee.Select(a => new DisplayPerson() { Firm = a.Firm, Person = a.Person, Title = a.Title, Seminar = seminar }).ToList())); } return(View()); }
/// <summary> /// Display details for an org that a user has access to. /// </summary> /// <param name="id">Organization id</param> /// <returns></returns> public ActionResult Details(string id) { var org = _organizationRepository.GetNullableById(id); var message = string.Empty; if (!_securityService.HasWorkgroupOrOrganizationAccess(null, org, out message)) { return(new HttpUnauthorizedResult(message)); } //var adminOrg = _queryRepositoryFactory.AdminOrgRepository.Queryable.Where(a => a.AccessUserId == CurrentUser.Identity.Name && a.IsActive && a.OrgId == id).Select(a => a.OrgId).FirstOrDefault(); //var org = _organizationRepository.GetNullableById(adminOrg); //if (org == null) //{ // return RedirectToAction("NotAuthorized", "Error"); //} return(View(org)); }
private void UpdateAssistant(Person person, Application application) { // transfer the assistant information var assistantType = _contactTypeRepository.GetNullableById('A'); var assistant = person.Contacts.Where(a => a.ContactType == assistantType).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(application.AssistantFirstName) && !string.IsNullOrWhiteSpace(application.AssistantLastName) && (!string.IsNullOrWhiteSpace(application.AssistantPhone) || !string.IsNullOrWhiteSpace(application.AssistantEmail))) { if (assistant != null) { assistant.FirstName = application.AssistantFirstName; assistant.LastName = application.AssistantLastName; assistant.Email = application.AssistantEmail; assistant.Phone = application.AssistantPhone; } else { var newAssistant = new Contact(application.AssistantFirstName, application.AssistantLastName, application.AssistantPhone, assistantType, person); newAssistant.Email = application.AssistantEmail; person.AddContact(newAssistant); } } }
public ActionResult AddPeople(int id, WizardWorkgroupPeoplePostModel workgroupPeoplePostModel, string roleFilter, string bulkEmail, string bulkKerb) { var notAddedKvp = new List <KeyValuePair <string, string> >(); var workgroup = _workgroupRepository.GetNullableById(id); if (workgroup == null) { Message = "Workgroup not found."; this.RedirectToAction <WorkgroupController>(a => a.Index(false)); } if (workgroupPeoplePostModel.Users == null) { workgroupPeoplePostModel.Users = new List <string>(); } ModelState.Clear(); workgroupPeoplePostModel.Role = _roleRepository.Queryable.FirstOrDefault(a => a.Id == roleFilter); //Ensure role picked is valid. if (workgroupPeoplePostModel.Role != null) { if (!_roleRepository.Queryable.Any(a => !a.IsAdmin && a.Id == workgroupPeoplePostModel.Role.Id)) { ModelState.AddModelError("Role", "Invalid Role Selected - don't mess with the query string!"); } } if (!ModelState.IsValid) { var viewModel = WorgroupPeopleCreateModel.Create(_roleRepository, workgroup); if (workgroupPeoplePostModel.Role != null) { viewModel.Role = workgroupPeoplePostModel.Role; } if (workgroupPeoplePostModel.Users != null && workgroupPeoplePostModel.Users.Count > 0) { var users = new List <IdAndName>(); foreach (var user in workgroupPeoplePostModel.Users) { var temp = _userRepository.GetNullableById(user); if (temp != null) { users.Add(new IdAndName(temp.Id, temp.FullName)); } else { var ldapuser = _searchService.FindUser(user); if (ldapuser != null) { users.Add(new IdAndName(ldapuser.LoginId, string.Format("{0} {1}", ldapuser.FirstName, ldapuser.LastName))); } } } viewModel.Users = users; } ViewBag.rolefilter = roleFilter; if (!string.IsNullOrWhiteSpace(roleFilter)) { viewModel.Role = _roleRepository.Queryable.SingleOrDefault(a => !a.IsAdmin && a.Id == roleFilter); } if (viewModel.Role.Level == 0) { ViewBag.StepNumber = 3 + (5 - 1); // Ugliness because a reviewer is level zero } else { ViewBag.StepNumber = 3 + (viewModel.Role.Level - 1); } return(View(viewModel)); } int successCount = 0; int failCount = 0; int duplicateCount = 0; foreach (var u in workgroupPeoplePostModel.Users) { successCount = _workgroupService.TryToAddPeople(id, workgroupPeoplePostModel.Role, workgroup, successCount, u, ref failCount, ref duplicateCount, notAddedKvp); } #region Bulk Load Email successCount = _workgroupService.TryBulkLoadPeople(bulkEmail, true, id, workgroupPeoplePostModel.Role, workgroup, successCount, ref failCount, ref duplicateCount, notAddedKvp); //const string regexPattern = @"\b[A-Z0-9._-]+@[A-Z0-9][A-Z0-9.-]{0,61}[A-Z0-9]\.[A-Z.]{2,6}\b"; //// Find matches //System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(bulkEmail, regexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); //foreach(System.Text.RegularExpressions.Match match in matches) //{ // var temp = match.ToString().ToLower(); // successCount = _workgroupService.TryToAddPeople(id, workgroupPeoplePostModel.Role, workgroup, successCount, temp, ref failCount, notAddedKvp); //} #endregion #region Bulk Load Kerb successCount = _workgroupService.TryBulkLoadPeople(bulkKerb, false, id, workgroupPeoplePostModel.Role, workgroup, successCount, ref failCount, ref duplicateCount, notAddedKvp); //const string regexPattern4Kerb = @"\b[A-Z0-9]{2,10}\b"; //// Find matches //System.Text.RegularExpressions.MatchCollection matchesKerb = System.Text.RegularExpressions.Regex.Matches(bulkKerb, regexPattern4Kerb, System.Text.RegularExpressions.RegexOptions.IgnoreCase); //foreach(System.Text.RegularExpressions.Match match in matchesKerb) //{ // var temp = match.ToString().ToLower(); // successCount = _workgroupService.TryToAddPeople(id, workgroupPeoplePostModel.Role, workgroup, successCount, temp, ref failCount, notAddedKvp); //} #endregion Message = string.Format("Successfully added {0} people to workgroup as {1}. {2} not added because of duplicated role or not found.", successCount, workgroupPeoplePostModel.Role.Name, failCount); if (failCount > 0 || successCount == 0) { if (failCount == 0) { ModelState.AddModelError("Users", "Must add at least 1 user or Skip"); } else if (failCount == duplicateCount) { Message = string.Format("The {0} users you added already have the role {1}", duplicateCount, workgroupPeoplePostModel.Role.Name); return(this.RedirectToAction(a => a.People(id, workgroupPeoplePostModel.Role.Id))); } var viewModel = WorgroupPeopleCreateModel.Create(_roleRepository, workgroup); viewModel.ErrorDetails = notAddedKvp; // ViewBag.DetailedMessage = notAddedSb.ToString(); ViewBag.rolefilter = roleFilter; if (!string.IsNullOrWhiteSpace(roleFilter)) { viewModel.Role = _roleRepository.Queryable.SingleOrDefault(a => !a.IsAdmin && a.Id == roleFilter); } if (viewModel.Role.Level == 0) { ViewBag.StepNumber = 3 + (5 - 1); // Ugliness because a reviewer is level zero } else { ViewBag.StepNumber = 3 + (viewModel.Role.Level - 1); } return(View(viewModel)); } Message = string.Format("Successfully added {0} people to workgroup as {1}.", successCount, workgroupPeoplePostModel.Role.Name); return(this.RedirectToAction(a => a.People(id, workgroupPeoplePostModel.Role.Id))); }
public void SetupDataForPeopleList() { #region Setup Roles var roles = new List <Role>(); SetupRoles(roles); #endregion Setup Roles #region Setup Users var users = new List <User>(); for (int i = 0; i < 6; i++) { users.Add(CreateValidEntities.User(i + 1)); users[i].SetIdTo((i + 1).ToString()); } new FakeUsers(0, UserRepository, users, true); #endregion Setup Users #region Setup Workgroups new FakeWorkgroups(3, WorkgroupRepository); #endregion Setup Workgroups #region Setup WorkgroupPermissions var workgroupPermissions = new List <WorkgroupPermission>(); for (int i = 0; i < 18; i++) { workgroupPermissions.Add(new WorkgroupPermission()); workgroupPermissions[i].Role = roles[(i % 6)]; workgroupPermissions[i].User = users[(i % 6)]; workgroupPermissions[i].Workgroup = WorkgroupRepository.GetNullableById((i / 6) + 1); } for (int i = 0; i < 3; i++) { workgroupPermissions.Add(new WorkgroupPermission()); workgroupPermissions[i + 18].Workgroup = WorkgroupRepository.GetNullableById(3); workgroupPermissions[i + 18].User = users[2]; } workgroupPermissions[18].Role = RoleRepository.GetNullableById(Role.Codes.Approver); workgroupPermissions[19].Role = RoleRepository.GetNullableById(Role.Codes.AccountManager); workgroupPermissions[20].Role = RoleRepository.GetNullableById(Role.Codes.Purchaser); new FakeWorkgroupPermissions(0, WorkgroupPermissionRepository, workgroupPermissions); #endregion Setup WorkgroupPermissions }
public ActionResult ModifyDepartmental(DepartmentalAdminModel departmentalAdminModel, List <string> orgs) { if (orgs == null || orgs.Count == 0) { ModelState.AddModelError("User.Organizations", "You must select at least one department for a departmental Admin."); } if (!ModelState.IsValid) { return(View(departmentalAdminModel)); } var user = _userRepository.GetNullableById(departmentalAdminModel.User.Id) ?? new User(departmentalAdminModel.User.Id); departmentalAdminModel.User.Roles = user.Roles; //Mapper.Map(departmentalAdminModel.User, user); // This was causing problems if an existing DA was saved. user.FirstName = departmentalAdminModel.User.FirstName; user.LastName = departmentalAdminModel.User.LastName; user.Email = departmentalAdminModel.User.Email; user.IsActive = departmentalAdminModel.User.IsActive; var isDeptAdmin = user.Roles.Any(x => x.Id == Role.Codes.DepartmentalAdmin); var isSscAdmin = user.Roles.Any(x => x.Id == Role.Codes.SscAdmin); if (!isDeptAdmin) { user.Roles.Add(_roleRepository.GetById(Role.Codes.DepartmentalAdmin)); } user.Organizations = new List <Organization>(); foreach (var org in orgs) { user.Organizations.Add(_organizationRepository.Queryable.Single(a => a.Id == org)); } _userRepository.EnsurePersistent(user); // invalid the cache for the user that was just given permissions _userIdentity.RemoveUserRoleFromCache(Resources.Role_CacheId, user.Id); if (isSscAdmin && departmentalAdminModel.UpdateAllSscAdmins) { var userList = new List <string>(); var users = _roleRepository.Queryable.Where(x => x.Id == Role.Codes.SscAdmin).SelectMany(x => x.Users).Where(w => w.IsActive && w.Id != user.Id).ToList(); foreach (var user1 in users) { user1.Organizations = new List <Organization>(); foreach (var org in orgs) { user1.Organizations.Add(_organizationRepository.Queryable.Single(a => a.Id == org)); } _userRepository.EnsurePersistent(user1); // invalid the cache for the user that was just given permissions _userIdentity.RemoveUserRoleFromCache(Resources.Role_CacheId, user1.Id); userList.Add(user1.FullNameAndId); } Message = string.Format( "{0} was added as a departmental admin to the specified organization(s) Also added perms for {1}.", user.FullNameAndId, string.Join(",", userList.ToArray())); } else { Message = string.Format("{0} was added as a departmental admin to the specified organization(s)", user.FullNameAndId); } return(this.RedirectToAction(a => a.Index())); }
public ActionResult Create(int?workgroupId, string orgId, ConditionalApprovalModifyModel modifyModel) { if (workgroupId.HasValue) { ViewBag.WorkgroupId = workgroupId.Value; modifyModel.ApprovalType = WorkgroupType; modifyModel.Workgroup = _workgroupRepository.GetNullableById(workgroupId.Value); var workgroup = _workgroupRepository.Queryable.Single(a => a.Id == workgroupId.Value); if (workgroup.Administrative) { ErrorMessage = "Conditional Approval may not be added to an administrative workgroup."; return(this.RedirectToAction <WizardController>(a => a.Details(workgroup.Id))); } } else if (!string.IsNullOrWhiteSpace(orgId)) { modifyModel.ApprovalType = OrganizationType; modifyModel.Organization = _organizationRepository.GetNullableById(orgId); ViewBag.OrganizationId = orgId; } var primaryApproverInDb = GetUserBySearchTerm(modifyModel.PrimaryApprover); var secondaryApproverInDb = string.IsNullOrWhiteSpace(modifyModel.SecondaryApprover) ? null : GetUserBySearchTerm(modifyModel.SecondaryApprover); if (primaryApproverInDb == null) { DirectoryUser primaryApproverInLdap = _directorySearchService.FindUser(modifyModel.PrimaryApprover); if (primaryApproverInLdap == null) { ModelState.AddModelError("primaryapprover", "No user could be found with the kerberos or email address entered"); } else //found the primary approver in ldap { primaryApproverInDb = new User(primaryApproverInLdap.LoginId) { FirstName = primaryApproverInLdap.FirstName, LastName = primaryApproverInLdap.LastName, Email = primaryApproverInLdap.EmailAddress, IsActive = true }; _userRepository.EnsurePersistent(primaryApproverInDb, forceSave: true); } } if (!string.IsNullOrWhiteSpace(modifyModel.SecondaryApprover)) //only check if a value was provided { if (secondaryApproverInDb == null) { DirectoryUser secondaryApproverInLdap = _directorySearchService.FindUser(modifyModel.SecondaryApprover); if (secondaryApproverInLdap == null) { ModelState.AddModelError("secondaryapprover", "No user could be found with the kerberos or email address entered"); } else //found the secondary approver in ldap { secondaryApproverInDb = new User(secondaryApproverInLdap.LoginId) { FirstName = secondaryApproverInLdap.FirstName, LastName = secondaryApproverInLdap.LastName, Email = secondaryApproverInLdap.EmailAddress, IsActive = true }; _userRepository.EnsurePersistent(secondaryApproverInDb, forceSave: true); } } } if (!ModelState.IsValid) { return(View(CreateModifyModel(modifyModel.ApprovalType, modifyModel))); } Check.Require(modifyModel.Workgroup != null || modifyModel.Organization != null, "Must have a Workgroup or an Organization"); var newConditionalApproval = new ConditionalApproval { Question = modifyModel.Question, Organization = modifyModel.Organization, Workgroup = modifyModel.Workgroup, PrimaryApprover = primaryApproverInDb, SecondaryApprover = secondaryApproverInDb }; _conditionalApprovalRepository.EnsurePersistent(newConditionalApproval); Message = "Conditional approval added successfully"; if (workgroupId.HasValue) { return(this.RedirectToAction(a => a.ByWorkgroup(workgroupId.Value))); } if (!string.IsNullOrWhiteSpace(orgId)) { return(this.RedirectToAction(a => a.ByOrg(orgId))); } //return this.RedirectToAction(a => a.Index()); return(this.RedirectToAction <ErrorController>(a => a.Index())); }
/// <summary> /// /// </summary> /// <param name="id">Workgroup Id</param> /// <param name="role">Role being for people being added</param> /// <param name="workgroup">workgroup</param> /// <param name="successCount">how many have already been successfully added</param> /// <param name="lookupUser">user being added</param> /// <param name="failCount">count of number not added</param> /// <param name="notAddedKvp">list of users not added and reason why.</param> /// <returns></returns> public int TryToAddPeople(int id, Role role, Workgroup workgroup, int successCount, string lookupUser, ref int failCount, ref int duplicateCount, List <KeyValuePair <string, string> > notAddedKvp) { var saveParm = lookupUser; var user = _userRepository.GetNullableById(lookupUser); if (user == null) { var ldapuser = _searchService.FindUser(lookupUser); if (ldapuser != null) { lookupUser = ldapuser.LoginId; user = _userRepository.GetNullableById(ldapuser.LoginId); if (user == null) { user = new User(ldapuser.LoginId); user.Email = ldapuser.EmailAddress; user.FirstName = ldapuser.FirstName; user.LastName = ldapuser.LastName; _userRepository.EnsurePersistent(user); var emailPrefs = new EmailPreferences(user.Id); _emailPreferencesRepository.EnsurePersistent(emailPrefs); } } } if (user == null) { //notAddedSb.AppendLine(string.Format("{0} : Not found", saveParm)); notAddedKvp.Add(new KeyValuePair <string, string>(saveParm, "Not found")); failCount++; return(successCount); } if (!_workgroupPermissionRepository.Queryable.Any(a => a.Role == role && a.User == user && a.Workgroup == workgroup && a.IsAdmin == false)) { var workgroupPermission = new WorkgroupPermission(); workgroupPermission.Role = role; workgroupPermission.User = _userRepository.GetNullableById(lookupUser); workgroupPermission.Workgroup = _workgroupRepository.GetNullableById(id); _workgroupPermissionRepository.EnsurePersistent(workgroupPermission); if (workgroup.Administrative) { var ids = GetChildWorkgroups(workgroup.Id); foreach (var childid in ids) { var childWorkgroup = _workgroupRepository.Queryable.Single(a => a.Id == childid); if (!_workgroupPermissionRepository.Queryable.Any(a => a.Workgroup == childWorkgroup && a.Role == role && a.User == user && a.IsAdmin && a.ParentWorkgroup == workgroup)) { Check.Require(role.Id != Role.Codes.Requester); var childPermission = new WorkgroupPermission(); childPermission.Role = role; childPermission.User = workgroupPermission.User; childPermission.Workgroup = childWorkgroup; childPermission.IsAdmin = true; childPermission.IsFullFeatured = workgroup.IsFullFeatured; childPermission.ParentWorkgroup = workgroup; _workgroupPermissionRepository.EnsurePersistent(childPermission); } } } // invalid the cache for the user that was just given permissions _userIdentity.RemoveUserRoleFromCache(Resources.Role_CacheId, workgroupPermission.User.Id); successCount++; } else { //notAddedSb.AppendLine(string.Format("{0} : Is a duplicate", lookupUser)); notAddedKvp.Add(new KeyValuePair <string, string>(lookupUser, "Is a duplicate")); failCount++; duplicateCount++; } return(successCount); }
// Create or update the person's business address if exists private void UpdateAddress(Person person, Application application) { // check if the person already has the address var address = person.Addresses.Where(a => a.AddressType.Id == StaticIndexes.Address_Business.ToCharArray()[0]).FirstOrDefault(); if (address == null) { address = new Address(application.FirmAddressLine1, application.FirmAddressLine2, application.FirmCity, application.FirmState, application.FirmZip, _addressTypeRepository.GetNullableById(StaticIndexes.Address_Business.ToCharArray()[0]), person); person.AddAddress(address); } else { // update the existing address address.Line1 = application.FirmAddressLine1; address.Line2 = application.FirmAddressLine2; address.City = application.FirmCity; address.State = application.FirmState; address.Zip = application.FirmZip; } }