public IHttpActionResult Post(CreateNotificationModel model) { if (model.SendDate == null) { model.SendDate = DateTime.Now; } var user = db.User.Where(u => u.Id == model.UserId).FirstOrDefault(); if (user == null) { return(NotFound()); } var notification = new Model.Notification { UserId = model.UserId, Category = model.Category, NotificationType = model.NotificationType, Message = model.Message, Link = model.Link, SendDate = model.SendDate.Value, CreatedDate = DateTime.Now, IsRead = false }; db.Notification.Add(notification); db.SaveChanges(); return(Ok(notification.Id)); }
private async Task <bool> CreateNotification(CreateNotificationModel model) { #region Create Schedule //TODO: It will be better to use automapper. var entity = new ScheduleInfo { RecurseId = model.RecurseId, Module = model.Module, ExpirationDate = model.ExpirationDate, MessageTemplateId = (long)model.MessageTemplate, JsonData = model.JsonData, UserSchedules = model.UserIds.Select(id => new UserSchedule() { UserId = id, Status = NotificationStatus.None }).ToList() }; await _scheduleRepository.AddAsync(entity); await _scheduleRepository.SaveAsync(); #endregion #region Create Jobs for schedule //TODO: Store job fire interval in DB or in some configuration file var jobDates = new List <int> { 2, 10, 15 }; var createdJobs = new List <ScheduleJob>(); foreach (var date in jobDates) { var fireDate = entity.ExpirationDate.AddDays(-date); var jobId = await _scheduledJobService.StartJobAsync(new NotificationJob(_serviceProvider), //TODO-Question: Why we create new obj? //TODO: Change this logic when Hangfire will change parameter type to DateTime. fireDate - DateTime.Now, new NotificationJobParameter { ScheduleId = entity.Id }); createdJobs.Add(new ScheduleJob() { JobId = jobId, FireDate = fireDate, }); } #endregion #region Save created jobs data entity.ScheduleJobs = createdJobs; return(await this._scheduleRepository.SaveAsync()); #endregion }
public async Task <IActionResult> CreateNotification(CreateNotificationModel request) { Guid appId = Guid.Parse(_configuration.GetSection(AppSettingKey.OneSignalAppId).Value); string restKey = _configuration.GetSection(AppSettingKey.OneSignalRestKey).Value; string result = await OneSignalPushNotificationHelper.OneSignalPushNotification(request, appId, restKey); return(RedirectToAction("Index", "Notification")); }
public async Task <(bool IsDone, string Message)> CreateTaskAsync(Guid userId, CreateTaskModel model) { try { var access = await _securityService.GetUserAccessAsync(userId, model.ProjectId); if (!access[UserAction.CREATE_TASK]) { return(IsDone : false, Message : "Access denied"); } var column = await _context.Columns.FindAsync(model.ColumnId); var board = await _context.Boards.FindAsync(column.BoardId); var assigneeId = _context.Users.SingleOrDefault(x => x.Email == model.AssigneeEmail)?.Id; var attachments = model.Attachments == null ? null : await ToAttachments(model.Attachments); var task = new DataProvider.Entities.Task { Title = $"{board.TaskPrefix}-{board.TaskIndex} {model.Title}", ColumnId = model.ColumnId, CreatorId = userId, AssigneeId = assigneeId, Content = model.Content ?? "", Priority = model.Priority, Severity = model.Severity, Type = model.Type, Attachments = attachments }; await _context.Tasks.AddAsync(task); board.TaskIndex++; _context.Update(board); await _context.SaveChangesAsync(); if (assigneeId != null) { var notification = new CreateNotificationModel { Subject = "You were assigned to task", Description = $"You were assigned to {task.Title}", DirectLink = $"/project/{model.ProjectId}/board/{column.BoardId}", RecipientEmail = model.AssigneeEmail }; await _notificationService.CreateNotificationAsync(notification); } return(IsDone : true, Message : "Success"); } catch (Exception e) { _logger.LogError("TaskService: CreateTaskAsync", e); } return(IsDone : false, Message : "Something went wrong, try again later"); }
public async Task <(bool IsDone, string Message)> AddUserToProjectAsync(Guid userId, AddUserModel model) { try { var userAccess = await _securityService.GetUserAccessAsync(userId, model.ProjectId); if (!userAccess[UserAction.UPDATE_PROJECT]) { _logger.LogWarning("ProjectService, AddUserToProjectAsync", "User action denied", userId); return(IsDone : false, Message : "Access denied"); } var user = _context.Users.SingleOrDefault(x => x.Email == model.Email); if (user == null) { return(IsDone : false, Message : "There is no such user"); } var existingProjectUser = _context.ProjectUsers.SingleOrDefault(x => x.ProjectId == model.ProjectId && x.UserId == user.Id); if (existingProjectUser != null) { return(IsDone : false, Message : "User already in project"); } var projectUser = new ProjectUser { Role = (int)UserRole.MEMBER, User = user, ProjectId = model.ProjectId }; await _context.ProjectUsers.AddAsync(projectUser); var result = await _context.SaveChangesAsync(); if (result < 1) { return(IsDone : false, Message : "Something went wrong, please try again later"); } var notification = new CreateNotificationModel { Description = "You were added to project", DirectLink = $"/project/{model.ProjectId}", RecipientEmail = user.Email, Subject = "You were added to project" }; var notificationResult = await _notificationService.CreateNotificationAsync(notification); return(IsDone : true, Message : "Success"); } catch (Exception e) { _logger.LogError("ProjectService, AddUserToProjectAsync", e); } return(IsDone : false, Message : "Something went wrong, please try again later"); }
public async Task <(bool IsDone, string Message)> RemoveUserFromProjectAsync(Guid userId, AddUserModel model) { try { var userAccess = await _securityService.GetUserAccessAsync(userId, model.ProjectId); if (!userAccess[UserAction.UPDATE_PROJECT]) { _logger.LogWarning("ProjectService, RemoveUserFromProjectAsync", "User action denied", userId); return(IsDone : false, Message : "Access denied"); } var user = _context.Users.SingleOrDefault(x => x.Email == model.Email); if (user == null) { return(IsDone : false, Message : "There is no such user"); } var existingProjectUser = _context.ProjectUsers.SingleOrDefault(x => x.Role != (int)UserRole.ADMIN && x.ProjectId == model.ProjectId && x.UserId == user.Id); if (existingProjectUser == null) { return(IsDone : false, Message : "There is no such user in project, or you're trying to delete project admin"); } _context.ProjectUsers.Remove(existingProjectUser); var result = await _context.SaveChangesAsync(); if (result < 1) { return(IsDone : false, Message : "Something went wrong, please try again later"); } var notification = new CreateNotificationModel { Description = "You were removed from project", DirectLink = "/projects", RecipientEmail = user.Email, Subject = "You were removed from project" }; var notificationResult = await _notificationService.CreateNotificationAsync(notification); return(IsDone : true, Message : "Success"); } catch (Exception e) { _logger.LogError("ProjectService, RemoveUserFromProjectAsync", e); } return(IsDone : false, Message : "Something went wrong, please try again later"); }
public async Task <IActionResult> Add([FromBody] CreateNotificationModel model) { var notification = _mapper.Map <NotificationModel, Notification>(model.Notification); notification.UserId = SesionUser.Id; var createdNotification = await _notification.Create(notification); await _notification.Send(createdNotification, model.Departments, model.Users); return(Ok()); }
public async Task <long> sendWebNotifyAPI(CreateNotificationModel model) { var response = await WepApiMethod.SendApiAsync <long> (HttpVerbs.Post, $"System/Notification", model, WepApiMethod.APIEngine.IntranetAPI); if (response.isSuccess) { return(response.Data); } else { return(-1); } }
public async Task <ActionResult> Test() { var model = new CreateNotificationModel { UserId = 1, NotificationType = NotificationType.ActivateAccount, Category = NotificationCategory.Learning, Message = "tetst", Link = "" }; var response2 = await WepApiMethod.SendApiAsync <long>(HttpVerbs.Post, $"System/Notification", model); return(Content("")); }
public static async Task <string> OneSignalPushNotification(CreateNotificationModel request, Guid appId, string restKey) { OneSignalClient client = new OneSignalClient(restKey); var opt = new NotificationCreateOptions() { AppId = appId, IncludePlayerIds = request.PlayerIds, SendAfter = DateTime.Now.AddSeconds(10) }; opt.Headings.Add(LanguageCodes.English, request.Title); opt.Contents.Add(LanguageCodes.English, request.Content); NotificationCreateResult result = await client.Notifications.CreateAsync(opt); return(result.Id); }
public async Task <bool> MoveTaskAsync(Guid userId, int projectId, int taskId, int columnId) { try { var access = await _securityService.GetUserAccessAsync(userId, projectId); if (!access[UserAction.CREATE_TASK]) { return(false); } var task = _context.Tasks .Include(x => x.Assignee) .SingleOrDefault(x => x.Id == taskId); task.ColumnId = columnId; _context.Update(task); await _context.SaveChangesAsync(); if (task.Assignee != null) { var newColumn = await _context.Columns.FindAsync(columnId); var notification = new CreateNotificationModel { Description = $"{task.Title} was changed", DirectLink = $"/project/{projectId}/board/{newColumn.BoardId}", RecipientEmail = task.Assignee.Email, Subject = "Task was changed" }; await _notificationService.CreateNotificationAsync(notification); } return(true); } catch (Exception e) { _logger.LogError("TaskService: MoveTaskAsync", e); } return(false); }
public async Task <bool> CreateNotificationAsync(CreateNotificationModel model) { try { var user = await _userManager.FindByEmailAsync(model.RecipientEmail); var notification = new Notification { RecipientId = user.Id, Description = model.Description, DirectLink = model.DirectLink, Subject = model.Subject, IsDelivered = false }; _context.Notifications.Add(notification); var result = await _context.SaveChangesAsync(); if (result < 0) { return(false); } var notificationModel = new NotificationViewModel { Description = notification.Description, DirectLink = notification.DirectLink, Id = notification.Id, Subject = notification.Subject }; return(await Notify(user.Id, notificationModel)); } catch (Exception e) { _logger.LogWarning("NotificationService, CreateNotificationAsync:", e); } return(false); }
public static async Task <string> OneSignalPushNotification(CreateNotificationModel request, Guid appId, string restKey) { var client = new OneSignalClient(restKey); var opt = new NotificationCreateOptions() { AppId = appId, IncludedSegments = new string[] { "Subscribed Users" } }; opt.Headings.Add(LanguageCodes.English, request.Title); opt.Contents.Add(LanguageCodes.English, request.Content); try { NotificationCreateResult result = await client.Notifications.CreateAsync(opt); return(result.Id); } catch (Exception ex) { throw; } }
public async Task <IHttpActionResult> GenerateAutoNotificationReminder(CreateAutoReminder reminder) { List <DateTime> ScheduleMessage = GetSLAReminder(reminder.NotificationType, reminder.StartNotificationDate); var template = db.NotificationTemplates.Where(t => t.NotificationType == reminder.NotificationType).FirstOrDefault(); int SLAReminderId = 0; // --> CALL StartNotification API (register SLAReminder) -> return [SLAReminderStatusId] CreateSLAReminderStatusModel objReminder = new CreateSLAReminderStatusModel { NotificationType = reminder.NotificationType, NotificationReminderStatusType = NotificationReminderStatusType.Open, StartDate = reminder.StartNotificationDate }; var responseStartNotification = StartNotificationFunc(objReminder); /*var responseStartNotification = await WepApiMethod.SendApiAsync<CreateSLAReminderStatusModel> * (HttpVerbs.Post, $"Reminder/SLA/StartNotification/", objReminder);*/ if (responseStartNotification != null) { SLAReminderId = responseStartNotification.Id; if (template.enableEmail) { string emailSubject = generateBodyMessage(template.TemplateSubject, reminder.NotificationType, reminder.ParameterListToSend); //send email ke setiap reciever foreach (var receiver in reminder.ReceiverId) { string receiverEmailAddress = db.User.Find(receiver).Email; reminder.ParameterListToSend.ReceiverFullName = GetReceiverFullName(receiverEmailAddress); string emailBody = generateBodyMessage(template.TemplateMessage, reminder.NotificationType, reminder.ParameterListToSend); int counter = 1; //send notification mengikut jadual foreach (var notifyDate in ScheduleMessage) { // --> CALL EMAIL API HERE--- // | send received notificationId here // \|/ var response = await sendEmailUsingAPIAsync(notifyDate, (int)reminder.NotificationCategory, (int)reminder.NotificationType, receiverEmailAddress, emailSubject, emailBody, counter); if (response != null) { string EmailNotificationId = response.datID; //assumed returned Id // --> CALL insert BulkNotificationGroup API (NotificationMedium : Email, int [SLAReminderStatusId]) BulkNotificationModel objEmailNotification = new BulkNotificationModel { SLAReminderStatusId = SLAReminderId, NotificationMedium = NotificationMedium.Email, NotificationId = EmailNotificationId }; var responseEmailNotificationGroup = RegisterBulkNotificationGroupFunc(objEmailNotification); } counter++; } } } if (template.enableSMSMessage) { //send sms ke setiap reciever foreach (var receiver in reminder.ReceiverId) { string receiverPhoneNo = db.User.Find(receiver).MobileNo; int counter = 1; foreach (var notifyDate in ScheduleMessage) { string SMSToSend = generateSMSMessage(template.SMSMessage, template.NotificationType, reminder.ParameterListToSend); // --> CALL SMS API HERE----- // | send received notificationId here // \|/ var response = await sendSMSUsingAPIAsync(notifyDate, (int)reminder.NotificationCategory, (int)reminder.NotificationType, receiverPhoneNo, null, SMSToSend, counter); if (response != null) { string SMSNotificationId = response.datID; //assumed returned Id // --> CALL insert BulkNotificationGroup API (NotificationMedium : SMS, [SLAReminderStatusId]) BulkNotificationModel objSMSNotification = new BulkNotificationModel { SLAReminderStatusId = SLAReminderId, NotificationMedium = NotificationMedium.SMS, NotificationId = SMSNotificationId }; var responseSMSNotificationGroup = RegisterBulkNotificationGroupFunc(objSMSNotification); } counter++; } } } if (template.enableWebMessage) { foreach (var receiver in reminder.ReceiverId) { int counter = 1; foreach (var notifyDate in ScheduleMessage) { string WebTextToSend = generateWEBMessage(template.WebMessage, template.NotificationType, reminder.ParameterListToSend); string WebLinkTextToSend = generateWEBLinkMessage(template.WebNotifyLink, template.NotificationType, reminder.ParameterListToSend); // --> CALL WEB API HERE----- // | send received notificationId here // \|/ CreateNotificationModel model = new CreateNotificationModel { UserId = receiver, NotificationType = reminder.NotificationType, Category = reminder.NotificationCategory, Message = WebTextToSend, Link = WebLinkTextToSend, SendDate = notifyDate }; var response = await sendWebNotifyAPI(model); if (response != -1) { string WEBNotificationId = response.ToString(); //assumed returned Id // --> CALL insert BulkNotificationGroup API (NotificationMedium : Web, [SLAReminderStatusId]) BulkNotificationModel objWEBNotification = new BulkNotificationModel { SLAReminderStatusId = SLAReminderId, NotificationMedium = NotificationMedium.Web, NotificationId = WEBNotificationId }; var responseWEBNotificationGroup = RegisterBulkNotificationGroup(objWEBNotification); } counter++; } } } ReminderResponse result = new ReminderResponse { Status = "Success", SLAReminderStatusId = SLAReminderId }; return(Ok(result)); } else { ReminderResponse result = new ReminderResponse { Status = "Failed", SLAReminderStatusId = SLAReminderId }; return(Ok(result)); } }
public async Task <bool> CreateNotification(CreateNotificationModel notification) { try { using (var context = DataContextFactory.CreateContext()) { var userInfo = await context.Users .Where(x => x.Id == notification.UserId) .Select(x => new Userinfo { DisableExchangeNotify = x.DisableExchangeNotify, DisableKarmaNotify = x.DisableKarmaNotify, DisableTipNotify = x.DisableTipNotify, DisableMarketplaceNotify = x.DisableMarketplaceNotify, DisablePoolNotify = x.DisablePoolNotify, DisableFaucetNotify = x.DisableFaucetNotify, }).FirstOrDefaultNoLockAsync().ConfigureAwait(false); if (notification.Data != null) { await SendDataNotification(new DataNotificationModel { UserId = new Guid(notification.UserId), Type = notification.DataType, Data = notification.Data }).ConfigureAwait(false); } var isNotificationDisabled = IsNotificationDisabled(userInfo, notification.Type); if (isNotificationDisabled) { return(true); } var entity = new Entity.UserNotification { Acknowledged = false, UserId = notification.UserId, Title = notification.Title, Notification = notification.Message, Timestamp = DateTime.UtcNow, Type = notification.Type.ToString() }; context.Notifications.Add(entity); await context.SaveChangesAsync().ConfigureAwait(false); await SendNotification(new NotificationModel { UserId = new Guid(notification.UserId), Type = notification.Level, Header = notification.Title, Notification = notification.Message }).ConfigureAwait(false); return(true); } } catch (Exception) { return(false); } }