Implement message preview feature for support tickets
CI / Backend (build + test) (push) Successful in 1m15s
CI / Frontend (lint + typecheck + build) (push) Successful in 30s

- Added a new property `MessagePreview` to the `TicketSummaryDto` to display the truncated first message of a ticket.
- Updated the `TicketMapping` class to retrieve the first message for each ticket and truncate it for preview purposes.
- Modified the `SupportTicketList` and `AdminSupportPage` components to conditionally render the message preview in the ticket list, enhancing user experience by providing context at a glance.
This commit is contained in:
Leonid Pershin
2026-07-14 07:47:57 +03:00
parent d26723dce0
commit 9a6540a266
6 changed files with 115 additions and 5 deletions
@@ -99,6 +99,18 @@ internal static class TicketMapping
.Select(g => new { TicketId = g.Key, Last = g.Max(c => c.CreatedAt) })
.ToDictionaryAsync(x => x.TicketId, x => x.Last, cancellationToken);
// Первое сообщение (не последний комментарий) — это исходный текст обращения, а не переписка.
var firstMessages = await dbContext
.TicketComments.AsNoTracking()
.Where(c => ticketIds.Contains(c.TicketId))
.GroupBy(c => c.TicketId)
.Select(g => new
{
TicketId = g.Key,
Body = g.OrderBy(c => c.CreatedAt).Select(c => c.Body).First(),
})
.ToDictionaryAsync(x => x.TicketId, x => x.Body, cancellationToken);
var userIds = tickets.Select(t => t.UserId).Distinct().ToList();
var userNames = await identityService.GetUserNamesAsync(userIds, cancellationToken);
@@ -110,8 +122,17 @@ internal static class TicketMapping
t.Type,
t.Status,
t.CreatedAt,
lastActivity.GetValueOrDefault(t.Id, t.CreatedAt)
lastActivity.GetValueOrDefault(t.Id, t.CreatedAt),
TruncatePreview(firstMessages.GetValueOrDefault(t.Id))
))
.ToList();
}
private static string? TruncatePreview(string? message)
{
if (string.IsNullOrEmpty(message))
return message;
return message.Length > 200 ? message[..200] + "…" : message;
}
}
@@ -3,7 +3,8 @@ using PnvPanel.Domain.Support;
namespace PnvPanel.Application.Support;
/// <summary>Строка списка тикетов — свой (ListMyTicketsQuery) и админский (ListAllTicketsQuery) списки
/// используют один и тот же DTO (владелец видит только свои UserId/UserName — не секрет для себя).</summary>
/// используют один и тот же DTO (владелец видит только свои UserId/UserName — не секрет для себя).
/// MessagePreview — начало первого сообщения тикета (обрезано), для превью в списке.</summary>
public sealed record TicketSummaryDto(
Guid Id,
Guid UserId,
@@ -11,5 +12,6 @@ public sealed record TicketSummaryDto(
TicketType Type,
TicketStatus Status,
DateTimeOffset CreatedAt,
DateTimeOffset LastActivityAt
DateTimeOffset LastActivityAt,
string? MessagePreview
);
@@ -0,0 +1,84 @@
using NSubstitute;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Support;
using PnvPanel.Application.Support.ListMyTickets;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Support;
using Xunit;
namespace PnvPanel.Application.Tests.Support;
public class ListMyTicketsQueryHandlerTests
{
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
[Fact]
public async Task Handle_ReturnsFirstMessageAsPreview_NotLastComment()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var ticket = SupportTicket.CreateBugReport(userId);
dbContext.SupportTickets.Add(ticket);
var firstComment = TicketComment.Create(ticket.Id, userId, "исходное сообщение о баге");
dbContext.TicketComments.Add(firstComment);
await dbContext.SaveChangesAsync(CancellationToken.None);
// Гарантируем, что второй комментарий получит более поздний CreatedAt (UtcNow может
// совпасть при быстром последовательном создании без явного clock-абстрагирования).
await Task.Delay(5, CancellationToken.None);
var replyComment = TicketComment.Create(
ticket.Id,
userId,
"более поздний ответ администратора"
);
dbContext.TicketComments.Add(replyComment);
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService
.GetUserNamesAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(new Dictionary<Guid, string> { [userId] = "alice" });
var currentUser = FakeCurrentUser.Authenticated(userId, "alice");
var handler = new ListMyTicketsQueryHandler(dbContext, _identityService, currentUser);
var result = await handler.Handle(
new ListMyTicketsQuery(TypeFilter: null, StatusFilter: null, Page: 1, PageSize: 20),
CancellationToken.None
);
Assert.True(result.IsSuccess);
var summary = Assert.Single(result.Value.Items);
Assert.Equal("исходное сообщение о баге", summary.MessagePreview);
}
[Fact]
public async Task Handle_TruncatesLongMessagePreview()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var ticket = SupportTicket.CreateBugReport(userId);
dbContext.SupportTickets.Add(ticket);
var longBody = new string('x', 250);
dbContext.TicketComments.Add(TicketComment.Create(ticket.Id, userId, longBody));
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService
.GetUserNamesAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
.Returns(new Dictionary<Guid, string> { [userId] = "alice" });
var currentUser = FakeCurrentUser.Authenticated(userId, "alice");
var handler = new ListMyTicketsQueryHandler(dbContext, _identityService, currentUser);
var result = await handler.Handle(
new ListMyTicketsQuery(TypeFilter: null, StatusFilter: null, Page: 1, PageSize: 20),
CancellationToken.None
);
Assert.True(result.IsSuccess);
var summary = Assert.Single(result.Value.Items);
Assert.Equal(201, summary.MessagePreview!.Length);
Assert.EndsWith("…", summary.MessagePreview);
}
}