Implement issue reporting and workflows
This commit is contained in:
1 parent
6ad3d5bbaa
commit
b80ec57589
23 files changed
+1407
-17
No files matched your search
@@ -1,5 +1,6 @@
|
||||
using Helpdesk.Domain.Auth;
|
||||
using Helpdesk.Domain.Catalogs;
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
@@ -12,6 +13,12 @@ public interface IAppDbContext
|
||||
DbSet<Building> Buildings { get; }
|
||||
DbSet<IssueCategory> IssueCategories { get; }
|
||||
DbSet<ProposalCategory> ProposalCategories { get; }
|
||||
DbSet<Issue> Issues { get; }
|
||||
DbSet<IssueEvent> IssueEvents { get; }
|
||||
DbSet<Attachment> Attachments { get; }
|
||||
DbSet<IssueNotification> IssueNotifications { get; }
|
||||
DbSet<NotificationDelivery> NotificationDeliveries { get; }
|
||||
DbSet<PushDevice> PushDevices { get; }
|
||||
|
||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using FluentValidation;
|
||||
using Helpdesk.Application.Auth;
|
||||
using Helpdesk.Application.Catalogs;
|
||||
using Helpdesk.Application.Issues;
|
||||
using Helpdesk.Application.Users;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -18,6 +19,7 @@ public static class DependencyInjection
|
||||
services.AddScoped<AuthService>();
|
||||
services.AddScoped<UserService>();
|
||||
services.AddScoped<CatalogService>();
|
||||
services.AddScoped<IssueService>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Helpdesk.Domain;
|
||||
using Helpdesk.Domain.Issues;
|
||||
|
||||
namespace Helpdesk.Application.Issues;
|
||||
|
||||
public record CreateIssueRequest(
|
||||
[Required, StringLength(200)] string Title,
|
||||
[Required] string Description,
|
||||
[Range(1, int.MaxValue)] int CategoryId,
|
||||
[Range(1, int.MaxValue)] int? BuildingId,
|
||||
[StringLength(255)] string? LocationDetail);
|
||||
|
||||
public sealed record EditIssueRequest(
|
||||
string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail,
|
||||
[Required, Range(0, int.MaxValue)] int? RowVersion)
|
||||
: CreateIssueRequest(Title, Description, CategoryId, BuildingId, LocationDetail);
|
||||
|
||||
public sealed record AssignIssueRequest(
|
||||
int AssigneeId, string? Priority, [Required, Range(0, int.MaxValue)] int? RowVersion);
|
||||
|
||||
public record IssueVersionRequest([Required, Range(0, int.MaxValue)] int? RowVersion);
|
||||
public sealed record VerifyIssueRequest(int? RowVersion, string? Note) : IssueVersionRequest(RowVersion);
|
||||
public sealed record IssueReasonRequest(int? RowVersion, string Reason) : IssueVersionRequest(RowVersion);
|
||||
public sealed record CommentRequest(string Text);
|
||||
|
||||
public sealed class IssueQuery
|
||||
{
|
||||
public string? Status { get; init; }
|
||||
public int? CategoryId { get; init; }
|
||||
public int? BuildingId { get; init; }
|
||||
public int? AssigneeId { get; init; }
|
||||
public int? ReporterId { get; init; }
|
||||
public DateTimeOffset? From { get; init; }
|
||||
public DateTimeOffset? To { get; init; }
|
||||
public string? Q { get; init; }
|
||||
public bool Mine { get; init; }
|
||||
public string? Sort { get; init; }
|
||||
public int Page { get; init; } = 1;
|
||||
public int PageSize { get; init; } = 20;
|
||||
}
|
||||
|
||||
public sealed record IssueSummary(
|
||||
int Id, string Title, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
|
||||
string Priority, int ReporterId, int? AssigneeId, DateTime CreatedAt)
|
||||
{
|
||||
internal static IssueSummary From(Issue issue) => new(
|
||||
issue.Id, issue.Title, issue.CategoryId, issue.BuildingId, issue.LocationDetail, issue.Status.ToCode(),
|
||||
issue.Priority.ToCode(), issue.ReporterId, issue.AssigneeId, issue.CreatedAt);
|
||||
}
|
||||
|
||||
public sealed record IssueDetail(
|
||||
int Id, string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
|
||||
string Priority, int ReporterId, int? AssigneeId, DateTime CreatedAt, int RowVersion,
|
||||
IReadOnlyList<string> AllowedActions, IReadOnlyList<AttachmentDto> Attachments);
|
||||
|
||||
public sealed record IssueEventDto(
|
||||
int Id, string EventType, string? FromStatus, string ToStatus, int ActorId, string ActorName, string? Note,
|
||||
DateTime OccurredAt);
|
||||
|
||||
public sealed record AssignableUserDto(int Id, string FirstName, string LastName, string Role, int OpenIssues);
|
||||
|
||||
public sealed record AttachmentDto(int Id, string FileName, string ContentType, long SizeBytes, DateTime CreatedAt)
|
||||
{
|
||||
internal static AttachmentDto From(Attachment attachment) => new(
|
||||
attachment.Id, attachment.OriginalFileName, attachment.ContentType, attachment.SizeBytes, attachment.CreatedAt);
|
||||
}
|
||||
|
||||
public sealed record AttachmentUpload(string FileName, long SizeBytes, Func<Stream> OpenRead);
|
||||
public sealed record StoredAttachment(string OriginalFileName, string StoredFileName, string ContentType, long SizeBytes);
|
||||
public sealed record AttachmentDownload(Stream Content, string FileName, string ContentType);
|
||||
|
||||
public interface IAttachmentStore
|
||||
{
|
||||
Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct);
|
||||
Stream OpenRead(string storedFileName);
|
||||
void Delete(string storedFileName);
|
||||
}
|
||||
|
||||
public static class AttachmentLimits
|
||||
{
|
||||
public const int MaxFiles = 5;
|
||||
public const int MaxFileBytes = 10 * 1024 * 1024;
|
||||
public const int MaxRequestBytes = MaxFiles * MaxFileBytes + 1024 * 1024;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Domain;
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Helpdesk.Application.Issues;
|
||||
|
||||
public sealed partial class IssueService
|
||||
{
|
||||
public async Task<PagedResult<IssueSummary>> ListAsync(IssueQuery filters, CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
var issues = db.Issues.AsNoTracking();
|
||||
if (filters.Mine || !Issue.CanReadAll(actor.Role))
|
||||
issues = issues.Where(i => i.ReporterId == actor.Id);
|
||||
|
||||
if (filters.Status is { } statusCode)
|
||||
{
|
||||
var status = ParseCode<IssueStatus>(statusCode);
|
||||
issues = issues.Where(i => i.Status == status);
|
||||
}
|
||||
if (filters.CategoryId is int categoryId)
|
||||
issues = issues.Where(i => i.CategoryId == categoryId);
|
||||
if (filters.BuildingId is int buildingId)
|
||||
issues = issues.Where(i => i.BuildingId == buildingId);
|
||||
if (filters.AssigneeId is int assigneeId)
|
||||
issues = issues.Where(i => i.AssigneeId == assigneeId);
|
||||
if (filters.ReporterId is int reporterId)
|
||||
issues = issues.Where(i => i.ReporterId == reporterId);
|
||||
if (filters.From >= filters.To)
|
||||
throw new BadRequestException("Začátek období musí předcházet jeho konci.");
|
||||
if (filters.From?.UtcDateTime is DateTime from)
|
||||
issues = issues.Where(i => i.CreatedAt >= from);
|
||||
if (filters.To?.UtcDateTime is DateTime to)
|
||||
issues = issues.Where(i => i.CreatedAt < to);
|
||||
if (!string.IsNullOrWhiteSpace(filters.Q))
|
||||
{
|
||||
var term = filters.Q.Trim();
|
||||
issues = issues.Where(i => i.Title.Contains(term) || i.Description.Contains(term));
|
||||
}
|
||||
|
||||
var ordered = filters.Sort switch
|
||||
{
|
||||
null or "newest" => issues.OrderByDescending(i => i.CreatedAt).ThenByDescending(i => i.Id),
|
||||
"oldest" => issues.OrderBy(i => i.CreatedAt).ThenBy(i => i.Id),
|
||||
_ => throw new BadRequestException("Řazení musí být newest nebo oldest."),
|
||||
};
|
||||
var page = Math.Max(1, filters.Page);
|
||||
var pageSize = Math.Clamp(filters.PageSize, 1, 100);
|
||||
var total = await issues.CountAsync(ct);
|
||||
var offset = (long)(page - 1) * pageSize;
|
||||
if (offset >= total)
|
||||
return new PagedResult<IssueSummary>([], total, page, pageSize);
|
||||
|
||||
var pageItems = await ordered.Skip((int)offset).Take(pageSize).ToListAsync(ct);
|
||||
return new PagedResult<IssueSummary>(pageItems.Select(IssueSummary.From).ToArray(), total, page, pageSize);
|
||||
}
|
||||
|
||||
public async Task<IssueDetail> GetAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
var issue = await LoadIssueAsync(id, actor, tracking: false, ct);
|
||||
return await LoadDetailAsync(issue, actor, ct);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<IssueEventDto>> GetEventsAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
await LoadIssueAsync(id, actor, tracking: false, ct);
|
||||
var entries = await (
|
||||
from entry in db.IssueEvents.AsNoTracking()
|
||||
join user in db.Users on entry.ActorId equals user.Id
|
||||
where entry.IssueId == id
|
||||
orderby entry.OccurredAt, entry.Id
|
||||
select new { Entry = entry, user.FirstName, user.LastName }).ToListAsync(ct);
|
||||
return entries.Select(entry => ToEvent(entry.Entry, $"{entry.FirstName} {entry.LastName}")).ToArray();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<AssignableUserDto>> GetAssignableAsync(CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
if (actor.Role != UserRole.Management)
|
||||
throw new ForbiddenException("Přehled řešitelů je určen vedení.");
|
||||
|
||||
var users = await db.Users.Where(u => u.IsActive && (u.Role == UserRole.Management || u.Role == UserRole.FacilityManager))
|
||||
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
|
||||
.Select(u => new
|
||||
{
|
||||
u.Id, u.FirstName, u.LastName, u.Role,
|
||||
OpenIssues = db.Issues.Count(i => i.AssigneeId == u.Id &&
|
||||
(i.Status == IssueStatus.Assigned || i.Status == IssueStatus.InProgress || i.Status == IssueStatus.PendingVerification)),
|
||||
}).ToListAsync(ct);
|
||||
return users.Select(u => new AssignableUserDto(u.Id, u.FirstName, u.LastName, u.Role.ToCode(), u.OpenIssues)).ToArray();
|
||||
}
|
||||
|
||||
public async Task<AttachmentDownload> DownloadAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
var attachment = await db.Attachments.AsNoTracking().Include(a => a.Issue).SingleOrDefaultAsync(a => a.Id == id, ct)
|
||||
?? throw new NotFoundException("Příloha neexistuje.");
|
||||
if (!attachment.Issue.CanRead(actor.Id, actor.Role))
|
||||
throw new ForbiddenException("K příloze nemáte přístup.");
|
||||
return new AttachmentDownload(files.OpenRead(attachment.StoredFileName), attachment.OriginalFileName, attachment.ContentType);
|
||||
}
|
||||
|
||||
private async Task<IssueDetail> LoadDetailAsync(Issue issue, User actor, CancellationToken ct)
|
||||
{
|
||||
var attachments = await db.Attachments.AsNoTracking().Where(a => a.IssueId == issue.Id).OrderBy(a => a.Id)
|
||||
.Select(a => new AttachmentDto(a.Id, a.OriginalFileName, a.ContentType, a.SizeBytes, a.CreatedAt)).ToListAsync(ct);
|
||||
return ToDetail(issue, actor, attachments);
|
||||
}
|
||||
|
||||
private static IssueDetail ToDetail(Issue issue, User actor, IReadOnlyList<AttachmentDto> attachments)
|
||||
{
|
||||
var actions = Enum.GetValues<IssueAction>()
|
||||
.Where(action => issue.Availability(action, actor.Id, actor.Role) == IssueActionAvailability.Allowed)
|
||||
.Select(action => action.ToCode()).ToArray();
|
||||
|
||||
return new IssueDetail(issue.Id, issue.Title, issue.Description, issue.CategoryId, issue.BuildingId, issue.LocationDetail,
|
||||
issue.Status.ToCode(), issue.Priority.ToCode(), issue.ReporterId, issue.AssigneeId, issue.CreatedAt,
|
||||
issue.RowVersion, actions, attachments);
|
||||
}
|
||||
|
||||
private static IssueEventDto ToEvent(IssueEvent entry, string actorName) =>
|
||||
new(entry.Id, entry.EventType.ToCode(), entry.FromStatus?.ToCode(), entry.ToStatus.ToCode(),
|
||||
entry.ActorId, actorName, entry.Note, entry.OccurredAt);
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
using System.Text;
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Domain;
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Helpdesk.Domain.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Helpdesk.Application.Issues;
|
||||
|
||||
public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentUser, IAttachmentStore files, TimeProvider clock)
|
||||
{
|
||||
public async Task<IssueDetail> CreateAsync(CreateIssueRequest request, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
await ValidateDetailsAsync(request, null, ct);
|
||||
var issue = new Issue(actor.Id, request.Title, request.Description, request.CategoryId, request.BuildingId, request.LocationDetail);
|
||||
db.Issues.Add(issue);
|
||||
AddEvent(issue, IssueEventType.Created, null, actor, null);
|
||||
var managementIds = await db.Users.Where(u => u.IsActive && u.Role == UserRole.Management)
|
||||
.Select(u => u.Id).ToArrayAsync(ct);
|
||||
await NotifyAsync(issue, actor.Id, managementIds, NotificationType.IssueCreated, "Nové hlášení závady", ct);
|
||||
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
|
||||
return ToDetail(issue, actor, attachments.Select(AttachmentDto.From).ToArray());
|
||||
}
|
||||
|
||||
public async Task<IssueDetail> EditAsync(int id, EditIssueRequest request, CancellationToken ct)
|
||||
{
|
||||
var (issue, actor) = await LoadActionAsync(id, IssueAction.Edit, ct);
|
||||
CheckVersion(issue, request.RowVersion);
|
||||
await ValidateDetailsAsync(request, issue, ct);
|
||||
issue.Edit(actor.Id, actor.Role, request.Title, request.Description, request.CategoryId, request.BuildingId, request.LocationDetail);
|
||||
AddEvent(issue, IssueEventType.Updated, null, actor, null);
|
||||
await SaveAsync(ct);
|
||||
return await LoadDetailAsync(issue, actor, ct);
|
||||
}
|
||||
|
||||
public async Task<IssueDetail> AssignAsync(int id, AssignIssueRequest request, CancellationToken ct)
|
||||
{
|
||||
var (issue, actor) = await LoadActionAsync(id, IssueAction.Assign, ct);
|
||||
CheckVersion(issue, request.RowVersion);
|
||||
var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct);
|
||||
if (assignee is null || !Issue.CanBeAssigned(assignee.Role))
|
||||
throw new BadRequestException("Vyberte aktivního správce budov nebo člena vedení.");
|
||||
if (issue.AssigneeId == assignee.Id)
|
||||
throw new ConflictException("Závada je již přiřazena tomuto řešiteli.");
|
||||
|
||||
IssuePriority? priority = request.Priority is null ? null : ParseCode<IssuePriority>(request.Priority);
|
||||
var from = issue.Status;
|
||||
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
|
||||
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName);
|
||||
await NotifyAsync(issue, actor.Id, [assignee.Id], NotificationType.IssueAssigned, "Závada byla přiřazena", ct);
|
||||
if (from == IssueStatus.Received && issue.ReporterId != assignee.Id)
|
||||
await NotifyAsync(issue, actor.Id, [issue.ReporterId], NotificationType.IssueStatusChanged, "Závada byla přiřazena", ct);
|
||||
|
||||
await SaveAsync(ct);
|
||||
return await LoadDetailAsync(issue, actor, ct);
|
||||
}
|
||||
|
||||
public async Task<IssueDetail> TransitionAsync(int id, IssueAction action, int? version, string? note, CancellationToken ct)
|
||||
{
|
||||
var (issue, actor) = await LoadActionAsync(id, action, ct);
|
||||
CheckVersion(issue, version);
|
||||
note = action is IssueAction.Reopen or IssueAction.Reject
|
||||
? RequiredText(note, "Důvod", MaxTextBytes)
|
||||
: OptionalText(note, "Poznámka", MaxTextBytes);
|
||||
|
||||
var from = issue.Status;
|
||||
issue.Transition(action, actor.Id, actor.Role, note);
|
||||
AddEvent(issue, IssueEventType.StatusChanged, from, actor, note);
|
||||
int? recipient = action is IssueAction.Confirm or IssueAction.Reopen ? issue.AssigneeId : issue.ReporterId;
|
||||
if (recipient is int recipientId)
|
||||
{
|
||||
var (type, title) = action == IssueAction.Reopen
|
||||
? (NotificationType.IssueReopened, "Závada byla znovu otevřena")
|
||||
: (NotificationType.IssueStatusChanged, "Stav závady se změnil");
|
||||
await NotifyAsync(issue, actor.Id, [recipientId], type, title, ct);
|
||||
}
|
||||
|
||||
await SaveAsync(ct);
|
||||
return await LoadDetailAsync(issue, actor, ct);
|
||||
}
|
||||
|
||||
public async Task<IssueEventDto> CommentAsync(int id, CommentRequest request, CancellationToken ct)
|
||||
{
|
||||
var (issue, actor) = await LoadActionAsync(id, IssueAction.Comment, ct);
|
||||
var text = RequiredText(request.Text, "Komentář", MaxTextBytes);
|
||||
issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role);
|
||||
var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text);
|
||||
int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId];
|
||||
await NotifyAsync(issue, actor.Id, recipients, NotificationType.IssueCommentAdded, "Nový komentář k závadě", ct);
|
||||
await SaveAsync(ct);
|
||||
return ToEvent(entry, actor.FullName);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<AttachmentDto>> AddAttachmentsAsync(
|
||||
int id, Func<CancellationToken, Task<AttachmentUpload[]>> readUploads, CancellationToken ct)
|
||||
{
|
||||
var (issue, actor) = await LoadActionAsync(id, IssueAction.AddAttachments, ct);
|
||||
var uploads = await readUploads(ct);
|
||||
if (uploads.Length == 0)
|
||||
throw new BadRequestException("Vyberte alespoň jeden soubor.");
|
||||
|
||||
issue.RecordParticipation(IssueAction.AddAttachments, actor.Id, actor.Role);
|
||||
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
|
||||
return attachments.Select(AttachmentDto.From).ToArray();
|
||||
}
|
||||
|
||||
private async Task<IReadOnlyList<Attachment>> SaveWithAttachmentsAsync(
|
||||
Issue issue, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
|
||||
{
|
||||
if (uploads.Count > AttachmentLimits.MaxFiles)
|
||||
throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů.");
|
||||
|
||||
var attachments = new List<Attachment>(uploads.Count);
|
||||
var saving = false;
|
||||
try
|
||||
{
|
||||
foreach (var upload in uploads)
|
||||
{
|
||||
var stored = await files.SaveAsync(upload, ct);
|
||||
var attachment = new Attachment(issue, stored.OriginalFileName, stored.StoredFileName,
|
||||
stored.ContentType, stored.SizeBytes);
|
||||
attachments.Add(attachment);
|
||||
db.Attachments.Add(attachment);
|
||||
}
|
||||
|
||||
ct.ThrowIfCancellationRequested();
|
||||
saving = true;
|
||||
await SaveAsync(ct);
|
||||
return attachments;
|
||||
}
|
||||
catch (Exception exception) when (!saving || exception is ConflictException)
|
||||
{
|
||||
// Po chybě s neznámým výsledkem commitu soubory ponecháme, aby metadata nemohla odkazovat na smazaná data.
|
||||
foreach (var attachment in attachments)
|
||||
files.Delete(attachment.StoredFileName);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<User> GetActorAsync(CancellationToken ct) =>
|
||||
await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == currentUser.Id && u.IsActive, ct)
|
||||
?? throw new UnauthorizedException("Účet není aktivní.");
|
||||
|
||||
private async Task<Issue> LoadIssueAsync(int id, User actor, bool tracking, CancellationToken ct)
|
||||
{
|
||||
var query = tracking ? db.Issues : db.Issues.AsNoTracking();
|
||||
var issue = await query.SingleOrDefaultAsync(i => i.Id == id, ct)
|
||||
?? throw new NotFoundException("Závada neexistuje.");
|
||||
if (!issue.CanRead(actor.Id, actor.Role))
|
||||
throw new ForbiddenException("K závadě nemáte přístup.");
|
||||
return issue;
|
||||
}
|
||||
|
||||
private async Task<(Issue Issue, User Actor)> LoadActionAsync(int id, IssueAction action, CancellationToken ct)
|
||||
{
|
||||
var actor = await GetActorAsync(ct);
|
||||
var issue = await LoadIssueAsync(id, actor, tracking: true, ct);
|
||||
switch (issue.Availability(action, actor.Id, actor.Role))
|
||||
{
|
||||
case IssueActionAvailability.Forbidden:
|
||||
throw new ForbiddenException("Tuto akci nemůžete provést.");
|
||||
case IssueActionAvailability.InvalidState:
|
||||
throw new ConflictException("Akce není v aktuálním stavu závady možná.");
|
||||
}
|
||||
return (issue, actor);
|
||||
}
|
||||
|
||||
private async Task ValidateDetailsAsync(CreateIssueRequest request, Issue? original, CancellationToken ct)
|
||||
{
|
||||
var title = RequiredText(request.Title, "Název", MaxTextBytes);
|
||||
RequiredText(request.Description, "Popis", MaxTextBytes);
|
||||
if (title.Length > 200 || request.LocationDetail?.Trim().Length > 255)
|
||||
throw new BadRequestException("Název smí mít nejvýše 200 znaků a upřesnění místa 255 znaků.");
|
||||
|
||||
if (original?.CategoryId != request.CategoryId &&
|
||||
!await db.IssueCategories.AnyAsync(c => c.Id == request.CategoryId && c.IsActive, ct))
|
||||
throw new BadRequestException("Vyberte aktivní kategorii závady.");
|
||||
|
||||
if (request.BuildingId is int buildingId && original?.BuildingId != buildingId &&
|
||||
!await db.Buildings.AnyAsync(b => b.Id == buildingId && b.IsActive, ct))
|
||||
throw new BadRequestException("Vyberte aktivní budovu.");
|
||||
}
|
||||
|
||||
private IssueEvent AddEvent(Issue issue, IssueEventType type, IssueStatus? fromStatus, User actor, string? note)
|
||||
{
|
||||
var entry = new IssueEvent(issue, type, fromStatus, actor.Id, note, clock.GetUtcNow().UtcDateTime);
|
||||
db.IssueEvents.Add(entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
private async Task NotifyAsync(Issue issue, int actorId, int[] recipientIds, NotificationType type, string title, CancellationToken ct)
|
||||
{
|
||||
var ids = recipientIds.Where(id => id != actorId).Distinct().ToArray();
|
||||
if (ids.Length == 0)
|
||||
return;
|
||||
|
||||
var reporterId = issue.ReporterId;
|
||||
var recipients = await db.Users.Where(u => u.IsActive && ids.Contains(u.Id) &&
|
||||
(u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management))
|
||||
.Select(u => new
|
||||
{
|
||||
u.Id,
|
||||
Email = u.EmailNotificationsEnabled && u.EmailConfirmed,
|
||||
Push = db.PushDevices.Any(device => device.UserId == u.Id),
|
||||
}).ToListAsync(ct);
|
||||
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
foreach (var recipient in recipients)
|
||||
{
|
||||
var notification = new IssueNotification(issue, recipient.Id, type, title, issue.Title);
|
||||
db.IssueNotifications.Add(notification);
|
||||
db.NotificationDeliveries.AddRange(
|
||||
new NotificationDelivery(notification, DeliveryChannel.Email, recipient.Email, now),
|
||||
new NotificationDelivery(notification, DeliveryChannel.Push, recipient.Push, now));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
|
||||
}
|
||||
}
|
||||
|
||||
private static void CheckVersion(Issue issue, int? supplied)
|
||||
{
|
||||
if (supplied is null or < 0)
|
||||
throw new BadRequestException("Zadejte platnou hodnotu rowVersion.");
|
||||
if (issue.RowVersion != supplied)
|
||||
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
|
||||
}
|
||||
|
||||
private const int MaxTextBytes = 65_535;
|
||||
|
||||
private static string RequiredText(string? input, string name, int maxBytes) =>
|
||||
OptionalText(input, name, maxBytes) ?? throw new BadRequestException($"{name}: hodnota je povinná.");
|
||||
|
||||
private static string? OptionalText(string? input, string name, int maxBytes)
|
||||
{
|
||||
var text = input?.Trim();
|
||||
if (string.IsNullOrEmpty(text))
|
||||
return null;
|
||||
if (Encoding.UTF8.GetByteCount(text) > maxBytes)
|
||||
throw new BadRequestException($"{name}: hodnota je příliš dlouhá.");
|
||||
return text;
|
||||
}
|
||||
|
||||
private static T ParseCode<T>(string code) where T : struct, Enum =>
|
||||
EnumCode.TryParse<T>(code, out var result)
|
||||
? result
|
||||
: throw new BadRequestException($"Neplatný kód '{code}'.");
|
||||
}
|
||||
Reference in new issue
Block a user