Implement issue reporting and workflows

This commit is contained in:
GonnaHetzMe committed 2026-11-18 18:32:59 +01:00
1 parent 6ad3d5bbaa
commit b80ec57589
23 files changed
+1407 -17

No files matched your search

@@ -1,6 +1,8 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Issues;
using Helpdesk.Infrastructure.Background;
using Helpdesk.Infrastructure.Email;
using Helpdesk.Infrastructure.Files;
using Helpdesk.Infrastructure.Persistence;
using Helpdesk.Infrastructure.Security;
using Microsoft.EntityFrameworkCore;
@@ -32,6 +34,7 @@ public static class DependencyInjection
services.AddSingleton<ITokenService, JwtTokenService>();
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
services.AddSingleton<IEmailSender, LoggingEmailSender>();
services.AddSingleton<IAttachmentStore, FileAttachmentStore>();
services.AddHostedService<RevokedTokenStoreLoader>();
services.AddHostedService<AdminSeeder>();
@@ -0,0 +1,155 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Helpdesk.Application.Common;
using Helpdesk.Application.Issues;
using Microsoft.Extensions.Logging;
namespace Helpdesk.Infrastructure.Files;
internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) : IAttachmentStore
{
private readonly string directory = Path.Combine(AppContext.BaseDirectory, "uploads");
public async Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct)
{
if (upload.SizeBytes is <= 0 or > AttachmentLimits.MaxFileBytes)
throw new BadRequestException("Příloha musí mít velikost od 1 B do 10 MB.");
var name = Path.GetFileName(upload.FileName.Replace('\\', '/')).Trim();
if (name.Length is 0 or > 255 || name.Any(char.IsControl))
throw new BadRequestException("Neplatný název přílohy.");
var extension = Path.GetExtension(name).ToLowerInvariant();
var contentType = extension switch
{
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".heic" => "image/heic",
".pdf" => "application/pdf",
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
_ => throw new BadRequestException("Tento typ přílohy není povolen."),
};
Directory.CreateDirectory(directory);
var key = Guid.NewGuid().ToString("D");
var path = FilePath(key);
var created = false;
try
{
await using var input = upload.OpenRead();
await using var output = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None,
bufferSize: 64 * 1024, useAsync: true);
created = true;
var buffer = new byte[64 * 1024];
long written = 0;
int read;
while ((read = await input.ReadAsync(buffer, ct)) > 0)
{
written += read;
if (written > upload.SizeBytes)
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
await output.WriteAsync(buffer.AsMemory(0, read), ct);
}
if (written != upload.SizeBytes)
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
output.Position = 0;
if (!await HasExpectedFormatAsync(output, extension, ct))
throw new BadRequestException("Obsah přílohy neodpovídá její příponě.");
return new StoredAttachment(name, key, contentType, written);
}
catch
{
if (created)
Delete(key);
throw;
}
}
public Stream OpenRead(string storedFileName)
{
try
{
return new FileStream(FilePath(storedFileName), FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 64 * 1024, useAsync: true);
}
catch (IOException exception) when (exception is FileNotFoundException or DirectoryNotFoundException)
{
logger.LogError(exception, "Soubor přílohy {AttachmentKey} v úložišti chybí.", storedFileName);
throw new NotFoundException("Soubor přílohy není dostupný.");
}
}
public void Delete(string storedFileName)
{
try
{
File.Delete(FilePath(storedFileName));
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
logger.LogError(exception, "Soubor přílohy {AttachmentKey} se nepodařilo uklidit.", storedFileName);
}
}
private string FilePath(string key) => Guid.TryParseExact(key, "D", out _)
? Path.Combine(directory, key)
: throw new InvalidOperationException("Neplatný klíč souboru přílohy.");
private static async Task<bool> HasExpectedFormatAsync(Stream stream, string extension, CancellationToken ct)
{
var header = new byte[(int)Math.Min(stream.Length, 512)];
await stream.ReadExactlyAsync(header, ct);
return extension switch
{
".jpg" or ".jpeg" => header.AsSpan().StartsWith(new byte[] { 0xff, 0xd8, 0xff }),
".png" => header.AsSpan().StartsWith(new byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a }),
".pdf" => header.AsSpan().StartsWith("%PDF-"u8),
".heic" => IsHeic(header, stream.Length),
".docx" => IsDocx(stream, header),
_ => false,
};
}
private static bool IsHeic(ReadOnlySpan<byte> header, long length)
{
if (header.Length < 16 || !header.Slice(4, 4).SequenceEqual("ftyp"u8))
return false;
var boxLength = BinaryPrimitives.ReadUInt32BigEndian(header);
if (boxLength < 16 || boxLength > length)
return false;
for (var offset = 8; offset + 4 <= Math.Min(boxLength, header.Length); offset += 4)
{
if (offset == 12)
continue; // minor_version
var brand = header.Slice(offset, 4);
if (brand.SequenceEqual("heic"u8) || brand.SequenceEqual("heix"u8) ||
brand.SequenceEqual("hevc"u8) || brand.SequenceEqual("hevx"u8))
return true;
}
return false;
}
private static bool IsDocx(Stream stream, ReadOnlySpan<byte> header)
{
if (!header.StartsWith(new byte[] { 0x50, 0x4b, 0x03, 0x04 }))
return false;
stream.Position = 0;
try
{
using var zip = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: true);
return zip.GetEntry("[Content_Types].xml") is not null && zip.GetEntry("word/document.xml") is not null;
}
catch (InvalidDataException)
{
return false;
}
}
}
@@ -1,6 +1,7 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Catalogs;
using Helpdesk.Domain.Issues;
using Helpdesk.Domain.Users;
using Helpdesk.Infrastructure.Security;
using Microsoft.EntityFrameworkCore;
@@ -20,6 +21,12 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
public DbSet<Building> Buildings => Set<Building>();
public DbSet<IssueCategory> IssueCategories => Set<IssueCategory>();
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
public DbSet<Issue> Issues => Set<Issue>();
public DbSet<IssueEvent> IssueEvents => Set<IssueEvent>();
public DbSet<Attachment> Attachments => Set<Attachment>();
public DbSet<IssueNotification> IssueNotifications => Set<IssueNotification>();
public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>();
public DbSet<PushDevice> PushDevices => Set<PushDevice>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -28,6 +35,12 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
modelBuilder.ApplyConfiguration(new BuildingConfiguration());
modelBuilder.ApplyConfiguration(new IssueCategoryConfiguration());
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
modelBuilder.ApplyConfiguration(new IssueConfiguration());
modelBuilder.ApplyConfiguration(new IssueEventConfiguration());
modelBuilder.ApplyConfiguration(new AttachmentConfiguration());
modelBuilder.ApplyConfiguration(new IssueNotificationConfiguration());
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
modelBuilder.Entity<PushDevice>().ToTable("push_device");
}
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
@@ -0,0 +1,75 @@
using Helpdesk.Domain.Catalogs;
using Helpdesk.Domain.Issues;
using Helpdesk.Domain.Users;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Helpdesk.Infrastructure.Persistence;
internal sealed class IssueConfiguration : IEntityTypeConfiguration<Issue>
{
public void Configure(EntityTypeBuilder<Issue> b)
{
b.ToTable("issue");
b.Property(x => x.Title).HasMaxLength(200);
b.Property(x => x.Description).HasColumnType("text");
b.Property(x => x.LocationDetail).HasMaxLength(255);
b.Property(x => x.Status).HasConversion<EnumCodeConverter<IssueStatus>>().HasMaxLength(30);
b.Property(x => x.Priority).HasConversion<EnumCodeConverter<IssuePriority>>().HasMaxLength(10);
b.Property(x => x.RowVersion).IsConcurrencyToken();
b.HasOne<IssueCategory>().WithMany().HasForeignKey(x => x.CategoryId);
b.HasOne<Building>().WithMany().HasForeignKey(x => x.BuildingId);
b.HasOne<User>().WithMany().HasForeignKey(x => x.ReporterId);
b.HasOne<User>().WithMany().HasForeignKey(x => x.AssigneeId);
}
}
internal sealed class IssueEventConfiguration : IEntityTypeConfiguration<IssueEvent>
{
public void Configure(EntityTypeBuilder<IssueEvent> b)
{
b.ToTable("issue_event");
b.Property(x => x.EventType).HasConversion<EnumCodeConverter<IssueEventType>>().HasMaxLength(20);
b.Property(x => x.FromStatus).HasConversion<EnumCodeConverter<IssueStatus>>().HasMaxLength(30);
b.Property(x => x.ToStatus).HasConversion<EnumCodeConverter<IssueStatus>>().HasMaxLength(30);
b.Property(x => x.Note).HasColumnType("text");
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId);
b.HasOne<User>().WithMany().HasForeignKey(x => x.ActorId);
}
}
internal sealed class AttachmentConfiguration : IEntityTypeConfiguration<Attachment>
{
public void Configure(EntityTypeBuilder<Attachment> b)
{
b.ToTable("attachment");
b.Property(x => x.OriginalFileName).HasMaxLength(255);
b.Property(x => x.StoredFileName).HasMaxLength(36);
b.Property(x => x.ContentType).HasMaxLength(100);
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId);
}
}
internal sealed class IssueNotificationConfiguration : IEntityTypeConfiguration<IssueNotification>
{
public void Configure(EntityTypeBuilder<IssueNotification> b)
{
b.ToTable("notification");
b.Property(x => x.Type).HasConversion<EnumCodeConverter<NotificationType>>().HasMaxLength(40);
b.Property(x => x.Title).HasMaxLength(200);
b.Property(x => x.Message).HasMaxLength(1000);
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId).IsRequired(false);
b.HasOne<User>().WithMany().HasForeignKey(x => x.UserId);
}
}
internal sealed class NotificationDeliveryConfiguration : IEntityTypeConfiguration<NotificationDelivery>
{
public void Configure(EntityTypeBuilder<NotificationDelivery> b)
{
b.ToTable("notification_delivery");
b.Property(x => x.Channel).HasConversion<EnumCodeConverter<DeliveryChannel>>().HasMaxLength(10);
b.Property(x => x.Status).HasConversion<EnumCodeConverter<DeliveryStatus>>().HasMaxLength(10);
b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId);
}
}