private async Task CreateNotificationForHoliday(string holidayName) { var admin = await userServices .GetUsersInRole(Enum.GetName(typeof(Role), Role.Administrator)) .FirstOrDefaultAsync(); NotificationCreateViewModel notification = new NotificationCreateViewModel { NotificationTypeId = (int)NotificationType.Holiday, NotificationText = "Днес се празнува - " + holidayName }; if (admin != null) { await notificationServices.CreateGlobalNotification(notification, admin.Id); } else { var agentIds = await dbContext.Users.OfType <AgentUsers>() .Select(a => a.Id) .ToListAsync(); foreach (var agentId in agentIds) { await notificationServices.CreateIndividualNotification(notification, agentId); } } }
public async Task NotifyForAppointments() { var appointmentsToBeNotified = await unitOfWork.AppointmentsRepository .Include(a => a.IssuerUser) .Where(a => a.CreatedOn.Year == DateTime.Now.Year && a.CreatedOn.Month == DateTime.Now.Month && a.CreatedOn.Day == DateTime.Now.Day) .ToListAsync(); foreach (var appointment in appointmentsToBeNotified) { var appointmentIssuerName = string.IsNullOrEmpty(appointment.IssuerUser.FirstName) && string.IsNullOrEmpty(appointment.IssuerUser.FirstName) ? appointment.IssuerUser.UserName : appointment.IssuerUser.FirstName + appointment.IssuerUser.LastName; NotificationCreateViewModel notification = new NotificationCreateViewModel { NotificationTypeId = (int) NotificationType.Calendar, NotificationPicture = null, NotificationText = "Имате уговорка в " + appointment.AppointmentDate.ToString("dd.MM.yyyy hh:mm") + " с " + appointmentIssuerName + " телефон:" + appointment.IssuerUser.PhoneNumber }; await notificationServices.CreateIndividualNotification(notification, appointment.AgentId); } }
public ActionResult Reply(int?id) { if (id == null) { return(HttpBadRequest("Notification id is null")); } Notification notification = null; if (User.IsInRole("SystemAdmin")) { notification = GStoreDb.Notifications.SingleOrDefault(n => n.NotificationId == id); } else { UserProfile userProfile = CurrentUserProfileOrThrow; notification = GStoreDb.Notifications.Where(n => (n.ToUserProfileId == userProfile.UserProfileId) && (n.NotificationId == id)).SingleOrDefault(); } if (notification == null) { return(HttpNotFound()); } NotificationCreateViewModel viewModel = new NotificationCreateViewModel(); viewModel.StartReply(notification); ViewBag.ToUserProfileId = AllowedToProfiles(); ViewBag.Importance = ImportanceItems(); return(View("Create", viewModel)); }
public async Task CreateGlobalNotification(NotificationCreateViewModel model, string userCreatorId) { if (!await IsUserExisting(userCreatorId)) { throw new ArgumentException("Потребителят, за който се създава известието не е намерен!"); } if (!await unitOfWork.NotificationsRepository.ExistType(model.NotificationTypeId)) { throw new ArgumentException("Не е намерен типът на нотификацията!"); } Notifications notification = new Notifications { IsGlobal = true, NotificationLink = model.NotificationLink, NotificationText = model.NotificationText, NotificationPicture = model.NotificationPicture, TypeId = model.NotificationTypeId, IsSeen = false, IsClicked = false, UserCreatorId = userCreatorId }; unitOfWork.NotificationsRepository.Add(notification); await unitOfWork.SaveAsync(); }
public async Task <PropertySearchListViewModel> CreateAsync(PropertySearchCreateViewModel model, string agentId) { if (string.IsNullOrEmpty(agentId)) { throw new ArgumentException("Не е установен брокерът задаващ въпроса!"); } if (!(await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Agent)) || await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Administrator)))) { throw new NotAuthorizedUserException("Потребителят няма право на това действие! Само админи и брокери имат достъп !"); } PropertySearches propertySearch = new PropertySearches { CityId = model.CityId, AdditionalInformation = model.AdditionalInformation, AgentId = agentId, AreaInSquareMeters = model.AreaInSquareMeters, Areas = model.Areas, IsRentSearch = model.IsRentSearch, PriceFrom = model.PriceFrom, PriceTo = model.PriceTo, UnitTypes = new HashSet <PropertyTypes>(await _dbContext.PropertyTypes .Where(pt => model.UnitTypeIds.Any(ut => pt.PropertyTypeId == ut)) .ToListAsync()), PersonSearcher = new PersonSearcher { Name = model.PersonSearcher.Name, PhoneNumber = model.PersonSearcher.PhoneNumber, Email = model.PersonSearcher.Email, AdditionalInformation = model.PersonSearcher.AdditionalInformation } }; _dbContext.PropertySearches.Add(propertySearch); await _dbContext.SaveChangesAsync(); #region Create notification var creatorName = await _dbContext.Users .Where(u => u.Id == propertySearch.AgentId) .Select(a => a.FirstName + " " + a.LastName) .FirstOrDefaultAsync(); var notificationToCreate = new NotificationCreateViewModel { NotificationTypeId = (int)NotificationType.Property, NotificationLink = "/propertysearches/details?id=" + propertySearch.Id, NotificationText = creatorName + " добави търсене на имот с цена " + propertySearch.PriceFrom + "лв." + " - " + propertySearch.PriceTo + "лв." }; await _notificationCreator.CreateGlobalNotification(notificationToCreate, propertySearch.AgentId); #endregion return(await GetAsync(propertySearch.Id)); }
public async Task <IHttpActionResult> Createnotification() { ResponseDataDTO <notification> response = new ResponseDataDTO <notification>(); try { var path = Path.GetTempPath(); if (!Request.Content.IsMimeMultipartContent("form-data")) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType)); } MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(path); await Request.Content.ReadAsMultipartAsync(streamProvider); // get data from formdata NotificationCreateViewModel notificationCreateViewModel = new NotificationCreateViewModel { ntf_title = Convert.ToString(streamProvider.FormData["ntf_title"]), ntf_description = Convert.ToString(streamProvider.FormData["ntf_description"]), ntf_datetime = Convert.ToDateTime(streamProvider.FormData["ntf_datetime"]), ntf_confim_datetime = Convert.ToDateTime(streamProvider.FormData["ntf_confim_datetime"]), staff_id = Convert.ToInt32(streamProvider.FormData["staff_id"]), }; // mapping view model to entity var creatednotification = _mapper.Map <notification>(notificationCreateViewModel); // save new notification _notificationservice.Create(creatednotification); // return response response.Code = HttpCode.OK; response.Message = MessageResponse.SUCCESS; response.Data = creatednotification; return(Ok(response)); } catch (Exception ex) { response.Code = HttpCode.INTERNAL_SERVER_ERROR; response.Message = ex.Message; response.Data = null; Console.WriteLine(ex.ToString()); return(Ok(response)); } }
public async Task <TrainingListViewModel> EditAsync(TrainingEditViewModel model, string adminId) { if (string.IsNullOrEmpty(adminId)) { throw new ArgumentException("Не е намерен администартора, който редактира Обучение!"); } if (!await _userManager.IsInRoleAsync(adminId, Enum.GetName(typeof(Role), Role.Administrator))) { throw new NotAuthorizedUserException("Потребителят няма право на това действие! Само админи имат право да редактират обучения !"); } var trainingToEdit = await _dbContext.Trainings .FirstOrDefaultAsync(t => t.Id == model.Id) ?? throw new ContentNotFoundException("Не е намерено обучението, което искате да редактирате!"); if (model.TrainingDate == null) { throw new ArgumentException("Не е въведена дата на обучението!"); } var oldThemeName = trainingToEdit.TrainingTheme; var oldThemeDate = trainingToEdit.TrainingDate; _dbContext.Trainings.Attach(trainingToEdit); trainingToEdit.TrainingDate = (DateTime)model.TrainingDate; trainingToEdit.AdditionalDescription = model.AdditionalDescription; trainingToEdit.TrainingTheme = model.TrainingTheme; trainingToEdit.TrainingMaterialsFolderLink = model.TrainingMaterialsFolderLink; await _dbContext.SaveChangesAsync(); #region notification var notificationToCreate = new NotificationCreateViewModel { NotificationTypeId = (int)NotificationType.Learning, NotificationLink = "/trainings/index?trainingId=" + model.Id, NotificationText = "Обучението на тема: " + oldThemeName + " от " + oldThemeDate.ToString("dddd, dd.MM.yyyyг. hh:mmч.") + "е преместено в " + ((DateTime)(model.TrainingDate)).ToString("dddd, dd.MM.yyyyг. hh:mmч.") + " с тема: " + model.TrainingTheme }; await _notificationCreator.CreateGlobalNotification(notificationToCreate, adminId); #endregion return(await Get(trainingToEdit.Id)); }
public async Task <TrainingListViewModel> CreateAsync(TrainingCreateViewModel model, string adminId) { if (string.IsNullOrEmpty(adminId)) { throw new ArgumentException("Не е намерен администартора, който създава Обучение!"); } if (!await _userManager.IsInRoleAsync(adminId, Enum.GetName(typeof(Role), Role.Administrator))) { throw new NotAuthorizedUserException("Потребителят няма право на това действие! Само админи имат право да създават обучения !"); } if (model.TrainingDate == null) { throw new ArgumentException("Не е въведена дата на обучението!"); } var training = new Model.Trainings { TrainingDate = (DateTime)model.TrainingDate, TrainingTheme = model.TrainingTheme, AdditionalDescription = model.AdditionalDescription, TrainingMaterialsFolderLink = model.TrainingMaterialsFolderLink }; _dbContext.Trainings.Add(training); await _dbContext.SaveChangesAsync(); #region notification var notificationToCreate = new NotificationCreateViewModel { NotificationTypeId = (int)NotificationType.Learning, NotificationLink = "/trainings/index?trainingId=" + training.Id, NotificationText = "Ще се проведе обучение на тема: " + training.TrainingTheme + " в " + training.TrainingDate.ToString("dddd, dd.MM.yyyyг. hh:mmч.") }; await _notificationCreator.CreateGlobalNotification(notificationToCreate, adminId); #endregion return(await Get(training.Id)); }
public async Task <AgentQuestionListViewModel> Create(string question, string agentId) { if (string.IsNullOrEmpty(question)) { throw new ArgumentException("Не е въведен въпрос!"); } if (string.IsNullOrEmpty(agentId)) { throw new ArgumentException("Не е намерен брокерът задаващ въпроса в системата!"); } var questionToCreate = new Model.AgentQuestions.AgentQuestions { Question = question, AgentId = agentId }; _dbContext.AgentQuestions.Add(questionToCreate); await _dbContext.SaveChangesAsync(); var createdQuestion = await Get(questionToCreate.Id, agentId); #region Create Notification var notificationToCreate = new NotificationCreateViewModel { NotificationTypeId = (int)NotificationType.Question, NotificationPicture = "", NotificationLink = "/agentquestions/index?questionId=" + createdQuestion.Id, NotificationText = createdQuestion.AskingAgentName + " пита: " + createdQuestion.Question }; await _notificationCreator.CreateGlobalNotification(notificationToCreate, agentId); #endregion return(createdQuestion); }
/// <summary> /// Create post /// </summary> /// <param name="model"></param> /// <param name="postCreatorId"></param> /// <returns></returns> public async Task <PostDetailViewModel> Create(PostCreateViewModel model, string postCreatorId) { //Does the user exist in the db if (!await userManager.Users.AnyAsync(u => u.Id == postCreatorId)) { throw new ArgumentException("Не е намерен потребителят с който сте логнати!"); } if (!await ThemesManager.Exists(model.ThemeId)) { throw new ArgumentException("Не е намерена темата в която искате да създадете пост!"); } var postToCreate = Mapper.Map <Posts>(model, opts => opts.Items.Add("UserId", postCreatorId)); postToCreate.Tags = new HashSet <Tags>(model.Tags.Select(t => new Tags { Name = t }).ToList()); unitOfWork.PostsRepository.Add(postToCreate); await unitOfWork.SaveAsync(); var postRelativeDirPath = Path.Combine(ConfigurationManager.AppSettings["BlogPostFolderRelativePath"], postToCreate.PostId.ToString()); var postPhysicalDirPath = Path.Combine(HttpRuntime.AppDomainAppPath.TrimEnd('\\'), postRelativeDirPath.TrimStart('\\')); Directory.CreateDirectory(postPhysicalDirPath); try { foreach (HttpPostedFileBase image in model.ImageFiles) { if (image == null) { continue; } var imagePath = Path.Combine(postPhysicalDirPath, image.FileName); ImageHelpers.SaveImage(image, imagePath); ImageHelpers.SaveAsWebP(image, imagePath); var imageRelPath = Path.Combine(postRelativeDirPath, image.FileName); postToCreate.Images.Add(new PostImages { ImagePath = imageRelPath }); } //This edit is cuz, we first add the property and use its id for the images Directory unitOfWork.PostsRepository.Edit(postToCreate); await unitOfWork.SaveAsync(); var post = Mapper.Map <PostDetailViewModel>(postToCreate); #region Notifications var notificationToCreate = new NotificationCreateViewModel { NotificationTypeId = (int)NotificationType.Post, NotificationPicture = post.ImageUrls.Any() ? post.ImageUrls[0] : "", NotificationLink = "/posts/details?id=" + post.PostId, NotificationText = post.AuthorName + " публикува пост: " + post.Title }; await _notificationCreator.CreateGlobalNotification(notificationToCreate, postCreatorId); #endregion return(post); } catch (Exception e) { //if something wrong delete the post from db and filesystem unitOfWork.PostsRepository.Delete(postToCreate); await unitOfWork.SaveAsync(); Directory.Delete(postPhysicalDirPath, true); throw; } }
//Work well public async Task <EditRentalInfoForPropertyViewModel> CreateRentalInfo(CreateRentalInfoViewModel rentalInfoToAddInProperty, string loggedUserId) { if (string.IsNullOrEmpty(loggedUserId)) { throw new ArgumentNullException(nameof(loggedUserId)); } var property = await unitOfWork.PropertiesRepository .Include(p => p.Images) .Where(p => p.Id == rentalInfoToAddInProperty.PropertyId) .FirstOrDefaultAsync() ?? throw new ContentNotFoundException("Имотът не е намерен!"); if (property.OwnerId != loggedUserId && property.AgentId != loggedUserId && !await userManager.IsInRoleAsync(loggedUserId, "Administrator")) { throw new NotAuthorizedException("Нямате право да създавате части в този имот!"); } var areaInSquareFt = rentalInfoToAddInProperty.Attributes .Where(a => a.Key == AttributesResolvers.AreaInSquareMetersAttribute) .Select(a => a.Value) .FirstOrDefault(); int?areaFinal = int.TryParse(areaInSquareFt, out var tempArea) ? tempArea : (int?)null; RentalsInfo rental = new RentalsInfo { PropertyId = rentalInfoToAddInProperty.PropertyId, RentalPrice = rentalInfoToAddInProperty.RentalPrice, RentalPricePeriodId = rentalInfoToAddInProperty.RentalPricePeriodId, UnitCount = rentalInfoToAddInProperty.UnitsCount, UnitTypeId = rentalInfoToAddInProperty.UnitTypeId, AdditionalDescription = rentalInfoToAddInProperty.AdditionalInfo, AreaInSquareMeters = areaFinal, Attributes = new HashSet <KeyValuePairs>(rentalInfoToAddInProperty.Attributes .Select(a => AttributesResolvers.AttributesResolver(a.Key, a.Value)) .ToList()), Extras = new HashSet <Extras>(_extrasManager.GetRentalExtras(rentalInfoToAddInProperty .RentalExtras .Where(e => e.IsChecked) .Select(e => e.ExtraId) .ToList())) }; unitOfWork.RentalsRepository.Add(rental); await unitOfWork.SaveAsync(); #region Notifications var creatorName = await unitOfWork.UsersRepository .Where(u => u.Id == property.AgentId) .Select(a => a.FirstName + " " + a.LastName) .FirstOrDefaultAsync(); var notificationToCreate = new NotificationCreateViewModel { NotificationTypeId = (int)NotificationType.Property, NotificationPicture = property.Images.Select(i => i.ImagePath).FirstOrDefault(), NotificationLink = "/properties/details?id=" + rental.Id + "&isrentsearching=True", NotificationText = creatorName + " добави имот: " + property.PropertyName }; await _notificationCreator.CreateGlobalNotification(notificationToCreate, property.AgentId); #endregion return(new EditRentalInfoForPropertyViewModel { UnitCount = rental.UnitCount, UnitTypeId = rental.UnitTypeId, // ReSharper disable once PossibleInvalidOperationException // Rental Create ViewModel guarantee for value here RentalPrice = (decimal)rental.RentalPrice, RentalInfoId = rental.Id, // ReSharper disable once PossibleInvalidOperationException RentalPricePeriodId = (int)rental.RentalPricePeriodId, AdditionalInfo = rental.AdditionalDescription, Attributes = rental.Attributes.Select(ra => new AttributesKeyValueViewModel { Key = ra.Key, Value = ra.Value }).ToList(), RentalExtras = rental.Extras.Select(re => new ExtraCheckBoxViewModel { ExtraId = re.ExtraId, ExtraName = re.ExtraName, IsChecked = true }).ToList() }); }
public async Task <RecordListViewModel> CreateRecord(CreateRecordViewModel model, string agentId) { if (!await IsAgentExisting(agentId)) { throw new ArgumentException("Агентът, не е намерен!"); } var record = new ContactsDiary { Address = model.Address, AdditionalDescription = model.AdditionalDescription, AgentId = agentId, CityDistrict = model.CityDistrict, CityId = model.CityId, ContactedPersonTypeId = model.ContactedPersonTypeId, DealTypeId = model.DealTypeId, Name = model.Name, NegotiationStateId = model.NegotiationStateId, PhoneNumber = model.PhoneNumber, PropertySource = model.PropertySource, PropertyTypeId = model.PropertyTypeId }; dbContext.ContactsDiary.Add(record); await dbContext.SaveChangesAsync(); var createdClient = await dbContext.ContactsDiary .Include(r => r.Agent) .Include(r => r.NegotiationState) .Include(r => r.ContactedPersonType) .Include(r => r.DealType) .Include(r => r.PropertyType) .Where(c => c.Id == record.Id).Select(r => new RecordListViewModel { Id = r.Id, CreatedOn = r.CreatedOn, PhoneNumber = r.PhoneNumber, Name = r.Name, CityId = r.CityId, CityName = r.City.CityName, CityDistrict = r.CityDistrict, Address = r.Address, PropertySource = r.PropertySource, AdditionalDescription = r.AdditionalDescription, ContactedPersonTypeId = r.ContactedPersonTypeId, ContactedPersonType = r.ContactedPersonType.ContactedPersonType, DealTypeId = r.DealTypeId, DealType = r.DealType.DealType, PropertyTypeId = r.PropertyTypeId, PropertyType = r.PropertyType.PropertyTypeName, NegotiationStateId = r.NegotiationStateId, NegotiationState = r.NegotiationState.State, RecordColor = r.NegotiationState.Color, AgentId = r.AgentId, AgentName = r.Agent.FirstName + " " + r.Agent.LastName }) .FirstOrDefaultAsync() ?? throw new ContentNotFoundException("Не е намерен записът!"); #region Notifications var notificationToCreate = new NotificationCreateViewModel { NotificationTypeId = (int)NotificationType.Contact, NotificationPicture = "", NotificationLink = "/contactsdiary/index?contactId=" + record.Id, NotificationText = createdClient.AgentName + " добави контакт: " + createdClient.ContactedPersonType + " - тел:" + createdClient.PhoneNumber }; await notificationCreator.CreateGlobalNotification(notificationToCreate, agentId); #endregion return(createdClient); }
public async Task <FileListViewModel> Create(FileCreateViewModel model, string agentId) { if (string.IsNullOrEmpty(agentId)) { throw new NotAuthorizedUserException("Само потребители могат да качват файлове!"); } if (!await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Administrator)) && !await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Agent)) && !await _userManager.IsInRoleAsync(agentId, Enum.GetName(typeof(Role), Role.Maintenance))) { throw new NotAuthorizedUserException("Нямате право да извършвате това действие!"); } if (await Exist(fileName: model.Name, folderId: model.FolderId)) { throw new ArgumentException("Съществува файл с това име в тази папка!"); } string filePath = Path.GetFileNameWithoutExtension(model.Name) + Path.GetExtension(model.File.FileName); if (model.FolderId != null) { filePath = Path.Combine(await _dbContext.Folders .Where(f => f.Id == model.FolderId).Select(f => f.RelativePath) .FirstOrDefaultAsync() ?? "", filePath); } else { filePath = Path.Combine(_baseMaterialsPath, filePath); } var physicalFilePath = Path.Combine(HttpRuntime.AppDomainAppPath.TrimEnd('\\'), filePath.Replace('/', '\\').TrimStart('\\')); try { model.File.SaveAs(physicalFilePath); } catch (Exception) { Directory.CreateDirectory(Path.GetDirectoryName(physicalFilePath) ?? throw new ArgumentException("Пътят е грешен")); model.File.SaveAs(physicalFilePath); } var file = new Files { Name = Path.GetFileName(filePath), FolderId = model.FolderId, AgentId = agentId, SizeInBytes = model.File.ContentLength, Type = MimeMapping.GetMimeMapping(model.File.FileName), RelativePath = filePath }; try { _dbContext.Files.Add(file); await _dbContext.SaveChangesAsync(); } catch (Exception) { File.Delete(physicalFilePath); throw; } var createdFile = await Get(file.Id, agentId); #region Notifications var notificationToCreate = new NotificationCreateViewModel { NotificationTypeId = (int)NotificationType.Material, NotificationPicture = "", NotificationLink = "/agentmaterials/index?fileId=" + createdFile.Id + (createdFile.FolderId != null ? "&folderId=" + createdFile.FolderId : ""), NotificationText = createdFile.AgentName + " добави материал: " + createdFile.Name }; await _notificationCreator.CreateGlobalNotification(notificationToCreate, agentId); #endregion return(createdFile); }
public ActionResult Create(NotificationCreateViewModel data) { Order order = null; if (data.OrderId.HasValue) { //verify user has access to the order StoreFrontConfiguration storeFrontConfig = CurrentStoreFrontConfigOrThrow; StoreFront storeFront = storeFrontConfig.StoreFront; UserProfile profile = CurrentUserProfileOrNull; string trimmedEmail = (string.IsNullOrWhiteSpace(data.OrderEmail) ? "" : data.OrderEmail.Trim().ToLower()); if (profile == null) { order = storeFront.Orders.SingleOrDefault(o => o.OrderId == data.OrderId.Value && o.Email.ToLower() == trimmedEmail && o.UserProfileId == null); if (order == null) { return(HttpBadRequest("Anonymous order not found or not authorized for order id " + data.OrderId.Value + " with email: " + data.OrderEmail)); } } else { if (profile.AspNetIdentityUserIsInRoleSystemAdmin()) { order = storeFront.Orders.SingleOrDefault(o => o.OrderId == data.OrderId.Value); if (order == null) { return(HttpBadRequest("Sys Admin order not found order id " + data.OrderId.Value)); } } else if (storeFrontConfig.OrderAdmin_UserProfileId == profile.UserProfileId) { order = storeFront.Orders.SingleOrDefault(o => o.OrderId == data.OrderId.Value); if (order == null) { return(HttpBadRequest("Order Admin order not found order id " + data.OrderId.Value)); } } else { order = storeFront.Orders.SingleOrDefault(o => o.OrderId == data.OrderId.Value && o.UserProfileId == profile.UserProfileId); if (order == null) { return(HttpBadRequest("Logged in order not found or no access order id " + data.OrderId.Value)); } } } } UserProfile target = GStoreDb.UserProfiles.SingleOrDefault(prof => prof.UserProfileId == data.ToUserProfileId); if (target == null) { ModelState.AddModelError("", "Target recipient is not found. Please email the system administrator if you think this is an error."); } if (!User.IsInRole("SystemAdmin")) { if (!target.AllowUsersToSendSiteMessages) { ModelState.AddModelError("", "You are not authorized to send a message to the selected user. Please email the system administrator if you think this is an error."); } } if (!ModelState.IsValid) { ViewBag.Importance = ImportanceItems(); ViewBag.ToUserProfileId = AllowedToProfiles(); data.UpdateOrder(order); return(View(data)); } Notification notification = GStoreDb.Notifications.Create(); UserProfile sender = CurrentUserProfileOrThrow; notification.FromUserProfileId = sender.UserProfileId; notification.From = sender.FullName; notification.To = target.FullName; notification.Subject = data.Subject; notification.ToUserProfileId = data.ToUserProfileId; notification.Importance = data.Importance; notification.Message = data.Message; notification.UrlHost = Request.Url.Host; notification.Client = CurrentClientOrThrow; notification.StoreFront = CurrentStoreFrontOrThrow; notification.OrderId = data.OrderId; if (!Request.Url.IsDefaultPort) { notification.UrlHost += ":" + Request.Url.Port; } notification.BaseUrl = Url.Action("Details", "Notifications", new { id = "" }); List <NotificationLink> linkCollection = new List <NotificationLink>(); if (!string.IsNullOrWhiteSpace(data.Link1Url)) { if (string.IsNullOrWhiteSpace(data.Link1Text)) { data.Link1Text = data.Link1Url; } NotificationLink newLink1 = GStoreDb.NotificationLinks.Create(); newLink1.SetDefaultsForNew(notification); newLink1.Order = 1; newLink1.LinkText = data.Link1Text; newLink1.Url = data.Link1Url; if (data.Link1Url.StartsWith("/") || data.Link1Url.StartsWith("~/")) { newLink1.IsExternal = false; } else { newLink1.IsExternal = true; } linkCollection.Add(newLink1); } if (!string.IsNullOrWhiteSpace(data.Link2Url)) { if (string.IsNullOrWhiteSpace(data.Link2Text)) { data.Link2Text = data.Link2Url; } NotificationLink newLink2 = GStoreDb.NotificationLinks.Create(); newLink2.SetDefaultsForNew(notification); newLink2.Order = 2; newLink2.LinkText = data.Link2Text; newLink2.Url = data.Link2Url; if (data.Link2Url.StartsWith("/") || data.Link2Url.StartsWith("~/")) { newLink2.IsExternal = false; } else { newLink2.IsExternal = true; } linkCollection.Add(newLink2); } if (!string.IsNullOrWhiteSpace(data.Link3Url)) { if (string.IsNullOrWhiteSpace(data.Link3Text)) { data.Link3Text = data.Link3Url; } NotificationLink newLink3 = GStoreDb.NotificationLinks.Create(); newLink3.SetDefaultsForNew(notification); newLink3.Order = 3; newLink3.LinkText = data.Link3Text; newLink3.Url = data.Link3Url; if (data.Link3Url.StartsWith("/") || data.Link3Url.StartsWith("~/")) { newLink3.IsExternal = false; } else { newLink3.IsExternal = true; } linkCollection.Add(newLink3); } if (!string.IsNullOrWhiteSpace(data.Link4Url)) { if (string.IsNullOrWhiteSpace(data.Link4Text)) { data.Link4Text = data.Link4Url; } NotificationLink newLink4 = GStoreDb.NotificationLinks.Create(); newLink4.SetDefaultsForNew(notification); newLink4.Order = 4; newLink4.LinkText = data.Link4Text; newLink4.Url = data.Link4Url; if (data.Link4Url.StartsWith("/") || data.Link4Url.StartsWith("~/")) { newLink4.IsExternal = false; } else { newLink4.IsExternal = true; } linkCollection.Add(newLink4); } if (linkCollection.Count != 0) { notification.NotificationLinks = linkCollection; } notification.IsPending = false; notification.StartDateTimeUtc = DateTime.UtcNow; notification.EndDateTimeUtc = DateTime.UtcNow; GStoreDb.Notifications.Add(notification); GStoreDb.SaveChanges(); AddUserMessage("Message sent!", "Message sent to " + notification.To.ToHtml(), UserMessageType.Success); return(RedirectToAction("Index")); }
// GET: Notifications/Create public ActionResult Create(string orderNumber, string orderEmail) { NotificationCreateViewModel viewModel = new NotificationCreateViewModel(); if (!string.IsNullOrWhiteSpace(orderNumber)) { //verify user has access to the order StoreFrontConfiguration storeFrontConfig = CurrentStoreFrontConfigOrThrow; StoreFront storeFront = storeFrontConfig.StoreFront; UserProfile profile = CurrentUserProfileOrNull; string trimmedOrderNumber = orderNumber.Trim().ToLower(); string trimmedEmail = orderEmail.Trim().ToLower(); Order order = null; if (profile == null) { order = storeFront.Orders.SingleOrDefault(o => o.OrderNumber.ToLower() == trimmedOrderNumber && o.Email.ToLower() == trimmedEmail && o.UserProfileId == null); if (order == null) { return(HttpBadRequest("Anonymous order not found or not authorized for order #" + orderNumber + " with email: " + orderEmail)); } } else { if (profile.AspNetIdentityUserIsInRoleSystemAdmin()) { order = storeFront.Orders.SingleOrDefault(o => o.OrderNumber.ToLower() == trimmedOrderNumber); if (order == null) { return(HttpBadRequest("Sys Admin order not found order #" + orderNumber)); } } else if (storeFrontConfig.OrderAdmin_UserProfileId == profile.UserProfileId) { order = storeFront.Orders.SingleOrDefault(o => o.OrderNumber.ToLower() == trimmedOrderNumber); if (order == null) { return(HttpBadRequest("Order Admin order not found order id " + orderNumber)); } } else { order = storeFront.Orders.SingleOrDefault(o => o.OrderNumber.ToLower() == trimmedOrderNumber && o.UserProfileId == profile.UserProfileId); if (order == null) { return(HttpBadRequest("Logged in order not found or no access order #" + orderNumber)); } } } if (order != null) { viewModel.UpdateOrder(order); viewModel.OrderEmail = trimmedEmail; viewModel.Subject = "Question about order " + order.OrderNumber + " placed " + order.CreateDateTimeUtc.ToUserDateTimeString(profile, storeFrontConfig, storeFront.Client); } } ViewBag.Importance = ImportanceItems(); ViewBag.ToUserProfileId = AllowedToProfiles(); return(View(viewModel)); }