From b80ec5758908bdd6c97ffb7fd2ea820ddd230012 Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Wed, 18 Nov 2026 18:32:59 +0100 Subject: [PATCH] Implement issue reporting and workflows --- .dockerignore | 11 + README.md | 2 +- .../Controllers/AttachmentsController.cs | 23 ++ .../Controllers/IssuesController.cs | 188 +++++++++++++ .../Controllers/UsersController.cs | 11 +- .../Infrastructure/AppExceptionHandler.cs | 1 + .../Infrastructure/AuthenticationSetup.cs | 1 + .../Infrastructure/SwaggerSetup.cs | 64 +++++ backend/src/Helpdesk.Api/Program.cs | 13 +- .../Abstractions/Abstractions.cs | 7 + .../DependencyInjection.cs | 2 + .../Helpdesk.Application/Issues/IssueDtos.cs | 85 ++++++ .../Issues/IssueService.Reads.cs | 128 +++++++++ .../Issues/IssueService.cs | 259 ++++++++++++++++++ backend/src/Helpdesk.Domain/Issues/Issue.cs | 137 +++++++++ .../Issues/IssueNotification.cs | 39 +++ .../Helpdesk.Domain/Issues/IssueRecords.cs | 43 +++ .../DependencyInjection.cs | 3 + .../Files/FileAttachmentStore.cs | 155 +++++++++++ .../Persistence/HelpdeskDbContext.cs | 13 + .../Persistence/IssueConfigurations.cs | 75 +++++ .../tests/Helpdesk.UnitTests/IssueTests.cs | 136 +++++++++ docs/navrh-aplikace.md | 28 +- 23 files changed, 1407 insertions(+), 17 deletions(-) create mode 100644 .dockerignore create mode 100644 backend/src/Helpdesk.Api/Controllers/AttachmentsController.cs create mode 100644 backend/src/Helpdesk.Api/Controllers/IssuesController.cs create mode 100644 backend/src/Helpdesk.Application/Issues/IssueDtos.cs create mode 100644 backend/src/Helpdesk.Application/Issues/IssueService.Reads.cs create mode 100644 backend/src/Helpdesk.Application/Issues/IssueService.cs create mode 100644 backend/src/Helpdesk.Domain/Issues/Issue.cs create mode 100644 backend/src/Helpdesk.Domain/Issues/IssueNotification.cs create mode 100644 backend/src/Helpdesk.Domain/Issues/IssueRecords.cs create mode 100644 backend/src/Helpdesk.Infrastructure/Files/FileAttachmentStore.cs create mode 100644 backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs create mode 100644 backend/tests/Helpdesk.UnitTests/IssueTests.cs diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..d4463eb --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +** +!backend/Directory.Build.props +!backend/Directory.Packages.props +!backend/src/ +!db/migrations/ +backend/**/bin +backend/**/obj +**/.env +**/*.env +**/*.pem +**/*.pfx diff --git a/README.md b/README.md index 012efb1..34720be 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ Při prvním startu se vytvoří účet administrátora z `ADMIN_EMAIL` / `ADMIN Vyžaduje .NET SDK 10. Unit testy: ```bash -dotnet test --solution backend/Helpdesk.sln +dotnet run --project backend/tests/Helpdesk.UnitTests/Helpdesk.UnitTests.csproj ``` ## Verzování databáze diff --git a/backend/src/Helpdesk.Api/Controllers/AttachmentsController.cs b/backend/src/Helpdesk.Api/Controllers/AttachmentsController.cs new file mode 100644 index 0000000..4e0ee6b --- /dev/null +++ b/backend/src/Helpdesk.Api/Controllers/AttachmentsController.cs @@ -0,0 +1,23 @@ +using Helpdesk.Application.Issues; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Helpdesk.Api.Controllers; + +[ApiController] +[Authorize] +[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] +[Route("api/attachments")] +public sealed class AttachmentsController(IssueService issues) : ControllerBase +{ + [HttpGet("{id:int}")] + [ProducesResponseType(StatusCodes.Status200OK, "application/octet-stream")] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task Download(int id, CancellationToken ct) + { + var file = await issues.DownloadAsync(id, ct); + Response.Headers["X-Content-Type-Options"] = "nosniff"; + return File(file.Content, file.ContentType, file.FileName); + } +} diff --git a/backend/src/Helpdesk.Api/Controllers/IssuesController.cs b/backend/src/Helpdesk.Api/Controllers/IssuesController.cs new file mode 100644 index 0000000..4d8fb08 --- /dev/null +++ b/backend/src/Helpdesk.Api/Controllers/IssuesController.cs @@ -0,0 +1,188 @@ +using System.Globalization; +using System.Text.Json; +using Helpdesk.Api.Infrastructure; +using Helpdesk.Application.Common; +using Helpdesk.Application.Issues; +using Helpdesk.Domain.Issues; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.RateLimiting; + +namespace Helpdesk.Api.Controllers; + +[ApiController] +[Authorize] +[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] +[Route("api/issues")] +[ProducesResponseType(StatusCodes.Status400BadRequest)] +[ProducesResponseType(StatusCodes.Status401Unauthorized)] +[ProducesResponseType(StatusCodes.Status403Forbidden)] +[ProducesResponseType(StatusCodes.Status404NotFound)] +[ProducesResponseType(StatusCodes.Status409Conflict)] +public sealed class IssuesController(IssueService issues) : ControllerBase +{ + // Pro popis o velikosti 65 535 bajtů ponechá prostor i při JSON escapování znaků. + private const int MaxJsonCreateBytes = 1024 * 1024; + + [HttpGet] + public Task> List([FromQuery] IssueQuery query, CancellationToken ct) => + issues.ListAsync(query, ct); + + [HttpGet("{id:int}")] + public Task Get(int id, CancellationToken ct) => issues.GetAsync(id, ct); + + [HttpPost] + [ReadIssueBodyManually] + [EnableRateLimiting(RateLimitPolicies.IssueWrites)] + [Consumes("application/json", "multipart/form-data")] + [RequestSizeLimit(AttachmentLimits.MaxRequestBytes)] + [RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status413PayloadTooLarge)] + [ProducesResponseType(StatusCodes.Status415UnsupportedMediaType)] + [ProducesResponseType(StatusCodes.Status429TooManyRequests)] + public async Task> Create(CancellationToken ct) + { + CreateIssueRequest request; + AttachmentUpload[] uploads = []; + try + { + if (Request.HasFormContentType) + { + var form = await ReadFormAsync(ct); + request = new CreateIssueRequest( + form["title"].ToString(), form["description"].ToString(), + ReadId(form, "categoryId") ?? throw new BadRequestException("Kategorie je povinná."), + ReadId(form, "buildingId"), form["locationDetail"].ToString()); + uploads = ReadUploads(form.Files); + } + else + { + if (Request.ContentType is null && Request.ContentLength is null or 0) + throw new BadRequestException("Vyplňte údaje závady."); + if (!Request.HasJsonContentType()) + return Problem(statusCode: StatusCodes.Status415UnsupportedMediaType); + + var contentType = Request.GetTypedHeaders().ContentType; + if (contentType is { Charset.HasValue: true, Encoding: null }) + return Problem(statusCode: StatusCodes.Status415UnsupportedMediaType); + + if (HttpContext.Features.Get() is { IsReadOnly: false } sizeLimit) + sizeLimit.MaxRequestBodySize = MaxJsonCreateBytes; + + request = await Request.ReadFromJsonAsync(ct) + ?? throw new BadRequestException("Vyplňte údaje závady."); + } + } + catch (JsonException) + { + throw new BadRequestException("Neplatný formát požadavku."); + } + + var result = await issues.CreateAsync(request, uploads, ct); + return CreatedAtAction(nameof(Get), new { id = result.Id }, result); + } + + [HttpPut("{id:int}")] + public Task Edit(int id, EditIssueRequest request, CancellationToken ct) => + issues.EditAsync(id, request, ct); + + [HttpPost("{id:int}/assign")] + public Task Assign(int id, AssignIssueRequest request, CancellationToken ct) => + issues.AssignAsync(id, request, ct); + + [HttpPost("{id:int}/start")] + public Task Start(int id, IssueVersionRequest request, CancellationToken ct) => + issues.TransitionAsync(id, IssueAction.StartWork, request.RowVersion, null, ct); + + [HttpPost("{id:int}/submit-for-verification")] + public Task SubmitForVerification(int id, VerifyIssueRequest request, CancellationToken ct) => + issues.TransitionAsync(id, IssueAction.SubmitForVerification, request.RowVersion, request.Note, ct); + + [HttpPost("{id:int}/confirm")] + public Task Confirm(int id, IssueVersionRequest request, CancellationToken ct) => + issues.TransitionAsync(id, IssueAction.Confirm, request.RowVersion, null, ct); + + [HttpPost("{id:int}/reopen")] + public Task Reopen(int id, IssueReasonRequest request, CancellationToken ct) => + issues.TransitionAsync(id, IssueAction.Reopen, request.RowVersion, request.Reason, ct); + + [HttpPost("{id:int}/reject")] + public Task Reject(int id, IssueReasonRequest request, CancellationToken ct) => + issues.TransitionAsync(id, IssueAction.Reject, request.RowVersion, request.Reason, ct); + + [HttpGet("{id:int}/events")] + public Task> Events(int id, CancellationToken ct) => issues.GetEventsAsync(id, ct); + + [HttpPost("{id:int}/comments")] + [EnableRateLimiting(RateLimitPolicies.IssueWrites)] + [ProducesResponseType(StatusCodes.Status429TooManyRequests)] + public Task Comment(int id, CommentRequest request, CancellationToken ct) => + issues.CommentAsync(id, request, ct); + + [HttpPost("{id:int}/attachments")] + [ReadIssueBodyManually] + [EnableRateLimiting(RateLimitPolicies.IssueWrites)] + [Consumes("multipart/form-data")] + [RequestSizeLimit(AttachmentLimits.MaxRequestBytes)] + [RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)] + [ProducesResponseType(StatusCodes.Status413PayloadTooLarge)] + [ProducesResponseType(StatusCodes.Status415UnsupportedMediaType)] + [ProducesResponseType(StatusCodes.Status429TooManyRequests)] + public async Task>> Upload(int id, CancellationToken ct) + { + if (!Request.HasFormContentType) + return Problem(statusCode: StatusCodes.Status415UnsupportedMediaType); + + var attachments = await issues.AddAttachmentsAsync(id, async token => + ReadUploads((await ReadFormAsync(token)).Files), ct); + return Ok(attachments); + } + + private async Task ReadFormAsync(CancellationToken ct) + { + try + { + return await Request.ReadFormAsync(ct); + } + catch (InvalidDataException) + { + throw new BadRequestException("Neplatný formát požadavku."); + } + } + + private static int? ReadId(IFormCollection form, string key) + { + var value = form[key].ToString(); + if (string.IsNullOrWhiteSpace(value)) + return null; + if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var id)) + throw new BadRequestException($"Neplatná hodnota {key}."); + return id; + } + + private static AttachmentUpload[] ReadUploads(IFormFileCollection files) + { + if (files.Count > AttachmentLimits.MaxFiles) + throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů."); + if (files.Any(file => file.Name != "files")) + throw new BadRequestException("Přílohy patří do pole files."); + + return files.Select(file => new AttachmentUpload(file.FileName, file.Length, file.OpenReadStream)).ToArray(); + } +} + +internal sealed class ReadIssueBodyManuallyAttribute : Attribute, IResourceFilter +{ + public void OnResourceExecuting(ResourceExecutingContext context) + { + context.ValueProviderFactories.RemoveType(); + context.ValueProviderFactories.RemoveType(); + context.ValueProviderFactories.RemoveType(); + } + + public void OnResourceExecuted(ResourceExecutedContext context) { } +} diff --git a/backend/src/Helpdesk.Api/Controllers/UsersController.cs b/backend/src/Helpdesk.Api/Controllers/UsersController.cs index adca8b1..e959462 100644 --- a/backend/src/Helpdesk.Api/Controllers/UsersController.cs +++ b/backend/src/Helpdesk.Api/Controllers/UsersController.cs @@ -1,5 +1,7 @@ using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Issues; using Helpdesk.Application.Users; +using Helpdesk.Api.Infrastructure; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -10,7 +12,7 @@ namespace Helpdesk.Api.Controllers; [Authorize] [Route("api/users")] [Produces("application/json")] -public sealed class UsersController(UserService users, ICurrentUser currentUser) : ControllerBase +public sealed class UsersController(UserService users, ICurrentUser currentUser, IssueService issues) : ControllerBase { /// Můj profil. [HttpGet("me")] @@ -21,4 +23,11 @@ public sealed class UsersController(UserService users, ICurrentUser currentUser) [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public Task UpdateMe(UpdateProfileRequest request, CancellationToken ct) => users.UpdateMeAsync(currentUser, request, ct); + + /// Aktivní řešitelé s počtem otevřených závad. + [HttpGet("assignable")] + [Authorize(Roles = Roles.Management)] + [ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public Task> GetAssignable(CancellationToken ct) => issues.GetAssignableAsync(ct); } diff --git a/backend/src/Helpdesk.Api/Infrastructure/AppExceptionHandler.cs b/backend/src/Helpdesk.Api/Infrastructure/AppExceptionHandler.cs index 9be5aea..bb271d6 100644 --- a/backend/src/Helpdesk.Api/Infrastructure/AppExceptionHandler.cs +++ b/backend/src/Helpdesk.Api/Infrastructure/AppExceptionHandler.cs @@ -21,6 +21,7 @@ internal sealed class AppExceptionHandler(IProblemDetailsService problemDetails) Title = "Neplatná vstupní data.", }, AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message }, + BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode }, _ => null, }; diff --git a/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs b/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs index d185b7d..102af77 100644 --- a/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs +++ b/backend/src/Helpdesk.Api/Infrastructure/AuthenticationSetup.cs @@ -42,4 +42,5 @@ public static class AuthenticationSetup public static class RateLimitPolicies { public const string Auth = "auth"; + public const string IssueWrites = "issue-writes"; } diff --git a/backend/src/Helpdesk.Api/Infrastructure/SwaggerSetup.cs b/backend/src/Helpdesk.Api/Infrastructure/SwaggerSetup.cs index 395bfe5..46b5fc9 100644 --- a/backend/src/Helpdesk.Api/Infrastructure/SwaggerSetup.cs +++ b/backend/src/Helpdesk.Api/Infrastructure/SwaggerSetup.cs @@ -1,4 +1,7 @@ using Microsoft.OpenApi; +using Swashbuckle.AspNetCore.SwaggerGen; +using Helpdesk.Api.Controllers; +using Helpdesk.Application.Issues; namespace Helpdesk.Api.Infrastructure; @@ -30,6 +33,7 @@ public static class SwaggerSetup { [new OpenApiSecuritySchemeReference(SchemeId, document)] = [], }); + options.OperationFilter(); var xml = Path.Combine(AppContext.BaseDirectory, "Helpdesk.Api.xml"); if (File.Exists(xml)) @@ -38,3 +42,63 @@ public static class SwaggerSetup return services; } } + +internal sealed class IssueRequestBody : IOperationFilter +{ + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + if (context.MethodInfo.DeclaringType != typeof(IssuesController)) + return; + + var create = context.MethodInfo.Name == nameof(IssuesController.Create); + if (!create && context.MethodInfo.Name != nameof(IssuesController.Upload)) + return; + + var properties = new Dictionary + { + ["files"] = new OpenApiSchema + { + Type = JsonSchemaType.Array, + MinItems = 1, + MaxItems = AttachmentLimits.MaxFiles, + Items = new OpenApiSchema { Type = JsonSchemaType.String, Format = "binary" }, + }, + }; + var required = new HashSet { "files" }; + if (create) + { + required = ["title", "description", "categoryId"]; + properties["title"] = new OpenApiSchema { Type = JsonSchemaType.String, MaxLength = 200 }; + properties["description"] = new OpenApiSchema { Type = JsonSchemaType.String }; + properties["categoryId"] = new OpenApiSchema { Type = JsonSchemaType.Integer }; + properties["buildingId"] = new OpenApiSchema { Type = JsonSchemaType.Integer }; + properties["locationDetail"] = new OpenApiSchema { Type = JsonSchemaType.String, MaxLength = 255 }; + } + + var content = new Dictionary + { + ["multipart/form-data"] = new() + { + Schema = new OpenApiSchema + { + Type = JsonSchemaType.Object, + Required = required, + Properties = properties, + }, + }, + }; + if (create) + { + content["application/json"] = new OpenApiMediaType + { + Schema = context.SchemaGenerator.GenerateSchema(typeof(CreateIssueRequest), context.SchemaRepository), + }; + } + + operation.RequestBody = new OpenApiRequestBody + { + Required = true, + Content = content, + }; + } +} diff --git a/backend/src/Helpdesk.Api/Program.cs b/backend/src/Helpdesk.Api/Program.cs index 3d32a0e..c6f7309 100644 --- a/backend/src/Helpdesk.Api/Program.cs +++ b/backend/src/Helpdesk.Api/Program.cs @@ -3,6 +3,7 @@ using Helpdesk.Api.Infrastructure; using Helpdesk.Application; using Helpdesk.Application.Abstractions; using Helpdesk.Infrastructure; +using Microsoft.IdentityModel.JsonWebTokens; var builder = WebApplication.CreateBuilder(args); @@ -20,13 +21,21 @@ builder.Services.AddProblemDetails(); builder.Services.AddExceptionHandler(); builder.Services.AddHelpdeskSwagger(); -// Ochrana /api/auth/* proti hádání hesel a zahlcení (kap. 10). +// Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10). builder.Services.AddRateLimiter(options => { options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter( http.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) })); + options.AddPolicy(RateLimitPolicies.IssueWrites, http => RateLimitPartition.GetSlidingWindowLimiter( + http.User.FindFirst(JwtRegisteredClaimNames.Sub)?.Value ?? "unknown", + _ => new SlidingWindowRateLimiterOptions + { + PermitLimit = 10, + Window = TimeSpan.FromMinutes(1), + SegmentsPerWindow = 6, + })); }); var app = builder.Build(); @@ -41,9 +50,9 @@ app.UseSwaggerUI(options => options.DocumentTitle = "Helpdesk API"; }); -app.UseRateLimiter(); app.UseAuthentication(); app.UseAuthorization(); +app.UseRateLimiter(); app.MapControllers(); diff --git a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs index aefcdc0..9da6dcb 100644 --- a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs +++ b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs @@ -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 Buildings { get; } DbSet IssueCategories { get; } DbSet ProposalCategories { get; } + DbSet Issues { get; } + DbSet IssueEvents { get; } + DbSet Attachments { get; } + DbSet IssueNotifications { get; } + DbSet NotificationDeliveries { get; } + DbSet PushDevices { get; } Task SaveChangesAsync(CancellationToken cancellationToken = default); } diff --git a/backend/src/Helpdesk.Application/DependencyInjection.cs b/backend/src/Helpdesk.Application/DependencyInjection.cs index 2cc9f21..d231b6b 100644 --- a/backend/src/Helpdesk.Application/DependencyInjection.cs +++ b/backend/src/Helpdesk.Application/DependencyInjection.cs @@ -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(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); return services; } } diff --git a/backend/src/Helpdesk.Application/Issues/IssueDtos.cs b/backend/src/Helpdesk.Application/Issues/IssueDtos.cs new file mode 100644 index 0000000..6258bcd --- /dev/null +++ b/backend/src/Helpdesk.Application/Issues/IssueDtos.cs @@ -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 AllowedActions, IReadOnlyList 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 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 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; +} diff --git a/backend/src/Helpdesk.Application/Issues/IssueService.Reads.cs b/backend/src/Helpdesk.Application/Issues/IssueService.Reads.cs new file mode 100644 index 0000000..45b07ce --- /dev/null +++ b/backend/src/Helpdesk.Application/Issues/IssueService.Reads.cs @@ -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> 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(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([], total, page, pageSize); + + var pageItems = await ordered.Skip((int)offset).Take(pageSize).ToListAsync(ct); + return new PagedResult(pageItems.Select(IssueSummary.From).ToArray(), total, page, pageSize); + } + + public async Task 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> 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> 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 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 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 attachments) + { + var actions = Enum.GetValues() + .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); +} diff --git a/backend/src/Helpdesk.Application/Issues/IssueService.cs b/backend/src/Helpdesk.Application/Issues/IssueService.cs new file mode 100644 index 0000000..2983c19 --- /dev/null +++ b/backend/src/Helpdesk.Application/Issues/IssueService.cs @@ -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 CreateAsync(CreateIssueRequest request, IReadOnlyList 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 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 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(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 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 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> AddAttachmentsAsync( + int id, Func> 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> SaveWithAttachmentsAsync( + Issue issue, IReadOnlyList 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(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 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 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(string code) where T : struct, Enum => + EnumCode.TryParse(code, out var result) + ? result + : throw new BadRequestException($"Neplatný kód '{code}'."); +} diff --git a/backend/src/Helpdesk.Domain/Issues/Issue.cs b/backend/src/Helpdesk.Domain/Issues/Issue.cs new file mode 100644 index 0000000..a201330 --- /dev/null +++ b/backend/src/Helpdesk.Domain/Issues/Issue.cs @@ -0,0 +1,137 @@ +using Helpdesk.Domain.Users; + +namespace Helpdesk.Domain.Issues; + +public enum IssueStatus { Received, Assigned, InProgress, PendingVerification, Resolved, Rejected } +public enum IssuePriority { Low, Normal, High } +public enum IssueEventType { Created, Updated, Assigned, StatusChanged, Commented } +public enum IssueAction { Edit, Assign, StartWork, SubmitForVerification, Confirm, Reopen, Reject, Comment, AddAttachments } +public enum IssueActionAvailability { Allowed, Forbidden, InvalidState } + +public sealed class Issue : IHasCreatedAt +{ + private Issue() { } + + public Issue(int reporterId, string title, string description, int categoryId, int? buildingId, string? locationDetail) + { + ReporterId = reporterId; + SetDetails(title, description, categoryId, buildingId, locationDetail); + } + + public int Id { get; private set; } + public string Title { get; private set; } = null!; + public string Description { get; private set; } = null!; + public int CategoryId { get; private set; } + public int? BuildingId { get; private set; } + public string? LocationDetail { get; private set; } + public IssueStatus Status { get; private set; } = IssueStatus.Received; + public IssuePriority Priority { get; private set; } = IssuePriority.Normal; + public int ReporterId { get; private set; } + public int? AssigneeId { get; private set; } + public int RowVersion { get; private set; } + public DateTime CreatedAt { get; set; } + + public static bool CanReadAll(UserRole role) => role is UserRole.FacilityManager or UserRole.Management; + + public static bool CanBeAssigned(UserRole role) => role is UserRole.FacilityManager or UserRole.Management; + + public bool CanRead(int userId, UserRole role) => CanReadAll(role) || ReporterId == userId; + + public IssueActionAvailability Availability(IssueAction action, int actorId, UserRole role) + { + var reporter = ReporterId == actorId; + var assignee = AssigneeId == actorId && CanBeAssigned(role); + var management = role == UserRole.Management; + + var authorized = action switch + { + IssueAction.Edit or IssueAction.Confirm or IssueAction.Reopen => reporter, + IssueAction.Assign => management, + IssueAction.StartWork or IssueAction.SubmitForVerification => assignee, + IssueAction.Reject => assignee || (management && AssigneeId is null), + IssueAction.Comment or IssueAction.AddAttachments => reporter || assignee, + _ => false, + }; + + if (!authorized) + return IssueActionAvailability.Forbidden; + + var permittedState = action switch + { + IssueAction.Edit => Status == IssueStatus.Received, + IssueAction.Assign => Status is IssueStatus.Received or IssueStatus.Assigned or IssueStatus.InProgress, + IssueAction.StartWork => Status == IssueStatus.Assigned, + IssueAction.SubmitForVerification => Status == IssueStatus.InProgress, + IssueAction.Confirm or IssueAction.Reopen => Status == IssueStatus.PendingVerification, + IssueAction.Reject => Status == IssueStatus.Received + ? management + : assignee && Status is (IssueStatus.Assigned or IssueStatus.InProgress), + IssueAction.Comment or IssueAction.AddAttachments => Status is not (IssueStatus.Resolved or IssueStatus.Rejected), + _ => false, + }; + return permittedState ? IssueActionAvailability.Allowed : IssueActionAvailability.InvalidState; + } + + public void Edit(int actorId, UserRole role, string title, string description, int categoryId, + int? buildingId, string? locationDetail) + { + Require(IssueAction.Edit, actorId, role); + SetDetails(title, description, categoryId, buildingId, locationDetail); + RowVersion++; + } + + public void Assign(int actorId, UserRole role, int assigneeId, UserRole assigneeRole, IssuePriority? priority) + { + Require(IssueAction.Assign, actorId, role); + if (!CanBeAssigned(assigneeRole)) + throw new ArgumentException("Neplatná role řešitele.", nameof(assigneeRole)); + if (AssigneeId == assigneeId) + throw new ArgumentException("Nový řešitel musí být jiný než stávající.", nameof(assigneeId)); + + AssigneeId = assigneeId; + Priority = priority ?? Priority; + Status = IssueStatus.Assigned; + RowVersion++; + } + + public void Transition(IssueAction action, int actorId, UserRole role, string? reason) + { + Require(action, actorId, role); + if (action is (IssueAction.Reject or IssueAction.Reopen) && string.IsNullOrWhiteSpace(reason)) + throw new ArgumentException("Důvod je povinný.", nameof(reason)); + + Status = action switch + { + IssueAction.StartWork or IssueAction.Reopen => IssueStatus.InProgress, + IssueAction.SubmitForVerification => IssueStatus.PendingVerification, + IssueAction.Confirm => IssueStatus.Resolved, + IssueAction.Reject => IssueStatus.Rejected, + _ => throw new ArgumentOutOfRangeException(nameof(action)), + }; + RowVersion++; + } + + public void RecordParticipation(IssueAction action, int actorId, UserRole role) + { + if (action is not (IssueAction.Comment or IssueAction.AddAttachments)) + throw new ArgumentOutOfRangeException(nameof(action)); + + Require(action, actorId, role); + RowVersion++; + } + + private void Require(IssueAction action, int actorId, UserRole role) + { + if (Availability(action, actorId, role) != IssueActionAvailability.Allowed) + throw new InvalidOperationException("Akce není pro tuto závadu povolena."); + } + + private void SetDetails(string title, string description, int categoryId, int? buildingId, string? locationDetail) + { + Title = title.Trim(); + Description = description.Trim(); + CategoryId = categoryId; + BuildingId = buildingId; + LocationDetail = string.IsNullOrWhiteSpace(locationDetail) ? null : locationDetail.Trim(); + } +} diff --git a/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs b/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs new file mode 100644 index 0000000..84f9aba --- /dev/null +++ b/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs @@ -0,0 +1,39 @@ +namespace Helpdesk.Domain.Issues; + +public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened } +public enum DeliveryChannel { Email, Push } +public enum DeliveryStatus { Pending, Skipped } + +public sealed class IssueNotification( + Issue issue, int userId, NotificationType type, string title, string message) : IHasCreatedAt +{ + private IssueNotification() : this(null!, 0, default, null!, null!) { } + + public int Id { get; private set; } + public int? IssueId { get; private set; } + public Issue Issue { get; private set; } = issue; + public int UserId { get; private set; } = userId; + public NotificationType Type { get; private set; } = type; + public string Title { get; private set; } = title; + public string Message { get; private set; } = message; + public DateTime CreatedAt { get; set; } +} + +public sealed class NotificationDelivery( + IssueNotification notification, DeliveryChannel channel, bool enabled, DateTime now) +{ + private NotificationDelivery() : this(null!, default, false, default) { } + + public int Id { get; private set; } + public int NotificationId { get; private set; } + public IssueNotification Notification { get; private set; } = notification; + public DeliveryChannel Channel { get; private set; } = channel; + public DeliveryStatus Status { get; private set; } = enabled ? DeliveryStatus.Pending : DeliveryStatus.Skipped; + public DateTime? NextAttemptAt { get; private set; } = enabled ? now : null; +} + +public sealed class PushDevice +{ + public int Id { get; private set; } + public int UserId { get; private set; } +} diff --git a/backend/src/Helpdesk.Domain/Issues/IssueRecords.cs b/backend/src/Helpdesk.Domain/Issues/IssueRecords.cs new file mode 100644 index 0000000..606e966 --- /dev/null +++ b/backend/src/Helpdesk.Domain/Issues/IssueRecords.cs @@ -0,0 +1,43 @@ +namespace Helpdesk.Domain.Issues; + +public sealed class IssueEvent +{ + private IssueEvent() { } + + public IssueEvent(Issue issue, IssueEventType eventType, IssueStatus? fromStatus, int actorId, string? note, + DateTime occurredAt) + { + Issue = issue; + EventType = eventType; + FromStatus = fromStatus; + ToStatus = issue.Status; + ActorId = actorId; + Note = note; + OccurredAt = occurredAt; + } + + public int Id { get; private set; } + public int IssueId { get; private set; } + public Issue Issue { get; private set; } = null!; + public IssueEventType EventType { get; private set; } + public IssueStatus? FromStatus { get; private set; } + public IssueStatus ToStatus { get; private set; } + public int ActorId { get; private set; } + public string? Note { get; private set; } + public DateTime OccurredAt { get; private set; } +} + +public sealed class Attachment( + Issue issue, string originalFileName, string storedFileName, string contentType, long sizeBytes) : IHasCreatedAt +{ + private Attachment() : this(null!, null!, null!, null!, 0) { } + + public int Id { get; private set; } + public int IssueId { get; private set; } + public Issue Issue { get; private set; } = issue; + public string OriginalFileName { get; private set; } = originalFileName; + public string StoredFileName { get; private set; } = storedFileName; + public string ContentType { get; private set; } = contentType; + public long SizeBytes { get; private set; } = sizeBytes; + public DateTime CreatedAt { get; set; } +} diff --git a/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs b/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs index 4c853e1..40b6693 100644 --- a/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs +++ b/backend/src/Helpdesk.Infrastructure/DependencyInjection.cs @@ -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(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddHostedService(); services.AddHostedService(); diff --git a/backend/src/Helpdesk.Infrastructure/Files/FileAttachmentStore.cs b/backend/src/Helpdesk.Infrastructure/Files/FileAttachmentStore.cs new file mode 100644 index 0000000..eca2958 --- /dev/null +++ b/backend/src/Helpdesk.Infrastructure/Files/FileAttachmentStore.cs @@ -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 logger) : IAttachmentStore +{ + private readonly string directory = Path.Combine(AppContext.BaseDirectory, "uploads"); + + public async Task 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 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 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 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; + } + } +} diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs index ac0826b..d964065 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs @@ -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 option public DbSet Buildings => Set(); public DbSet IssueCategories => Set(); public DbSet ProposalCategories => Set(); + public DbSet Issues => Set(); + public DbSet IssueEvents => Set(); + public DbSet Attachments => Set(); + public DbSet IssueNotifications => Set(); + public DbSet NotificationDeliveries => Set(); + public DbSet PushDevices => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -28,6 +35,12 @@ public sealed class HelpdeskDbContext(DbContextOptions 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().ToTable("push_device"); } protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs b/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs new file mode 100644 index 0000000..6394776 --- /dev/null +++ b/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs @@ -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 +{ + public void Configure(EntityTypeBuilder 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>().HasMaxLength(30); + b.Property(x => x.Priority).HasConversion>().HasMaxLength(10); + b.Property(x => x.RowVersion).IsConcurrencyToken(); + b.HasOne().WithMany().HasForeignKey(x => x.CategoryId); + b.HasOne().WithMany().HasForeignKey(x => x.BuildingId); + b.HasOne().WithMany().HasForeignKey(x => x.ReporterId); + b.HasOne().WithMany().HasForeignKey(x => x.AssigneeId); + } +} + +internal sealed class IssueEventConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("issue_event"); + b.Property(x => x.EventType).HasConversion>().HasMaxLength(20); + b.Property(x => x.FromStatus).HasConversion>().HasMaxLength(30); + b.Property(x => x.ToStatus).HasConversion>().HasMaxLength(30); + b.Property(x => x.Note).HasColumnType("text"); + b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId); + b.HasOne().WithMany().HasForeignKey(x => x.ActorId); + } +} + +internal sealed class AttachmentConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder 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 +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("notification"); + b.Property(x => x.Type).HasConversion>().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().WithMany().HasForeignKey(x => x.UserId); + } +} + +internal sealed class NotificationDeliveryConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("notification_delivery"); + b.Property(x => x.Channel).HasConversion>().HasMaxLength(10); + b.Property(x => x.Status).HasConversion>().HasMaxLength(10); + b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId); + } +} diff --git a/backend/tests/Helpdesk.UnitTests/IssueTests.cs b/backend/tests/Helpdesk.UnitTests/IssueTests.cs new file mode 100644 index 0000000..d77c36a --- /dev/null +++ b/backend/tests/Helpdesk.UnitTests/IssueTests.cs @@ -0,0 +1,136 @@ +using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Users; + +namespace Helpdesk.UnitTests; + +public sealed class IssueTests +{ + private const int Reporter = 1; + private const int Manager = 2; + private const int Assignee = 3; + private const int Replacement = 4; + + [Fact] + public void NewIssueStartsReceivedWithNormalPriority() + { + var issue = At(IssueStatus.Received); + Assert.Equal(IssueStatus.Received, issue.Status); + Assert.Equal(IssuePriority.Normal, issue.Priority); + Assert.Equal(0, issue.RowVersion); + Assert.Null(issue.AssigneeId); + } + + [Theory] + [InlineData(IssueStatus.Received)] + [InlineData(IssueStatus.Assigned)] + [InlineData(IssueStatus.InProgress)] + public void ManagementCanAssignOrReassign(IssueStatus from) + { + var issue = At(from); + var version = issue.RowVersion; + Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Assign, Manager, UserRole.Management)); + issue.Assign(Manager, UserRole.Management, Replacement, UserRole.Management, IssuePriority.High); + Assert.Equal(IssueStatus.Assigned, issue.Status); + Assert.Equal(Replacement, issue.AssigneeId); + Assert.Equal(IssuePriority.High, issue.Priority); + Assert.Equal(version + 1, issue.RowVersion); + } + + [Theory] + [InlineData(IssueStatus.Assigned, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueStatus.InProgress)] + [InlineData(IssueStatus.InProgress, IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, IssueStatus.PendingVerification)] + [InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Reporter, UserRole.Admin, IssueStatus.Resolved)] + [InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Reporter, UserRole.Admin, IssueStatus.InProgress)] + [InlineData(IssueStatus.Assigned, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)] + [InlineData(IssueStatus.InProgress, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueStatus.Rejected)] + [InlineData(IssueStatus.Received, IssueAction.Reject, Manager, UserRole.Management, IssueStatus.Rejected)] + public void AllowedTransitionsIncrementVersion( + IssueStatus from, IssueAction action, int actorId, UserRole role, IssueStatus target) + { + var issue = At(from); + var version = issue.RowVersion; + Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(action, actorId, role)); + issue.Transition(action, actorId, role, "Důvod"); + Assert.Equal(target, issue.Status); + Assert.Equal(version + 1, issue.RowVersion); + } + + [Theory] + [InlineData(IssueStatus.Assigned, IssueAction.StartWork, Replacement, UserRole.FacilityManager, IssueActionAvailability.Forbidden)] + [InlineData(IssueStatus.Assigned, IssueAction.StartWork, Assignee, UserRole.Student, IssueActionAvailability.Forbidden)] + [InlineData(IssueStatus.Assigned, IssueAction.Reject, Manager, UserRole.Management, IssueActionAvailability.Forbidden)] + [InlineData(IssueStatus.Assigned, IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)] + [InlineData(IssueStatus.InProgress, IssueAction.StartWork, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)] + [InlineData(IssueStatus.PendingVerification, IssueAction.Confirm, Assignee, UserRole.FacilityManager, IssueActionAvailability.Forbidden)] + [InlineData(IssueStatus.PendingVerification, IssueAction.Reject, Assignee, UserRole.FacilityManager, IssueActionAvailability.InvalidState)] + [InlineData(IssueStatus.Resolved, IssueAction.Reopen, Reporter, UserRole.Admin, IssueActionAvailability.InvalidState)] + [InlineData(IssueStatus.Rejected, IssueAction.Reject, Manager, UserRole.Management, IssueActionAvailability.InvalidState)] + public void DisallowedTransitionsMatchAvailability( + IssueStatus from, IssueAction action, int actorId, UserRole role, IssueActionAvailability expected) + { + var issue = At(from); + var version = issue.RowVersion; + Assert.Equal(expected, issue.Availability(action, actorId, role)); + Assert.Throws(() => issue.Transition(action, actorId, role, "Důvod")); + Assert.Equal(from, issue.Status); + Assert.Equal(version, issue.RowVersion); + } + + [Theory] + [InlineData(IssueStatus.PendingVerification, IssueAction.Reopen, Reporter, UserRole.Admin)] + [InlineData(IssueStatus.Received, IssueAction.Reject, Manager, UserRole.Management)] + public void ReasonsAreRequired(IssueStatus from, IssueAction action, int actorId, UserRole role) + { + var issue = At(from); + Assert.Throws(() => issue.Transition(action, actorId, role, " ")); + Assert.Equal(from, issue.Status); + } + + [Fact] + public void ReassigningToSameUserKeepsWorkInProgress() + { + var issue = At(IssueStatus.InProgress); + var version = issue.RowVersion; + Assert.Throws(() => + issue.Assign(Manager, UserRole.Management, Assignee, UserRole.FacilityManager, IssuePriority.High)); + Assert.Equal(IssueStatus.InProgress, issue.Status); + Assert.Equal(version, issue.RowVersion); + } + + [Fact] + public void ParticipationFollowsOwnershipAndClosesWithIssue() + { + var issue = At(IssueStatus.Assigned); + Assert.True(issue.CanRead(Reporter, UserRole.Admin)); + Assert.False(issue.CanRead(Replacement, UserRole.Admin)); + Assert.True(issue.CanRead(Replacement, UserRole.FacilityManager)); + Assert.Equal(IssueActionAvailability.Forbidden, issue.Availability(IssueAction.Comment, Manager, UserRole.Management)); + Assert.Equal(IssueActionAvailability.Allowed, issue.Availability(IssueAction.Comment, Reporter, UserRole.Admin)); + issue.RecordParticipation(IssueAction.Comment, Reporter, UserRole.Admin); + issue.Transition(IssueAction.Reject, Assignee, UserRole.FacilityManager, "Důvod"); + Assert.Equal(IssueActionAvailability.InvalidState, issue.Availability(IssueAction.AddAttachments, Reporter, UserRole.Admin)); + } + + private static Issue At(IssueStatus result) + { + var issue = new Issue(Reporter, "Projektor", "Nefunguje", 1, null, null); + if (result == IssueStatus.Received) + return issue; + if (result == IssueStatus.Rejected) + { + issue.Transition(IssueAction.Reject, Manager, UserRole.Management, "Důvod"); + return issue; + } + + issue.Assign(Manager, UserRole.Management, Assignee, UserRole.FacilityManager, null); + if (result == IssueStatus.Assigned) + return issue; + issue.Transition(IssueAction.StartWork, Assignee, UserRole.FacilityManager, null); + if (result == IssueStatus.InProgress) + return issue; + issue.Transition(IssueAction.SubmitForVerification, Assignee, UserRole.FacilityManager, null); + if (result == IssueStatus.Resolved) + issue.Transition(IssueAction.Confirm, Reporter, UserRole.Admin, null); + return issue; + } +} diff --git a/docs/navrh-aplikace.md b/docs/navrh-aplikace.md index 833bda8..addc044 100644 --- a/docs/navrh-aplikace.md +++ b/docs/navrh-aplikace.md @@ -90,9 +90,9 @@ Legenda: ✅ povoleno, 🔸 povoleno s podmínkou, — nepovoleno | Centrální přehled všech závad (filtry) | — | ✅ (jen čtení) | ✅ | — | | Přiřadit / přeřadit závadu řešiteli, nastavit prioritu | — | — | ✅ | — | | Zahájit řešení, předat k ověření | — | 🔸 jen přiřazené jemu | 🔸 jen přiřazené jemu | — | -| Zamítnout závadu (s důvodem) | — | 🔸 jen přiřazené jemu | 🔸 přiřazené jemu + ve stavu *Přijata* | — | -| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | — | -| Komentovat závadu | 🔸 hlásič | 🔸 hlásič nebo řešitel | 🔸 hlásič nebo řešitel; ostatní jen čtení | — | +| Zamítnout závadu (s důvodem) | — | 🔸 jen přiřazené jemu | 🔸 přiřazené jemu nebo nepřiřazené ve stavu *Přijata* | — | +| Potvrdit vyřešení / znovu otevřít | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | 🔸 jen hlásič | +| Komentovat závadu | 🔸 hlásič | 🔸 hlásič nebo řešitel | 🔸 hlásič nebo řešitel; ostatní jen čtení | 🔸 hlásič | | Podat návrh na zlepšení | ✅ | ✅ | ✅ | ✅ | | Zobrazit všechny návrhy | ✅ | ✅ | ✅ | ✅ | | Hlasovat pro návrh | 🔸 ne pro vlastní | 🔸 | 🔸 | 🔸 | @@ -512,6 +512,7 @@ Větvení: `main` (stabilní), `develop`, feature větve `feature/`, merg | Tokeny | Všechny tokeny jsou podepsané JWT podle RFC 7519 s unikátním `jti` a typem v hlavičce. V databázi není žádný token ani jeho hash (kap. 10.1). | | Šifrování citlivých údajů | Telefonní číslo uživatele šifrováno AES-256-GCM (EF Core value converter), klíč mimo DB – v proměnné prostředí / Docker secret. Přenos výhradně HTTPS (TLS 1.2+), HSTS. | | Přílohy | Kontrola typu (přípona + signatura souboru) a velikosti, ukládání pod náhodným GUID mimo webový kořen, stahování jen přes API s kontrolou oprávnění k závadě. | +| Zápisy závad | Vytvoření závady, přidání komentáře a nahrání příloh mají společný limit 10 požadavků za minutu na účet a instanci API. Překročení vrací 429. | | Vstupy | Validace DTO (FluentValidation), parametrizované dotazy (EF Core), HTML výstup kódován Razorem (XSS), anti-forgery tokeny ve webových formulářích (CSRF). | | Tajemství | JWT klíč, DB heslo, šifrovací klíč, SMTP a Firebase přístupy pouze v proměnných prostředí / `.env` mimo Git. | @@ -660,23 +661,24 @@ Všechny endpointy mají prefix `/api`, formát JSON, chyby ve formátu **Proble ### Hlášení závad | Metoda | Endpoint | Role | Popis | |---|---|---|---| -| GET | `/issues` | přihlášený | Seznam; filtry `status`, `categoryId`, `buildingId`, `assigneeId`, `reporterId`, `from`, `to`, `q`, `mine`; řazení `sort`. Student/vyučující dostane jen vlastní. | -| POST | `/issues` | přihlášený | Vytvoření hlášení (T1) | +| GET | `/issues` | přihlášený | Seznam; filtry `status`, `categoryId`, `buildingId`, `assigneeId`, `reporterId`, `from`, `to`, `q`, `mine`; řazení `sort=newest\|oldest`. Student, vyučující a administrátor vidí jen vlastní. | +| POST | `/issues` | přihlášený | Vytvoření hlášení (T1), JSON do 1 MiB nebo multipart s poli hlášení a soubory v poli `files` | | GET | `/issues/{id}` | účastník / správce / vedení | Detail vč. `allowedActions` a `rowVersion` | -| PUT | `/issues/{id}` | hlásič | Úprava ve stavu Přijata | +| PUT | `/issues/{id}` | hlásič | Úprava ve stavu Přijata s `rowVersion` | | POST | `/issues/{id}/assign` | vedení | `{ assigneeId, priority?, rowVersion }` (T2, T3) | -| POST | `/issues/{id}/start` | řešitel | T4 | -| POST | `/issues/{id}/submit-for-verification` | řešitel | `{ note? }` (T5) | -| POST | `/issues/{id}/confirm` | hlásič | T6 | -| POST | `/issues/{id}/reopen` | hlásič | `{ reason }` (T7) | -| POST | `/issues/{id}/reject` | řešitel / vedení | `{ reason }` (T8, T9) | +| POST | `/issues/{id}/start` | řešitel | `{ rowVersion }` (T4) | +| POST | `/issues/{id}/submit-for-verification` | řešitel | `{ rowVersion, note? }` (T5) | +| POST | `/issues/{id}/confirm` | hlásič | `{ rowVersion }` (T6) | +| POST | `/issues/{id}/reopen` | hlásič | `{ rowVersion, reason }` (T7) | +| POST | `/issues/{id}/reject` | řešitel / vedení | `{ rowVersion, reason }` (T8, T9) | | GET | `/issues/{id}/events` | jako detail | Časová osa – všechny události včetně komentářů (`issue_event`) | | POST | `/issues/{id}/comments` | hlásič, řešitel | `{ text }` – zapíše událost `COMMENTED` | -| POST | `/issues/{id}/attachments` | hlásič, řešitel | `multipart/form-data` | +| POST | `/issues/{id}/attachments` | hlásič, řešitel | `multipart/form-data`, 1–5 souborů v poli `files` | | GET | `/attachments/{id}` | jako detail závady | Stažení souboru | | GET | `/users/assignable` | vedení | Možní řešitelé s počtem otevřených závad | Přechody stavů jsou záměrně **samostatné akční endpointy** místo obecného `PATCH status` – každý má vlastní vstupní data, oprávnění a je jednoznačně zdokumentovaný ve Swaggeru. +Po přidání komentáře nebo příloh klient znovu načte detail, aby získal aktuální `rowVersion`. ### Návrhy na zlepšení | Metoda | Endpoint | Role | Popis | @@ -1164,7 +1166,7 @@ flowchart LR | Služba | Image | Sítě | Porty | Úložiště | Poznámka | |---|---|---|---|---|---| -| `proxy` | `nginx` | frontend | **80, 443 publikované** | certifikáty | TLS (vývoj: `mkcert`, produkce: Let's Encrypt), HSTS, limit velikosti požadavku 50 MB (5 příloh × 10 MB) | +| `proxy` | `nginx` | frontend | **80, 443 publikované** | certifikáty | TLS (vývoj: `mkcert`, produkce: Let's Encrypt), HSTS, limit velikosti požadavku 51 MiB (5 příloh × 10 MiB a režie multipart) | | `web` | vlastní (`dotnet/aspnet`) | frontend | interně 8080 | `web-keys` | klíče ASP.NET Core Data Protection pro šifrované cookie (bez persistence by restart odhlásil všechny uživatele) | | `api` | vlastní (`dotnet/aspnet`) | frontend, backend | interně 8080 | `uploads` | Swagger na `/swagger`, `GET /health`, vytvoření admin účtu z env | | `migrator` | vlastní (`dotnet/runtime`) | backend | — | — | aplikuje nové migrace z `db/migrations` a skončí | -- 2.54.1