diff --git a/CHANGELOG.md b/CHANGELOG.md index 141d3be..c8f385b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ Each release lists **Upgrade notes** when an install needs action beyond the ste ### Added - **Watch tasks** (Configuration → Work items → *Task watchers*, off by default): a Watch / Watching button with the watcher count and list in the task header, and a **Watching** filter (bell menu → *Tasks I'm watching*). The creator, developer and tester watch a task automatically, as does anyone who comments on it; anyone can unwatch, and that choice sticks. Watchers get an in-app notification when the status, developer/tester or comments change, including changes from Git merge requests, bulk updates and issue sync, but never for their own changes. Members who can no longer see the task stop receiving them. *E-mail watchers* also sends them by e-mail. ([#15](https://github.com/Taskist/taskist/issues/15)) +- **@mentions in comments.** Type `@` in a task's comment box to pick someone who can see the task. The mention is stored by user id and shown as a highlighted name, so it follows renames. The mentioned person gets an in-app notification; a person who is both mentioned and watching gets one notification, not two. Mentions also add the person as a watcher when task watchers are on. Mentioning yourself, a non-member, or a member who can't see the task does nothing. Optional extras, both off until enabled: a **Mention** chat event per project channel, and an e-mail using the new **Mentioned** e-mail template (seeded inactive; activate it under Integrations → Email Template). ([#14](https://github.com/Taskist/taskist/issues/14)) ### Security @@ -23,6 +24,7 @@ Each release lists **Upgrade notes** when an install needs action beyond the ste ### Upgrade notes - New additive migration `AddBacklogWatcher` (table `BacklogWatcher`), applied automatically by Docker; manual installs run `dotnet ef database update` or the regenerated `sql-scripts/01_schema.sql`. Re-run `sql-scripts/03_locale.sql` for the new labels. +- Re-run `sql-scripts/02_defaults.sql` to add the inactive **Mentioned** e-mail template (Docker does this automatically). Existing project chat channels don't receive the new **Mention** event until it is ticked on the project's Notifications tab. ## [1.1.0] - 2026-11-16 diff --git a/sql-scripts/02_defaults.sql b/sql-scripts/02_defaults.sql index 4c7d9a2..49292e9 100644 --- a/sql-scripts/02_defaults.sql +++ b/sql-scripts/02_defaults.sql @@ -311,6 +311,13 @@ SELECT t.[Name], t.[EmailSubject], t.[EmailBody], @emailAccountId, 1 FROM @emailTemplates AS t WHERE NOT EXISTS (SELECT 1 FROM [EmailTemplate] AS e WHERE e.[Name] = t.[Name]); +/* Mention e-mails are optional: the template is created inactive. Activate it under Integrations -> Email Template. */ +INSERT INTO [EmailTemplate] ([Name], [EmailSubject], [EmailBody], [EmailAccountId], [Active]) +SELECT 'Mentioned', '{author} mentioned you on #{task_id} {title}', + '

Hello {display_name},

{author} mentioned you on a task:

#{task_id} - {title}

Project: {project_name}

{comment}

View task

', + @emailAccountId, 0 +WHERE NOT EXISTS (SELECT 1 FROM [EmailTemplate] AS e WHERE e.[Name] = 'Mentioned'); + /* --------------------------------------------------------------------------------------------------------- Administrator account Created only while the [User] table is empty, so re-running never restores it after it was renamed, diff --git a/sql-scripts/03_locale.sql b/sql-scripts/03_locale.sql index d071850..aab26b7 100644 --- a/sql-scripts/03_locale.sql +++ b/sql-scripts/03_locale.sql @@ -158,6 +158,8 @@ FROM (VALUES (N'Backlog.Issue.SyncStopped', N'Sync stopped'), (N'Backlog.Issue.Title', N'Issue'), (N'Backlog.Issue.UnlinkConfirm', N'Stop syncing with this issue? The issue itself is not changed.'), + (N'Backlog.Mention.Hint', N'@ to mention someone'), + (N'Backlog.Mention.NoMatch', N'No matching people on this task'), (N'Backlog.Module', N'Module'), (N'Backlog.Mr.Create', N'Create merge request'), (N'Backlog.Mr.CreateButton', N'Create merge request'), @@ -326,6 +328,7 @@ FROM (VALUES (N'ChatEvent.CodeReview', N'Code review activity'), (N'ChatEvent.Commented', N'New comment'), (N'ChatEvent.Conflict', N'Merge conflicts'), + (N'ChatEvent.Mentioned', N'Mention'), (N'ChatEvent.MergeRequestClosed', N'Merge/pull request closed'), (N'ChatEvent.MergeRequestMerged', N'Merge/pull request merged'), (N'ChatEvent.MergeRequestOpened', N'Merge/pull request opened'), diff --git a/src/Libraries/Taskist.Core/Common/MentionText.cs b/src/Libraries/Taskist.Core/Common/MentionText.cs new file mode 100644 index 0000000..db06f57 --- /dev/null +++ b/src/Libraries/Taskist.Core/Common/MentionText.cs @@ -0,0 +1,80 @@ +using System.Net; +using System.Text; +using System.Text.RegularExpressions; + +namespace Taskist.Core.Common; + +public static partial class MentionText +{ + #region Fields + + public const string UnknownName = "unknown user"; + + #endregion + + #region Methods + + public static string Token(int userId) => $"@[{userId}]"; + + public static IReadOnlyList ParseUserIds(string? text) + { + if (string.IsNullOrEmpty(text)) + return []; + + var ids = new List(); + foreach (Match match in TokenRegex().Matches(text)) + { + if (int.TryParse(match.Groups[1].Value, out var id) && id > 0 && !ids.Contains(id)) + ids.Add(id); + } + + return ids; + } + + public static string ToPlainText(string? text, IReadOnlyDictionary names) + { + if (string.IsNullOrEmpty(text)) + return string.Empty; + + return TokenRegex().Replace(text, match => "@" + NameOf(match, names)); + } + + public static string ToHtml(string? text, IReadOnlyDictionary names) + { + if (string.IsNullOrEmpty(text)) + return string.Empty; + + var html = new StringBuilder(); + var position = 0; + foreach (Match match in TokenRegex().Matches(text)) + { + html.Append(WebUtility.HtmlEncode(text[position..match.Index])); + + var known = int.TryParse(match.Groups[1].Value, out var id) && names.ContainsKey(id); + html.Append(known + ? $"@{WebUtility.HtmlEncode(names[id])}" + : $"@{UnknownName}"); + + position = match.Index + match.Length; + } + + html.Append(WebUtility.HtmlEncode(text[position..])); + return html.ToString(); + } + + #endregion + + #region Utilities + + private static string NameOf(Match match, IReadOnlyDictionary names) + { + return int.TryParse(match.Groups[1].Value, out var id) && names.TryGetValue(id, out var name) + ? name + : UnknownName; + } + + [GeneratedRegex(@"@\[(\d{1,9})\]")] + private static partial Regex TokenRegex(); + + #endregion +} diff --git a/src/Libraries/Taskist.Core/Enums/ChatEvent.cs b/src/Libraries/Taskist.Core/Enums/ChatEvent.cs index 021b70f..a91b031 100644 --- a/src/Libraries/Taskist.Core/Enums/ChatEvent.cs +++ b/src/Libraries/Taskist.Core/Enums/ChatEvent.cs @@ -13,5 +13,6 @@ public enum ChatEvent MergeRequestClosed = 64, CodeReview = 128, Conflict = 256, - All = TaskAssigned | StatusChanged | TaskUpdated | Commented | MergeRequestOpened | MergeRequestMerged | MergeRequestClosed | CodeReview | Conflict + Mentioned = 512, + All = TaskAssigned | StatusChanged | TaskUpdated | Commented | MergeRequestOpened | MergeRequestMerged | MergeRequestClosed | CodeReview | Conflict | Mentioned } diff --git a/src/Libraries/Taskist.Core/Enums/EmailTemplateType.cs b/src/Libraries/Taskist.Core/Enums/EmailTemplateType.cs index 10b0d88..91c8944 100644 --- a/src/Libraries/Taskist.Core/Enums/EmailTemplateType.cs +++ b/src/Libraries/Taskist.Core/Enums/EmailTemplateType.cs @@ -9,5 +9,6 @@ public enum EmailTemplateType Notification, Invite, NewTaskNotification, - TaskNotification + TaskNotification, + Mentioned } diff --git a/src/Libraries/Taskist.Core/Enums/NotificationType.cs b/src/Libraries/Taskist.Core/Enums/NotificationType.cs index 7aec8de..db4aaec 100644 --- a/src/Libraries/Taskist.Core/Enums/NotificationType.cs +++ b/src/Libraries/Taskist.Core/Enums/NotificationType.cs @@ -11,5 +11,6 @@ public enum NotificationType MergeRequestClosed, TaskStatusChanged, TaskCommented, - TaskAssignmentChanged + TaskAssignmentChanged, + Mentioned } diff --git a/src/Libraries/Taskist.Service/Git/Issues/IssueSyncService.cs b/src/Libraries/Taskist.Service/Git/Issues/IssueSyncService.cs index ed3bee3..9cf97a3 100644 --- a/src/Libraries/Taskist.Service/Git/Issues/IssueSyncService.cs +++ b/src/Libraries/Taskist.Service/Git/Issues/IssueSyncService.cs @@ -52,6 +52,7 @@ public class IssueSyncService : IIssueSyncService private readonly IClosingRequirementService _closingRequirementService; private readonly ITaskCodeService _taskCodeService; private readonly IBacklogWatcherService _backlogWatcherService; + private readonly IMentionService _mentionService; private readonly ILogger _logger; #endregion @@ -76,8 +77,10 @@ public IssueSyncService(IRepository linkRepository, IClosingRequirementService closingRequirementService, ITaskCodeService taskCodeService, IBacklogWatcherService backlogWatcherService, + IMentionService mentionService, ILogger logger) { + _mentionService = mentionService; _backlogWatcherService = backlogWatcherService; _linkRepository = linkRepository; _commentLinkRepository = commentLinkRepository; @@ -905,7 +908,9 @@ await _commentLinkRepository.InsertAsync(new ExternalCommentLink private async Task OutboundCommentBodyAsync(BacklogComment comment) { var author = comment.CreatedBy ?? await _userRepository.GetByIdAsync(comment.CreatedById); - return $"**{author?.Name ?? "A Taskist user"}** {OutboundMarker}\n\n{comment.Comment?.Trim()}"; + var names = await _mentionService.GetNamesAsync([comment.Comment]); + var text = MentionText.ToPlainText(comment.Comment, names).Trim(); + return $"**{author?.Name ?? "A Taskist user"}** {OutboundMarker}\n\n{text}"; } private static string InboundCommentHtml(GitRepositoryContext repository, GitIssueCommentDto comment) diff --git a/src/Libraries/Taskist.Service/Messages/IMessageService.cs b/src/Libraries/Taskist.Service/Messages/IMessageService.cs index e42fc1d..408e5bd 100644 --- a/src/Libraries/Taskist.Service/Messages/IMessageService.cs +++ b/src/Libraries/Taskist.Service/Messages/IMessageService.cs @@ -27,5 +27,7 @@ public interface IMessageService Task EmailTaskNotificationAsync(Backlog backlog, User loggedUser, string status, bool tester); + Task EmailMentionAsync(Backlog backlog, User recipient, string authorName, string excerpt); + #endregion } diff --git a/src/Libraries/Taskist.Service/Messages/MessageService.cs b/src/Libraries/Taskist.Service/Messages/MessageService.cs index f512c66..cdef554 100644 --- a/src/Libraries/Taskist.Service/Messages/MessageService.cs +++ b/src/Libraries/Taskist.Service/Messages/MessageService.cs @@ -242,6 +242,44 @@ public async Task EmailTaskNotificationAsync(Backlog backlog, User loggedU return Task.CompletedTask; } + public async Task EmailMentionAsync(Backlog backlog, User recipient, string authorName, string excerpt) + { + if (backlog == null || recipient == null || string.IsNullOrWhiteSpace(recipient.Email)) + return; + + var emailTemplate = await _emailTemplateService.GetByNameAsync(EmailTemplateType.Mentioned.ToString()); + if (emailTemplate == null || !emailTemplate.Active || string.IsNullOrEmpty(emailTemplate.EmailBody)) + return; + + var emailAccount = await _emailAccounteService.GetByIdAsync(emailTemplate.EmailAccountId); + if (emailAccount == null || !emailAccount.Active) + return; + + var tokenValues = new Dictionary + { + { "url", WebUtility.HtmlEncode($"{_httpHelper.GetBaseURL()}/backlog/edit/{backlog.Id}") }, + { "task_id", backlog.Id.ToString() }, + { "display_name", WebUtility.HtmlEncode(recipient.Name) }, + { "author", WebUtility.HtmlEncode(authorName) }, + { "title", WebUtility.HtmlEncode(backlog.Title) }, + { "project_name", WebUtility.HtmlEncode(backlog.Project?.Name ?? string.Empty) }, + { "comment", WebUtility.HtmlEncode(excerpt).Replace("\n", "
") } + }; + var subjectValues = new Dictionary + { + { "task_id", backlog.Id.ToString() }, + { "author", authorName }, + { "title", backlog.Title } + }; + + var body = ReplaceTokensRegex(emailTemplate.EmailBody, tokenValues); + var subject = ReplaceTokensRegex(emailTemplate.EmailSubject ?? string.Empty, subjectValues); + var email = recipient.Email; + var name = recipient.Name; + + _backgroundJobClient.Enqueue(() => _emailSenderService.SendEmailAsync(emailAccount, subject, body, email, name)); + } + #endregion #region Helpers diff --git a/src/Libraries/Taskist.Service/WorkItems/BacklogService.cs b/src/Libraries/Taskist.Service/WorkItems/BacklogService.cs index 0e0e2eb..0b7b465 100644 --- a/src/Libraries/Taskist.Service/WorkItems/BacklogService.cs +++ b/src/Libraries/Taskist.Service/WorkItems/BacklogService.cs @@ -50,6 +50,7 @@ public class BacklogService : IBacklogService protected readonly IntegrationSettings _integrationSettings; protected readonly IRepository _backlogWatcherRepository; protected readonly IBacklogWatcherService _backlogWatcherService; + protected readonly IMentionService _mentionService; #endregion @@ -76,8 +77,10 @@ public BacklogService(IRepository backlogRepository, IClosingRequirementService closingRequirementService, IntegrationSettings integrationSettings, IRepository backlogWatcherRepository, - IBacklogWatcherService backlogWatcherService) + IBacklogWatcherService backlogWatcherService, + IMentionService mentionService) { + _mentionService = mentionService; _integrationSettings = integrationSettings; _backlogWatcherRepository = backlogWatcherRepository; _backlogWatcherService = backlogWatcherService; @@ -1587,15 +1590,25 @@ await _backlogCommentRepository.InsertAsync(new BacklogComment await AddToNotification(ChatEvent.Commented, backlog, notifications, $"A new comment was added by {loggedUserName}"); await _notificationChannelService.TaskUpdatesAsync(notifications); - var excerpt = HtmlText.ToPlainText(comment, 200); - await _backlogWatcherService.NotifyAsync(backlog, new TaskWatchNotice + var names = await _mentionService.GetNamesAsync([comment]); + var excerpt = HtmlText.ToPlainText(MentionText.ToPlainText(comment, names), 200); + if (string.IsNullOrWhiteSpace(excerpt)) + excerpt = "New comment"; + + var mentioned = await _mentionService.ResolveAsync(backlog, comment, loggedUserId); + + var watchNotice = new TaskWatchNotice { Type = NotificationType.TaskCommented, - Detail = string.IsNullOrWhiteSpace(excerpt) ? "New comment" : excerpt, + Detail = excerpt, ActorId = loggedUserId, ActorName = loggedUserName - }); + }; + watchNotice.Skip.AddRange(mentioned.Select(x => x.Id)); + await _backlogWatcherService.NotifyAsync(backlog, watchNotice); await _backlogWatcherService.AutoWatchAsync(backlogId, loggedUserId, WatchSource.Commented); + + await _mentionService.NotifyAsync(backlog, mentioned, loggedUserId, loggedUserName, excerpt); } } diff --git a/src/Libraries/Taskist.Service/WorkItems/BacklogWatcherService.cs b/src/Libraries/Taskist.Service/WorkItems/BacklogWatcherService.cs index 02a597b..df5aaf0 100644 --- a/src/Libraries/Taskist.Service/WorkItems/BacklogWatcherService.cs +++ b/src/Libraries/Taskist.Service/WorkItems/BacklogWatcherService.cs @@ -2,14 +2,12 @@ using Microsoft.Extensions.Logging; using Taskist.Core.Common; using Taskist.Core.Domain.Settings; -using Taskist.Core.Domain.Users; using Taskist.Core.Domain.WorkItems; using Taskist.Core.Dtos.Notification; using Taskist.Core.Dtos.WorkItems; using Taskist.Core.Enums; using Taskist.Data.Repository; using Taskist.Service.Messages; -using Taskist.Service.Users; namespace Taskist.Service.WorkItems; @@ -18,8 +16,7 @@ public class BacklogWatcherService : IBacklogWatcherService #region Fields protected readonly IRepository _watcherRepository; - protected readonly IRepository _userRepository; - protected readonly IUserService _userService; + protected readonly ITaskViewerService _taskViewerService; protected readonly IUserNotificationService _userNotificationService; protected readonly WorkItemSettings _workItemSettings; protected readonly ILogger _logger; @@ -29,15 +26,13 @@ public class BacklogWatcherService : IBacklogWatcherService #region Ctor public BacklogWatcherService(IRepository watcherRepository, - IRepository userRepository, - IUserService userService, + ITaskViewerService taskViewerService, IUserNotificationService userNotificationService, WorkItemSettings workItemSettings, ILogger logger) { _watcherRepository = watcherRepository; - _userRepository = userRepository; - _userService = userService; + _taskViewerService = taskViewerService; _userNotificationService = userNotificationService; _workItemSettings = workItemSettings; _logger = logger; @@ -60,7 +55,7 @@ public async Task GetStateAsync(Backlog backlog, int userId) state.Watching = WatcherRecipients.IsWatching(userId, implicitWatchers, rows); - var users = await AllowedUsersAsync(backlog, WatcherRecipients.Watchers(implicitWatchers, rows)); + var users = await _taskViewerService.FilterViewersAsync(backlog, WatcherRecipients.Watchers(implicitWatchers, rows)); state.Watchers = users .Select(x => x.Name) .OrderBy(x => x, StringComparer.OrdinalIgnoreCase) @@ -107,7 +102,7 @@ public async Task NotifyAsync(Backlog backlog, TaskWatchNotice notice) if (ids.Count == 0) return; - var users = await AllowedUsersAsync(backlog, ids); + var users = await _taskViewerService.FilterViewersAsync(backlog, ids); if (users.Count == 0) return; @@ -166,28 +161,5 @@ await _watcherRepository.InsertAsync(new BacklogWatcher await _watcherRepository.UpdateAsync(row); } - private async Task> AllowedUsersAsync(Backlog backlog, IReadOnlyList ids) - { - if (ids.Count == 0) - return []; - - var users = await _userRepository.Table - .Where(x => ids.Contains(x.Id) && !x.Deleted && !x.Locked) - .ToListAsync(); - - var allowed = new List(); - foreach (var user in users) - { - var mapping = await _userService.GetProjectMapping(user.Id, backlog.ProjectId); - if (mapping == null) - continue; - - if (mapping.CanViewOthersTask || backlog.AssigneeId == user.Id || backlog.TesterId == user.Id) - allowed.Add(user); - } - - return allowed; - } - #endregion } diff --git a/src/Libraries/Taskist.Service/WorkItems/IMentionService.cs b/src/Libraries/Taskist.Service/WorkItems/IMentionService.cs new file mode 100644 index 0000000..dcb0fdf --- /dev/null +++ b/src/Libraries/Taskist.Service/WorkItems/IMentionService.cs @@ -0,0 +1,15 @@ +using Taskist.Core.Domain.Users; +using Taskist.Core.Domain.WorkItems; + +namespace Taskist.Service.WorkItems; + +public interface IMentionService +{ + Task> GetCandidatesAsync(Backlog backlog, int currentUserId, string? term, int take = 8); + + Task> ResolveAsync(Backlog backlog, string? comment, int authorId); + + Task> GetNamesAsync(IEnumerable texts); + + Task NotifyAsync(Backlog backlog, IList mentioned, int authorId, string authorName, string excerpt); +} diff --git a/src/Libraries/Taskist.Service/WorkItems/ITaskViewerService.cs b/src/Libraries/Taskist.Service/WorkItems/ITaskViewerService.cs new file mode 100644 index 0000000..b08c5e4 --- /dev/null +++ b/src/Libraries/Taskist.Service/WorkItems/ITaskViewerService.cs @@ -0,0 +1,11 @@ +using Taskist.Core.Domain.Users; +using Taskist.Core.Domain.WorkItems; + +namespace Taskist.Service.WorkItems; + +public interface ITaskViewerService +{ + Task> FilterViewersAsync(Backlog backlog, IEnumerable userIds); + + Task> GetViewersAsync(Backlog backlog); +} diff --git a/src/Libraries/Taskist.Service/WorkItems/MentionService.cs b/src/Libraries/Taskist.Service/WorkItems/MentionService.cs new file mode 100644 index 0000000..8b832cd --- /dev/null +++ b/src/Libraries/Taskist.Service/WorkItems/MentionService.cs @@ -0,0 +1,130 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using Taskist.Core.Common; +using Taskist.Core.Domain.Users; +using Taskist.Core.Domain.WorkItems; +using Taskist.Core.Dtos.Notification; +using Taskist.Core.Enums; +using Taskist.Data.Repository; +using Taskist.Service.Messages; + +namespace Taskist.Service.WorkItems; + +public class MentionService : IMentionService +{ + #region Fields + + protected readonly IRepository _userRepository; + protected readonly ITaskViewerService _taskViewerService; + protected readonly IBacklogWatcherService _backlogWatcherService; + protected readonly IUserNotificationService _userNotificationService; + protected readonly IMessageService _messageService; + protected readonly INotificationChannelService _notificationChannelService; + protected readonly ILogger _logger; + + #endregion + + #region Ctor + + public MentionService(IRepository userRepository, + ITaskViewerService taskViewerService, + IBacklogWatcherService backlogWatcherService, + IUserNotificationService userNotificationService, + IMessageService messageService, + INotificationChannelService notificationChannelService, + ILogger logger) + { + _userRepository = userRepository; + _taskViewerService = taskViewerService; + _backlogWatcherService = backlogWatcherService; + _userNotificationService = userNotificationService; + _messageService = messageService; + _notificationChannelService = notificationChannelService; + _logger = logger; + } + + #endregion + + #region Methods + + public async Task> GetCandidatesAsync(Backlog backlog, int currentUserId, string? term, int take = 8) + { + var viewers = await _taskViewerService.GetViewersAsync(backlog); + var search = term?.Trim() ?? string.Empty; + + return viewers + .Where(x => x.Id != currentUserId) + .Where(x => search.Length == 0 + || x.Name.Contains(search, StringComparison.OrdinalIgnoreCase) + || (x.Email ?? string.Empty).StartsWith(search, StringComparison.OrdinalIgnoreCase)) + .OrderBy(x => x.Name.StartsWith(search, StringComparison.OrdinalIgnoreCase) ? 0 : 1) + .ThenBy(x => x.Name, StringComparer.OrdinalIgnoreCase) + .Take(take) + .ToList(); + } + + public async Task> ResolveAsync(Backlog backlog, string? comment, int authorId) + { + var ids = MentionText.ParseUserIds(comment).Where(x => x != authorId).ToList(); + if (ids.Count == 0) + return []; + + return await _taskViewerService.FilterViewersAsync(backlog, ids); + } + + public async Task> GetNamesAsync(IEnumerable texts) + { + var ids = texts.SelectMany(MentionText.ParseUserIds).Distinct().ToList(); + if (ids.Count == 0) + return new Dictionary(); + + var users = await _userRepository.Table + .Where(x => ids.Contains(x.Id)) + .ToListAsync(); + + return users.ToDictionary(x => x.Id, x => x.Name); + } + + public async Task NotifyAsync(Backlog backlog, IList mentioned, int authorId, string authorName, string excerpt) + { + var recipients = (mentioned ?? []).Where(x => x.Id != authorId).GroupBy(x => x.Id).Select(x => x.First()).ToList(); + if (backlog == null || recipients.Count == 0) + return; + + try + { + await _userNotificationService.NotifyAsync(new UserNotificationRequest + { + UserIds = recipients.Select(x => x.Id).ToList(), + Type = NotificationType.Mentioned, + Title = $"#{backlog.Id} {backlog.Title}", + Message = $"{authorName} mentioned you: {excerpt}", + Url = $"~/Backlog/Edit/{backlog.Id}" + }); + + foreach (var user in recipients) + await _messageService.EmailMentionAsync(backlog, user, authorName, excerpt); + + var names = string.Join(", ", recipients.Select(x => x.Name)); + await _notificationChannelService.TaskUpdatesAsync(recipients.Select(x => new ChatTaskUpdateDto + { + Name = x.Name, + Email = x.Email, + TaskId = backlog.Id, + TaskTitle = backlog.Title, + Message = $"{authorName} mentioned {names}: {excerpt}", + ProjectId = backlog.ProjectId, + Event = ChatEvent.Mentioned + }).ToList()); + + foreach (var user in recipients) + await _backlogWatcherService.AutoWatchAsync(backlog.Id, user.Id, WatchSource.Mentioned); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Could not notify the users mentioned on task {TaskId}", backlog.Id); + } + } + + #endregion +} diff --git a/src/Libraries/Taskist.Service/WorkItems/TaskViewerService.cs b/src/Libraries/Taskist.Service/WorkItems/TaskViewerService.cs new file mode 100644 index 0000000..ce6fc5d --- /dev/null +++ b/src/Libraries/Taskist.Service/WorkItems/TaskViewerService.cs @@ -0,0 +1,71 @@ +using Microsoft.EntityFrameworkCore; +using Taskist.Core.Domain.Users; +using Taskist.Core.Domain.WorkItems; +using Taskist.Core.Enums; +using Taskist.Data.Repository; + +namespace Taskist.Service.WorkItems; + +public class TaskViewerService : ITaskViewerService +{ + #region Fields + + protected readonly IRepository _userRepository; + protected readonly IRepository _userProjectMapRepository; + + #endregion + + #region Ctor + + public TaskViewerService(IRepository userRepository, + IRepository userProjectMapRepository) + { + _userRepository = userRepository; + _userProjectMapRepository = userProjectMapRepository; + } + + #endregion + + #region Methods + + public async Task> FilterViewersAsync(Backlog backlog, IEnumerable userIds) + { + var ids = (userIds ?? []).Where(x => x > 0).Distinct().ToList(); + if (backlog == null || backlog.Deleted || ids.Count == 0) + return []; + + return await ViewersQuery(backlog) + .Where(x => ids.Contains(x.Id)) + .ToListAsync(); + } + + public async Task> GetViewersAsync(Backlog backlog) + { + if (backlog == null || backlog.Deleted) + return []; + + return await ViewersQuery(backlog).ToListAsync(); + } + + #endregion + + #region Utilities + + private IQueryable ViewersQuery(Backlog backlog) + { + var projectId = backlog.ProjectId; + var assigneeId = backlog.AssigneeId; + var testerId = backlog.TesterId; + + var viewerIds = _userProjectMapRepository.Table + .Where(m => m.ProjectId == projectId && m.Project.Active && !m.Project.Deleted + && (m.CanViewOthersTask || m.UserId == assigneeId || m.UserId == testerId)) + .Select(m => m.UserId); + + return _userRepository.Table + .Where(u => !u.Deleted && !u.Locked && !u.SystemAccount && u.Status == (int)UserStatus.Active + && viewerIds.Contains(u.Id)); + } + + #endregion +} diff --git a/src/Presentation/Taskist.Web/Controllers/Masters/ProjectController.cs b/src/Presentation/Taskist.Web/Controllers/Masters/ProjectController.cs index 4d60944..de2025d 100644 --- a/src/Presentation/Taskist.Web/Controllers/Masters/ProjectController.cs +++ b/src/Presentation/Taskist.Web/Controllers/Masters/ProjectController.cs @@ -609,7 +609,7 @@ public async Task AddNotification(int projectId) var model = new ProjectNotificationChannelModel { ProjectId = projectId, - Events = Enum.GetValues().Where(e => e != ChatEvent.None && e != ChatEvent.All && e != ChatEvent.TaskUpdated).Select(e => (int)e).ToList() + Events = Enum.GetValues().Where(e => e != ChatEvent.None && e != ChatEvent.All && e != ChatEvent.TaskUpdated && e != ChatEvent.Mentioned).Select(e => (int)e).ToList() }; await InitNotificationModelAsync(model); diff --git a/src/Presentation/Taskist.Web/Controllers/WorkItems/BacklogController.cs b/src/Presentation/Taskist.Web/Controllers/WorkItems/BacklogController.cs index d6e5177..5837986 100644 --- a/src/Presentation/Taskist.Web/Controllers/WorkItems/BacklogController.cs +++ b/src/Presentation/Taskist.Web/Controllers/WorkItems/BacklogController.cs @@ -70,6 +70,7 @@ public class BacklogController : BaseController protected readonly IClosingRequirementService _closingRequirementService; protected readonly IUploadTokenService _uploadTokenService; protected readonly IBacklogWatcherService _backlogWatcherService; + protected readonly IMentionService _mentionService; private const int BulkMoveLimit = 100; @@ -110,10 +111,12 @@ public BacklogController(IBacklogService backlogItemService, IClosingRequirementService closingRequirementService, IMergeRequestReviewService mergeRequestReviewService, IUploadTokenService uploadTokenService, - IBacklogWatcherService backlogWatcherService) + IBacklogWatcherService backlogWatcherService, + IMentionService mentionService) { _uploadTokenService = uploadTokenService; _backlogWatcherService = backlogWatcherService; + _mentionService = mentionService; _closingRequirementService = closingRequirementService; _mergeRequestReviewService = mergeRequestReviewService; _backlogItemService = backlogItemService; @@ -762,16 +765,19 @@ public async Task Comments(int id) return AccessDeniedPartial(); var data = await _backlogItemService.GetAllCommentsAsync(id); + var names = await _mentionService.GetNamesAsync(data.Where(s => !s.SystemComment).Select(s => s.Comment)); var model = new BacklogCommentModel() { BackLogId = id, CanPostToIssue = await _issueSyncService.HasActiveLinkAsync(id), + MentionUrl = Url.Action("MentionCandidates", new { id }), Comments = data.Select(s => new BacklogCommentGridModel { CommentById = s.CreatedById, CommentBy = s.CreatedBy.Name, CommentOn = s.CreatedOn, Comment = s.Comment, + CommentHtml = s.SystemComment ? null : MentionText.ToHtml(s.Comment, names), SystemComment = s.SystemComment }).ToList() }; @@ -779,6 +785,24 @@ public async Task Comments(int id) return PartialView(model); } + [CheckPermission(nameof(PermissionProvider.ManageBacklog))] + public async Task MentionCandidates(int id, string? q) + { + if (!await _backlogItemService.CanViewTaskAsync(id)) + return Json(Array.Empty()); + + var task = await _backlogItemService.GetByIdAsync(id); + var users = await _mentionService.GetCandidatesAsync(task, UserId, q); + + return Json(users.Select(u => new + { + id = u.Id, + name = u.Name, + token = MentionText.Token(u.Id), + photo = Url.Action("Photo", "Profile", new { userId = u.Id }) + })); + } + [HttpPost] [CheckPermission(nameof(PermissionProvider.ManageBacklog))] public async Task CommentCreate(int id, string comment, bool postToIssue = false) @@ -795,12 +819,14 @@ public async Task CommentCreate(int id, string comment, bool post if (postToIssue) await _gitJobScheduler.EnqueueIssuePushAsync(id); + var names = await _mentionService.GetNamesAsync([comment]); return Json(new { success = true, commentbyid = UserId, commentby = UserName, - commenton = DateTime.Now.ToString("dd-MM-yyyy hh:mm") + commenton = DateTime.Now.ToString("dd-MM-yyyy hh:mm"), + html = MentionText.ToHtml(comment, names) }); } diff --git a/src/Presentation/Taskist.Web/Models/WorkItems/BacklogCommentGridModel.cs b/src/Presentation/Taskist.Web/Models/WorkItems/BacklogCommentGridModel.cs index 9cf3428..4094a64 100644 --- a/src/Presentation/Taskist.Web/Models/WorkItems/BacklogCommentGridModel.cs +++ b/src/Presentation/Taskist.Web/Models/WorkItems/BacklogCommentGridModel.cs @@ -10,6 +10,8 @@ public class BacklogCommentGridModel public string Comment { get; set; } + public string? CommentHtml { get; set; } + public bool SystemComment { get; set; } public string? FieldLabel { get; set; } diff --git a/src/Presentation/Taskist.Web/Models/WorkItems/BacklogCommentModel.cs b/src/Presentation/Taskist.Web/Models/WorkItems/BacklogCommentModel.cs index a7cd09f..4efba4e 100644 --- a/src/Presentation/Taskist.Web/Models/WorkItems/BacklogCommentModel.cs +++ b/src/Presentation/Taskist.Web/Models/WorkItems/BacklogCommentModel.cs @@ -13,5 +13,7 @@ public BacklogCommentModel() public bool CanPostToIssue { get; set; } + public string? MentionUrl { get; set; } + public List Comments { get; set; } } diff --git a/src/Presentation/Taskist.Web/Views/Backlog/Comments.cshtml b/src/Presentation/Taskist.Web/Views/Backlog/Comments.cshtml index bd22107..e18ff8a 100644 --- a/src/Presentation/Taskist.Web/Views/Backlog/Comments.cshtml +++ b/src/Presentation/Taskist.Web/Views/Backlog/Comments.cshtml @@ -1,6 +1,7 @@ @model BacklogCommentModel -
+
@@ -17,7 +18,7 @@ @comment.CommentBy
-
@if (comment.SystemComment) { @Html.Raw(comment.Comment) } else { @comment.Comment }
+
@if (comment.SystemComment) { @Html.Raw(comment.Comment) } else { @Html.Raw(comment.CommentHtml) }
} @@ -28,7 +29,7 @@
- Enter to send · Shift+Enter for a new line + Enter to send · Shift+Enter for a new line · @Localize("Backlog.Mention.Hint").Text @if (Model.CanPostToIssue) {
diff --git a/src/Presentation/Taskist.Web/Views/Backlog/Edit.cshtml b/src/Presentation/Taskist.Web/Views/Backlog/Edit.cshtml index 22c4407..8325ae1 100644 --- a/src/Presentation/Taskist.Web/Views/Backlog/Edit.cshtml +++ b/src/Presentation/Taskist.Web/Views/Backlog/Edit.cshtml @@ -17,6 +17,7 @@ + diff --git a/src/Presentation/Taskist.Web/Views/Backlog/Index.cshtml b/src/Presentation/Taskist.Web/Views/Backlog/Index.cshtml index 303c144..9777ad5 100644 --- a/src/Presentation/Taskist.Web/Views/Backlog/Index.cshtml +++ b/src/Presentation/Taskist.Web/Views/Backlog/Index.cshtml @@ -25,6 +25,7 @@ + } diff --git a/src/Presentation/Taskist.Web/Views/Notification/_NotificationList.cshtml b/src/Presentation/Taskist.Web/Views/Notification/_NotificationList.cshtml index 94b72cc..9a90695 100644 --- a/src/Presentation/Taskist.Web/Views/Notification/_NotificationList.cshtml +++ b/src/Presentation/Taskist.Web/Views/Notification/_NotificationList.cshtml @@ -12,6 +12,7 @@ NotificationType.TaskStatusChanged => ("fa-arrow-right-arrow-left", "blue"), NotificationType.TaskCommented => ("fa-comment-dots", "teal"), NotificationType.TaskAssignmentChanged => ("fa-user-pen", "amber"), + NotificationType.Mentioned => ("fa-at", "blue"), _ => ("fa-bell", "grey") }; string Age(DateTime utc) diff --git a/src/Presentation/Taskist.Web/wwwroot/css/pages/backlog-task.css b/src/Presentation/Taskist.Web/wwwroot/css/pages/backlog-task.css index ab3312d..fe6a32b 100644 --- a/src/Presentation/Taskist.Web/wwwroot/css/pages/backlog-task.css +++ b/src/Presentation/Taskist.Web/wwwroot/css/pages/backlog-task.css @@ -299,6 +299,72 @@ display: flex; gap: 8px; align-items: flex-end; + position: relative; +} + +.mention { + color: var(--cui-primary); + background: rgba(var(--cui-primary-rgb), 0.1); + border-radius: 4px; + padding: 0 3px; + font-weight: 600; + white-space: nowrap; +} + +.mention--unknown { + color: #8a93a2; + background: transparent; + font-weight: 400; +} + +.mention-menu { + position: absolute; + left: 0; + bottom: calc(100% + 4px); + z-index: 1060; + min-width: 220px; + max-width: 320px; + max-height: 240px; + overflow-y: auto; + margin: 0; + padding: 4px; + list-style: none; + background: #fff; + border: 1px solid #dde3ea; + border-radius: 8px; + box-shadow: 0 6px 18px rgba(16, 24, 40, 0.12); +} + +.mention-menu__item { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + padding: 6px 8px; + border: 0; + border-radius: 6px; + background: transparent; + color: #33455c; + font-size: 0.85rem; + text-align: left; +} + +.mention-menu__item:hover, +.mention-menu__item.is-active { + background: rgba(var(--cui-primary-rgb), 0.12); +} + +.mention-menu__item img { + width: 22px; + height: 22px; + border-radius: 50%; + object-fit: cover; +} + +.mention-menu__empty { + padding: 6px 8px; + font-size: 0.8rem; + color: #8a93a2; } .comment-input-wrap textarea { diff --git a/src/Presentation/Taskist.Web/wwwroot/css/theme-dark.generated.css b/src/Presentation/Taskist.Web/wwwroot/css/theme-dark.generated.css index 872f327..6e76e60 100644 --- a/src/Presentation/Taskist.Web/wwwroot/css/theme-dark.generated.css +++ b/src/Presentation/Taskist.Web/wwwroot/css/theme-dark.generated.css @@ -567,6 +567,13 @@ background: #212631; border-top: 1px solid #4a566d; } +[data-coreui-theme=dark] .mention-menu { + background: #212631; + border: 1px solid #4c5560; +} +[data-coreui-theme=dark] .mention-menu__item { + color: #bcc5d2; +} [data-coreui-theme=dark] .history-item::before { background: #303b46; } diff --git a/src/Presentation/Taskist.Web/wwwroot/js/pages/backlog/backlog-comments.js b/src/Presentation/Taskist.Web/wwwroot/js/pages/backlog/backlog-comments.js index 2685d04..f4323c6 100644 --- a/src/Presentation/Taskist.Web/wwwroot/js/pages/backlog/backlog-comments.js +++ b/src/Presentation/Taskist.Web/wwwroot/js/pages/backlog/backlog-comments.js @@ -28,6 +28,8 @@ var BacklogComments = (function () { var comment = $input.val().trim(); if (!comment) return; + if (window.BacklogMentions) comment = BacklogMentions.encode($root, comment); + var dto = { id: $root.data("task-id"), comment: comment, postToIssue: $root.find(".comment-post-to-issue").is(":checked") }; JSManager.ajaxPost($root.data("create-url"), dto, "comment-box", "Processing...", function (response) { if (!response || response.success !== true) { @@ -43,7 +45,9 @@ var BacklogComments = (function () { $item.find(".comment-avatar").html($('').attr("src", $root.data("photo-url") + "?userId=" + response.commentbyid)); $item.find(".comment-author").text(response.commentby); $item.find(".comment-time").text("just now"); - $item.find(".comment-text").text(comment); + if (typeof response.html === "string") $item.find(".comment-text").html(response.html); + else $item.find(".comment-text").text(comment); + if (window.BacklogMentions) BacklogMentions.reset($root); $list.append($item); $root.find(".comments-empty").addClass("d-none"); $input.val("").trigger("input").focus(); diff --git a/src/Presentation/Taskist.Web/wwwroot/js/pages/backlog/backlog-mentions.js b/src/Presentation/Taskist.Web/wwwroot/js/pages/backlog/backlog-mentions.js new file mode 100644 index 0000000..9fb1e15 --- /dev/null +++ b/src/Presentation/Taskist.Web/wwwroot/js/pages/backlog/backlog-mentions.js @@ -0,0 +1,157 @@ +var BacklogMentions = (function () { + "use strict"; + + var state = null; + var timer = null; + var requestNo = 0; + + function picked($root) { + var list = $root.data("mentions"); + if (!list) { + list = []; + $root.data("mentions", list); + } + return list; + } + + function encode($root, text) { + var list = picked($root).slice().sort(function (a, b) { return b.name.length - a.name.length; }); + list.forEach(function (m) { + text = text.split("@" + m.name).join(m.token); + }); + return text; + } + + function reset($root) { + $root.data("mentions", []); + close(); + } + + function queryAt(input) { + var caret = input.selectionStart; + if (caret !== input.selectionEnd) return null; + var match = /(^|\s)@([^\s@]{0,30})$/.exec(input.value.slice(0, caret)); + if (!match) return null; + return { start: caret - match[2].length - 1, term: match[2] }; + } + + function close() { + if (state && state.$menu) state.$menu.remove(); + state = null; + clearTimeout(timer); + } + + function render() { + if (!state) return; + if (!state.$menu) { + state.$menu = $('
    '); + state.$input.closest(".comment-input-wrap").append(state.$menu); + } + + state.$menu.empty(); + if (state.items.length === 0) { + state.$menu.append($('
  • ').text(state.$root.data("mention-empty") || "")); + return; + } + + state.items.forEach(function (item, i) { + var $btn = $('') + .toggleClass("is-active", i === state.index) + .attr("aria-selected", i === state.index ? "true" : "false") + .attr("data-index", i) + .append($('').attr("src", item.photo)) + .append($("").text(item.name)); + state.$menu.append($("
  • ").append($btn)); + }); + } + + function search(term) { + var url = state && state.$root.data("mention-url"); + if (!url) return; + + clearTimeout(timer); + timer = setTimeout(function () { + var current = ++requestNo; + $.ajax({ url: url, data: { q: term }, dataType: "json" }) + .done(function (items) { + if (!state || current !== requestNo) return; + state.items = items || []; + state.index = 0; + render(); + }) + .fail(close); + }, 150); + } + + function choose(item) { + if (!state || !item) return; + + var input = state.$input[0]; + var caret = input.selectionStart; + var insert = "@" + item.name + " "; + input.value = input.value.slice(0, state.start) + insert + input.value.slice(caret); + var position = state.start + insert.length; + input.setSelectionRange(position, position); + + var list = picked(state.$root); + if (!list.some(function (m) { return m.token === item.token; })) + list.push({ name: item.name, token: item.token }); + + var $input = state.$input; + close(); + $input.trigger("input").trigger("focus"); + } + + $(document).on("input click", ".comments-root .comment-input", function () { + var $input = $(this); + var query = queryAt(this); + if (!query) { + close(); + return; + } + + if (!state || state.$input[0] !== this) { + close(); + state = { $root: $input.closest(".comments-root"), $input: $input, $menu: null, items: [], index: 0 }; + } + + state.start = query.start; + search(query.term); + }); + + $(document).on("mousedown", ".mention-menu__item", function (e) { + e.preventDefault(); + if (state) choose(state.items[Number.parseInt($(this).attr("data-index"), 10)]); + }); + + $(document).on("blur", ".comments-root .comment-input", function () { + setTimeout(function () { + if (state && document.activeElement !== state.$input[0]) close(); + }, 150); + }); + + document.addEventListener("keydown", function (e) { + if (!state || !state.$menu || e.target !== state.$input[0]) return; + + if (e.key === "Escape") { + close(); + } else if (state.items.length === 0) { + return; + } else if (e.key === "ArrowDown") { + state.index = (state.index + 1) % state.items.length; + render(); + } else if (e.key === "ArrowUp") { + state.index = (state.index - 1 + state.items.length) % state.items.length; + render(); + } else if (e.key === "Enter" || e.key === "Tab") { + choose(state.items[state.index]); + } else { + return; + } + + e.preventDefault(); + e.stopPropagation(); + }, true); + + return { encode: encode, reset: reset }; +})(); diff --git a/src/Tests/Taskist.Tests/Common/MentionTextTests.cs b/src/Tests/Taskist.Tests/Common/MentionTextTests.cs new file mode 100644 index 0000000..23c8dec --- /dev/null +++ b/src/Tests/Taskist.Tests/Common/MentionTextTests.cs @@ -0,0 +1,89 @@ +using Taskist.Core.Common; + +namespace Taskist.Tests.Common; + +public class MentionTextTests +{ + #region Helpers + + private static readonly Dictionary Names = new() { [4] = "Bob Tester", [7] = "Cara " }; + + #endregion + + #region ParseUserIds + + [Fact] + public void ParseUserIds_ReturnsEachMentionOnce_InOrder() + { + Assert.Equal([7, 4], MentionText.ParseUserIds("@[7] please check, @[4] and @[7] again")); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("no mentions here")] + [InlineData("email bob@[example] or @[] or @[abc] or @[0]")] + [InlineData("@ [4] and @[ 4]")] + public void ParseUserIds_IgnoresTextThatIsNotAToken(string? text) + { + Assert.Empty(MentionText.ParseUserIds(text)); + } + + [Fact] + public void ParseUserIds_IgnoresOverlongIds() + { + Assert.Empty(MentionText.ParseUserIds("@[12345678901]")); + } + + [Fact] + public void Token_RoundTripsThroughTheParser() + { + Assert.Equal([42], MentionText.ParseUserIds("hi " + MentionText.Token(42))); + } + + #endregion + + #region ToPlainText + + [Fact] + public void ToPlainText_ReplacesTokensWithNames() + { + Assert.Equal("@Bob Tester can you look?", MentionText.ToPlainText("@[4] can you look?", Names)); + } + + [Fact] + public void ToPlainText_UnknownUser_IsNamedGenerically() + { + Assert.Equal("ping @unknown user", MentionText.ToPlainText("ping @[99]", Names)); + } + + #endregion + + #region ToHtml + + [Fact] + public void ToHtml_EncodesTextAndHighlightsMentions() + { + var html = MentionText.ToHtml("hi @[4] & @[7]", Names); + + Assert.Equal("<b>hi</b> @Bob Tester & " + + "@Cara <Ops>", html); + } + + [Fact] + public void ToHtml_UnknownUser_IsMarked_WithoutLeakingTheId() + { + var html = MentionText.ToHtml("@[99]", Names); + + Assert.Contains("mention--unknown", html); + Assert.DoesNotContain("99", html); + } + + [Fact] + public void ToHtml_KeepsNewlines_ForPreWrapDisplay() + { + Assert.Equal("a\nb", MentionText.ToHtml("a\nb", Names)); + } + + #endregion +}