From b80ec5758908bdd6c97ffb7fd2ea820ddd230012 Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Wed, 18 Nov 2026 18:32:59 +0100 Subject: [PATCH 1/3] 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čí | From 9ca23a2c155ee891aad8e4446c8117c1451f3335 Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Wed, 18 Nov 2026 18:40:53 +0100 Subject: [PATCH 2/3] Add notification inbox and restrict email logging --- .../Controllers/NotificationsController.cs | 39 ++++++++++++ .../DependencyInjection.cs | 2 + .../Notifications/NotificationService.cs | 61 +++++++++++++++++++ .../Issues/IssueNotification.cs | 4 +- .../Email/LoggingEmailSender.cs | 11 +++- 5 files changed, 114 insertions(+), 3 deletions(-) create mode 100644 backend/src/Helpdesk.Api/Controllers/NotificationsController.cs create mode 100644 backend/src/Helpdesk.Application/Notifications/NotificationService.cs diff --git a/backend/src/Helpdesk.Api/Controllers/NotificationsController.cs b/backend/src/Helpdesk.Api/Controllers/NotificationsController.cs new file mode 100644 index 0000000..5ed84af --- /dev/null +++ b/backend/src/Helpdesk.Api/Controllers/NotificationsController.cs @@ -0,0 +1,39 @@ +using Helpdesk.Application.Common; +using Helpdesk.Application.Notifications; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Helpdesk.Api.Controllers; + +[ApiController] +[Authorize] +[Route("api/notifications")] +[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] +[ProducesResponseType(StatusCodes.Status401Unauthorized)] +public sealed class NotificationsController(NotificationService notifications) : ControllerBase +{ + [HttpGet] + public Task> List( + [FromQuery] bool unreadOnly = false, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, + CancellationToken ct = default) => notifications.ListAsync(unreadOnly, page, pageSize, ct); + + [HttpGet("unread-count")] + public Task CountUnread(CancellationToken ct) => notifications.CountUnreadAsync(ct); + + [HttpPost("{id:int}/read")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task MarkRead(int id, CancellationToken ct) + { + await notifications.MarkReadAsync(id, ct); + return NoContent(); + } + + [HttpPost("read-all")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task MarkAllRead(CancellationToken ct) + { + await notifications.MarkAllReadAsync(ct); + return NoContent(); + } +} diff --git a/backend/src/Helpdesk.Application/DependencyInjection.cs b/backend/src/Helpdesk.Application/DependencyInjection.cs index d231b6b..e16c834 100644 --- a/backend/src/Helpdesk.Application/DependencyInjection.cs +++ b/backend/src/Helpdesk.Application/DependencyInjection.cs @@ -2,6 +2,7 @@ using FluentValidation; using Helpdesk.Application.Auth; using Helpdesk.Application.Catalogs; using Helpdesk.Application.Issues; +using Helpdesk.Application.Notifications; using Helpdesk.Application.Users; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -20,6 +21,7 @@ public static class DependencyInjection services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); return services; } } diff --git a/backend/src/Helpdesk.Application/Notifications/NotificationService.cs b/backend/src/Helpdesk.Application/Notifications/NotificationService.cs new file mode 100644 index 0000000..50ac01f --- /dev/null +++ b/backend/src/Helpdesk.Application/Notifications/NotificationService.cs @@ -0,0 +1,61 @@ +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; +using Helpdesk.Domain; +using Helpdesk.Domain.Issues; +using Microsoft.EntityFrameworkCore; + +namespace Helpdesk.Application.Notifications; + +public sealed record NotificationDto( + int Id, string Type, string Title, string Message, int? IssueId, int? ProposalId, DateTime CreatedAt, DateTime? ReadAt); + +public sealed record UnreadCountDto(int Count); + +public sealed class NotificationService(IAppDbContext db, ICurrentUser currentUser, TimeProvider clock) +{ + public async Task> ListAsync(bool unreadOnly, int page, int pageSize, CancellationToken ct) + { + page = Math.Max(1, page); + pageSize = Math.Clamp(pageSize, 1, 100); + + var query = Inbox().AsNoTracking(); + if (unreadOnly) + query = query.Where(n => n.ReadAt == null); + + var total = await query.CountAsync(ct); + var offset = (long)(page - 1) * pageSize; + if (offset >= total) + return new PagedResult([], total, page, pageSize); + + var rows = await query.OrderByDescending(n => n.CreatedAt).ThenByDescending(n => n.Id) + .Skip((int)offset).Take(pageSize).ToListAsync(ct); + var items = rows.Select(n => new NotificationDto( + n.Id, n.Type.ToCode(), n.Title, n.Message, n.IssueId, n.ProposalId, n.CreatedAt, n.ReadAt)).ToArray(); + return new PagedResult(items, total, page, pageSize); + } + + public async Task CountUnreadAsync(CancellationToken ct) => + new(await Inbox().CountAsync(n => n.ReadAt == null, ct)); + + public async Task MarkReadAsync(int id, CancellationToken ct) + { + var match = Inbox().Where(n => n.Id == id); + if (await MarkUnreadRowsAsync(match, ct) == 0 && !await match.AnyAsync(ct)) + throw new NotFoundException("Notifikace neexistuje."); + } + + public async Task MarkAllReadAsync(CancellationToken ct) => await MarkUnreadRowsAsync(Inbox(), ct); + + private IQueryable Inbox() + { + var userId = currentUser.Id; + return db.IssueNotifications.Where(n => n.UserId == userId); + } + + private Task MarkUnreadRowsAsync(IQueryable query, CancellationToken ct) + { + var now = clock.GetUtcNow().UtcDateTime; + return query.Where(n => n.ReadAt == null) + .ExecuteUpdateAsync(update => update.SetProperty(n => n.ReadAt, now), ct); + } +} diff --git a/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs b/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs index 84f9aba..144c935 100644 --- a/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs +++ b/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs @@ -1,6 +1,6 @@ namespace Helpdesk.Domain.Issues; -public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened } +public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged } public enum DeliveryChannel { Email, Push } public enum DeliveryStatus { Pending, Skipped } @@ -11,12 +11,14 @@ public sealed class IssueNotification( public int Id { get; private set; } public int? IssueId { get; private set; } + public int? ProposalId { 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 DateTime? ReadAt { get; private set; } } public sealed class NotificationDelivery( diff --git a/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs b/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs index 4fe3109..6b269b5 100644 --- a/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs +++ b/backend/src/Helpdesk.Infrastructure/Email/LoggingEmailSender.cs @@ -1,4 +1,5 @@ using Helpdesk.Application.Abstractions; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Helpdesk.Infrastructure.Email; @@ -7,14 +8,20 @@ namespace Helpdesk.Infrastructure.Email; /// Vývojová náhrada odesílání e-mailů – obsah zapíše do logu (odkaz pro ověření e-mailu je tak vidět /// v docker compose logs api). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi. /// -internal sealed partial class LoggingEmailSender(ILogger logger) : IEmailSender +internal sealed partial class LoggingEmailSender(ILogger logger, IHostEnvironment environment) : IEmailSender { public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default) { - LogEmail(to, subject, body); + if (environment.IsDevelopment()) + LogEmail(to, subject, body); + else + LogMissingTransport(); return Task.CompletedTask; } [LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")] private partial void LogEmail(string to, string subject, string body); + + [LoggerMessage(Level = LogLevel.Warning, Message = "E-mail nebyl odeslán. Pro toto prostředí není nakonfigurován poštovní transport.")] + private partial void LogMissingTransport(); } From 1ff4a0a81497f932aedb258104a301f91fe2c9b7 Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Wed, 18 Nov 2026 21:58:33 +0100 Subject: [PATCH 3/3] Add proposal workflow and voting API --- .../Controllers/ProposalsController.cs | 63 +++++++ .../Abstractions/Abstractions.cs | 11 +- .../DependencyInjection.cs | 3 + .../Issues/IssueService.cs | 42 +---- .../Notifications/NotificationService.cs | 8 +- .../Notifications/NotificationWriter.cs | 52 ++++++ .../Proposals/ProposalDtos.cs | 29 ++++ .../Proposals/ProposalService.Reads.cs | 104 ++++++++++++ .../Proposals/ProposalService.cs | 156 ++++++++++++++++++ .../Issues/IssueNotification.cs | 41 ----- .../Notifications/Notification.cs | 63 +++++++ .../src/Helpdesk.Domain/Proposals/Proposal.cs | 64 +++++++ .../Proposals/ProposalRecords.cs | 66 ++++++++ .../Persistence/HelpdeskDbContext.cs | 26 ++- .../Persistence/IssueConfigurations.cs | 7 +- .../Persistence/ProposalConfigurations.cs | 46 ++++++ .../tests/Helpdesk.UnitTests/ProposalTests.cs | 98 +++++++++++ 17 files changed, 796 insertions(+), 83 deletions(-) create mode 100644 backend/src/Helpdesk.Api/Controllers/ProposalsController.cs create mode 100644 backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs create mode 100644 backend/src/Helpdesk.Application/Proposals/ProposalDtos.cs create mode 100644 backend/src/Helpdesk.Application/Proposals/ProposalService.Reads.cs create mode 100644 backend/src/Helpdesk.Application/Proposals/ProposalService.cs delete mode 100644 backend/src/Helpdesk.Domain/Issues/IssueNotification.cs create mode 100644 backend/src/Helpdesk.Domain/Notifications/Notification.cs create mode 100644 backend/src/Helpdesk.Domain/Proposals/Proposal.cs create mode 100644 backend/src/Helpdesk.Domain/Proposals/ProposalRecords.cs create mode 100644 backend/src/Helpdesk.Infrastructure/Persistence/ProposalConfigurations.cs create mode 100644 backend/tests/Helpdesk.UnitTests/ProposalTests.cs diff --git a/backend/src/Helpdesk.Api/Controllers/ProposalsController.cs b/backend/src/Helpdesk.Api/Controllers/ProposalsController.cs new file mode 100644 index 0000000..5b9bebf --- /dev/null +++ b/backend/src/Helpdesk.Api/Controllers/ProposalsController.cs @@ -0,0 +1,63 @@ +using Helpdesk.Api.Infrastructure; +using Helpdesk.Application.Common; +using Helpdesk.Application.Proposals; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Helpdesk.Api.Controllers; + +[ApiController] +[Authorize] +[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)] +[Route("api/proposals")] +[ProducesResponseType(StatusCodes.Status400BadRequest)] +[ProducesResponseType(StatusCodes.Status401Unauthorized)] +[ProducesResponseType(StatusCodes.Status403Forbidden)] +[ProducesResponseType(StatusCodes.Status404NotFound)] +[ProducesResponseType(StatusCodes.Status409Conflict)] +public sealed class ProposalsController(ProposalService proposals) : ControllerBase +{ + [HttpGet] + public Task> List([FromQuery] ProposalQuery query, CancellationToken ct) => + proposals.ListAsync(query, ct); + + [HttpGet("{id:int}")] + public Task Get(int id, CancellationToken ct) => proposals.GetAsync(id, ct); + + [HttpPost] + [RequestSizeLimit(1024 * 1024)] + [ProducesResponseType(StatusCodes.Status201Created)] + public async Task> Create(SaveProposalRequest request, CancellationToken ct) + { + var proposal = await proposals.CreateAsync(request, ct); + return CreatedAtAction(nameof(Get), new { id = proposal.Id }, proposal); + } + + [HttpPut("{id:int}")] + [RequestSizeLimit(1024 * 1024)] + public Task Edit(int id, SaveProposalRequest request, CancellationToken ct) => + proposals.EditAsync(id, request, ct); + + [HttpPut("{id:int}/vote")] + [RequestSizeLimit(1024 * 1024)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task SetVote(int id, VoteRequest request, CancellationToken ct) + { + await proposals.SetVoteAsync(id, request.Value, ct); + return NoContent(); + } + + [HttpDelete("{id:int}/vote")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task RemoveVote(int id, CancellationToken ct) + { + await proposals.RemoveVoteAsync(id, ct); + return NoContent(); + } + + [HttpPost("{id:int}/status")] + [Authorize(Roles = Roles.Management)] + [RequestSizeLimit(1024 * 1024)] + public Task ChangeStatus(int id, ChangeProposalStatusRequest request, CancellationToken ct) => + proposals.ChangeStatusAsync(id, request, ct); +} diff --git a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs index 9da6dcb..81f767d 100644 --- a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs +++ b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs @@ -1,8 +1,11 @@ using Helpdesk.Domain.Auth; using Helpdesk.Domain.Catalogs; using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; +using Helpdesk.Domain.Proposals; using Helpdesk.Domain.Users; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; namespace Helpdesk.Application.Abstractions; @@ -16,11 +19,17 @@ public interface IAppDbContext DbSet Issues { get; } DbSet IssueEvents { get; } DbSet Attachments { get; } - DbSet IssueNotifications { get; } + DbSet Proposals { get; } + DbSet ProposalEvents { get; } + DbSet ProposalVotes { get; } + DbSet ProposalScores { get; } + DbSet Notifications { get; } DbSet NotificationDeliveries { get; } DbSet PushDevices { get; } Task SaveChangesAsync(CancellationToken cancellationToken = default); + Task BeginProposalWriteAsync(CancellationToken ct); + Task LockProposalAsync(int id, CancellationToken ct); } public interface IPasswordHasher diff --git a/backend/src/Helpdesk.Application/DependencyInjection.cs b/backend/src/Helpdesk.Application/DependencyInjection.cs index e16c834..462c29b 100644 --- a/backend/src/Helpdesk.Application/DependencyInjection.cs +++ b/backend/src/Helpdesk.Application/DependencyInjection.cs @@ -3,6 +3,7 @@ using Helpdesk.Application.Auth; using Helpdesk.Application.Catalogs; using Helpdesk.Application.Issues; using Helpdesk.Application.Notifications; +using Helpdesk.Application.Proposals; using Helpdesk.Application.Users; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -22,6 +23,8 @@ public static class DependencyInjection services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); return services; } } diff --git a/backend/src/Helpdesk.Application/Issues/IssueService.cs b/backend/src/Helpdesk.Application/Issues/IssueService.cs index 2983c19..8752382 100644 --- a/backend/src/Helpdesk.Application/Issues/IssueService.cs +++ b/backend/src/Helpdesk.Application/Issues/IssueService.cs @@ -1,14 +1,17 @@ using System.Text; using Helpdesk.Application.Abstractions; using Helpdesk.Application.Common; +using Helpdesk.Application.Notifications; using Helpdesk.Domain; using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; 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 sealed partial class IssueService( + IAppDbContext db, ICurrentUser currentUser, IAttachmentStore files, TimeProvider clock, NotificationWriter notificationWriter) { public async Task CreateAsync(CreateIssueRequest request, IReadOnlyList uploads, CancellationToken ct) { @@ -19,7 +22,7 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU 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); + await notificationWriter.ForIssueAsync(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()); } @@ -49,9 +52,9 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU 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); + await notificationWriter.ForIssueAsync(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 notificationWriter.ForIssueAsync(issue, actor.Id, [issue.ReporterId], NotificationType.IssueStatusChanged, "Závada byla přiřazena", ct); await SaveAsync(ct); return await LoadDetailAsync(issue, actor, ct); @@ -74,7 +77,7 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU 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 notificationWriter.ForIssueAsync(issue, actor.Id, [recipientId], type, title, ct); } await SaveAsync(ct); @@ -88,7 +91,7 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU 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 notificationWriter.ForIssueAsync(issue, actor.Id, recipients, NotificationType.IssueCommentAdded, "Nový komentář k závadě", ct); await SaveAsync(ct); return ToEvent(entry, actor.FullName); } @@ -190,33 +193,6 @@ public sealed partial class IssueService(IAppDbContext db, ICurrentUser currentU 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 diff --git a/backend/src/Helpdesk.Application/Notifications/NotificationService.cs b/backend/src/Helpdesk.Application/Notifications/NotificationService.cs index 50ac01f..7299ed3 100644 --- a/backend/src/Helpdesk.Application/Notifications/NotificationService.cs +++ b/backend/src/Helpdesk.Application/Notifications/NotificationService.cs @@ -1,7 +1,7 @@ using Helpdesk.Application.Abstractions; using Helpdesk.Application.Common; using Helpdesk.Domain; -using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; using Microsoft.EntityFrameworkCore; namespace Helpdesk.Application.Notifications; @@ -46,13 +46,13 @@ public sealed class NotificationService(IAppDbContext db, ICurrentUser currentUs public async Task MarkAllReadAsync(CancellationToken ct) => await MarkUnreadRowsAsync(Inbox(), ct); - private IQueryable Inbox() + private IQueryable Inbox() { var userId = currentUser.Id; - return db.IssueNotifications.Where(n => n.UserId == userId); + return db.Notifications.Where(n => n.UserId == userId); } - private Task MarkUnreadRowsAsync(IQueryable query, CancellationToken ct) + private Task MarkUnreadRowsAsync(IQueryable query, CancellationToken ct) { var now = clock.GetUtcNow().UtcDateTime; return query.Where(n => n.ReadAt == null) diff --git a/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs b/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs new file mode 100644 index 0000000..1f14be6 --- /dev/null +++ b/backend/src/Helpdesk.Application/Notifications/NotificationWriter.cs @@ -0,0 +1,52 @@ +using Helpdesk.Application.Abstractions; +using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; +using Helpdesk.Domain.Proposals; +using Helpdesk.Domain.Users; +using Microsoft.EntityFrameworkCore; + +namespace Helpdesk.Application.Notifications; + +/// Připraví notifikace a záznamy outboxu pro uložení spolu s událostí. +public sealed class NotificationWriter(IAppDbContext db, TimeProvider clock) +{ + public Task ForIssueAsync(Issue issue, int actorId, int[] recipientIds, NotificationType type, string title, + CancellationToken ct) + { + var reporterId = issue.ReporterId; + var eligibleUsers = db.Users.Where(u => + u.Id == reporterId || u.Role == UserRole.FacilityManager || u.Role == UserRole.Management); + return QueueAsync(eligibleUsers, actorId, recipientIds, + id => new Notification(issue, id, type, title, issue.Title), ct); + } + + public Task ForProposalStatusAsync(Proposal proposal, int actorId, CancellationToken ct) => + QueueAsync(db.Users, actorId, [proposal.AuthorId], + id => new Notification(proposal, id, "Stav návrhu se změnil"), ct); + + private async Task QueueAsync(IQueryable eligibleUsers, int actorId, int[] recipientIds, + Func create, CancellationToken ct) + { + var ids = recipientIds.Where(id => id != actorId).Distinct().ToArray(); + if (ids.Length == 0) + return; + + var recipients = await eligibleUsers.Where(u => u.IsActive && ids.Contains(u.Id)) + .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 = create(recipient.Id); + db.Notifications.Add(notification); + db.NotificationDeliveries.AddRange( + new NotificationDelivery(notification, DeliveryChannel.Email, recipient.Email, now), + new NotificationDelivery(notification, DeliveryChannel.Push, recipient.Push, now)); + } + } +} diff --git a/backend/src/Helpdesk.Application/Proposals/ProposalDtos.cs b/backend/src/Helpdesk.Application/Proposals/ProposalDtos.cs new file mode 100644 index 0000000..19a3114 --- /dev/null +++ b/backend/src/Helpdesk.Application/Proposals/ProposalDtos.cs @@ -0,0 +1,29 @@ +namespace Helpdesk.Application.Proposals; + +public sealed record SaveProposalRequest(string Title, string Description, int CategoryId); +public sealed record ChangeProposalStatusRequest(string Status, string? Note); +public sealed record VoteRequest(int Value); + +public sealed class ProposalQuery +{ + public string? Status { get; init; } + public int? CategoryId { get; init; } + public int? AuthorId { get; init; } + public string? Q { get; init; } + public string? Sort { get; init; } + public int Page { get; init; } = 1; + public int PageSize { get; init; } = 20; +} + +public record ProposalSummary( + int Id, string Title, int CategoryId, int AuthorId, string Status, DateTime CreatedAt, + long VotesFor, long VotesAgainst, long Score, int? MyVote); + +public sealed record ProposalDetail( + int Id, string Title, int CategoryId, int AuthorId, string Status, DateTime CreatedAt, + long VotesFor, long VotesAgainst, long Score, int? MyVote, string Description, IReadOnlyList Events) + : ProposalSummary(Id, Title, CategoryId, AuthorId, Status, CreatedAt, VotesFor, VotesAgainst, Score, MyVote); + +public sealed record ProposalEventDto( + int Id, string EventType, string? FromStatus, string ToStatus, int ActorId, string ActorName, string? Note, + DateTime OccurredAt); diff --git a/backend/src/Helpdesk.Application/Proposals/ProposalService.Reads.cs b/backend/src/Helpdesk.Application/Proposals/ProposalService.Reads.cs new file mode 100644 index 0000000..577243d --- /dev/null +++ b/backend/src/Helpdesk.Application/Proposals/ProposalService.Reads.cs @@ -0,0 +1,104 @@ +using Helpdesk.Application.Common; +using Helpdesk.Domain; +using Helpdesk.Domain.Proposals; +using Microsoft.EntityFrameworkCore; + +namespace Helpdesk.Application.Proposals; + +public sealed partial class ProposalService +{ + public async Task> ListAsync(ProposalQuery filters, CancellationToken ct) + { + await GetActorRoleAsync(ct); + var proposals = db.Proposals.AsNoTracking(); + if (filters.Status is { } code) + { + var status = ParseStatus(code); + proposals = proposals.Where(p => p.Status == status); + } + if (filters.CategoryId is int categoryId) + proposals = proposals.Where(p => p.CategoryId == categoryId); + if (filters.AuthorId is int authorId) + proposals = proposals.Where(p => p.AuthorId == authorId); + if (!string.IsNullOrWhiteSpace(filters.Q)) + { + var term = filters.Q.Trim(); + proposals = proposals.Where(p => p.Title.Contains(term) || p.Description.Contains(term)); + } + + var rows = WithScores(proposals); + var ordered = filters.Sort switch + { + null or "newest" => rows.OrderByDescending(r => r.Proposal.CreatedAt).ThenByDescending(r => r.Proposal.Id), + "score" => rows.OrderByDescending(r => r.Score).ThenByDescending(r => r.Proposal.CreatedAt) + .ThenByDescending(r => r.Proposal.Id), + _ => throw new BadRequestException("Řazení musí být newest nebo score."), + }; + + var page = Math.Max(1, filters.Page); + var pageSize = Math.Clamp(filters.PageSize, 1, 100); + var total = await proposals.CountAsync(ct); + var offset = (long)(page - 1) * pageSize; + if (offset >= total) + return new PagedResult([], total, page, pageSize); + + var pageRows = await ordered.Skip((int)offset).Take(pageSize).ToListAsync(ct); + return new PagedResult(pageRows.Select(ToSummary).ToArray(), total, page, pageSize); + } + + public async Task GetAsync(int id, CancellationToken ct) + { + await GetActorRoleAsync(ct); + return await LoadDetailAsync(id, ct); + } + + private async Task LoadDetailAsync(int id, CancellationToken ct) + { + var row = await WithScores(db.Proposals.AsNoTracking().Where(p => p.Id == id)).SingleOrDefaultAsync(ct) + ?? throw new NotFoundException("Návrh neexistuje."); + var entries = await ( + from entry in db.ProposalEvents.AsNoTracking() + join actor in db.Users on entry.ActorId equals actor.Id + where entry.ProposalId == id + orderby entry.OccurredAt, entry.Id + select new { Entry = entry, actor.FirstName, actor.LastName }).ToListAsync(ct); + var events = entries.Select(e => new ProposalEventDto( + e.Entry.Id, e.Entry.EventType.ToCode(), e.Entry.FromStatus?.ToCode(), e.Entry.ToStatus.ToCode(), + e.Entry.ActorId, $"{e.FirstName} {e.LastName}", e.Entry.Note, e.Entry.OccurredAt)).ToArray(); + var summary = ToSummary(row); + return new ProposalDetail(summary.Id, summary.Title, summary.CategoryId, summary.AuthorId, summary.Status, + summary.CreatedAt, summary.VotesFor, summary.VotesAgainst, summary.Score, summary.MyVote, row.Proposal.Description, events); + } + + private IQueryable WithScores(IQueryable proposals) + { + var actorId = currentUser.Id; + return from proposal in proposals + join score in db.ProposalScores on proposal.Id equals score.ProposalId + select new ScoredProposal + { + Proposal = proposal, + VotesFor = score.VotesFor, + VotesAgainst = score.VotesAgainst, + Score = score.Score, + MyVote = db.ProposalVotes.Where(v => v.ProposalId == proposal.Id && v.UserId == actorId) + .Select(v => (sbyte?)v.Value).FirstOrDefault(), + }; + } + + private static ProposalSummary ToSummary(ScoredProposal row) + { + var proposal = row.Proposal; + return new ProposalSummary(proposal.Id, proposal.Title, proposal.CategoryId, proposal.AuthorId, + proposal.Status.ToCode(), proposal.CreatedAt, (long)row.VotesFor, (long)row.VotesAgainst, (long)row.Score, row.MyVote); + } + + private sealed class ScoredProposal + { + public required Proposal Proposal { get; init; } + public decimal VotesFor { get; init; } + public decimal VotesAgainst { get; init; } + public decimal Score { get; init; } + public sbyte? MyVote { get; init; } + } +} diff --git a/backend/src/Helpdesk.Application/Proposals/ProposalService.cs b/backend/src/Helpdesk.Application/Proposals/ProposalService.cs new file mode 100644 index 0000000..233ee95 --- /dev/null +++ b/backend/src/Helpdesk.Application/Proposals/ProposalService.cs @@ -0,0 +1,156 @@ +using System.Text; +using Helpdesk.Application.Abstractions; +using Helpdesk.Application.Common; +using Helpdesk.Application.Notifications; +using Helpdesk.Domain; +using Helpdesk.Domain.Proposals; +using Helpdesk.Domain.Users; +using Microsoft.EntityFrameworkCore; + +namespace Helpdesk.Application.Proposals; + +public sealed partial class ProposalService( + IAppDbContext db, ICurrentUser currentUser, NotificationWriter notifications, TimeProvider clock) +{ + private const int MaxTextBytes = 65_535; + + public async Task CreateAsync(SaveProposalRequest request, CancellationToken ct) + { + await GetActorRoleAsync(ct); + var (title, description) = ValidateDetails(request); + await RequireActiveCategoryAsync(request.CategoryId, ct); + var proposal = new Proposal(currentUser.Id, title, description, request.CategoryId); + db.Proposals.Add(proposal); + AddEvent(proposal, ProposalEventType.Created); + await db.SaveChangesAsync(ct); + return await LoadDetailAsync(proposal.Id, ct); + } + + public async Task EditAsync(int id, SaveProposalRequest request, CancellationToken ct) + { + await GetActorRoleAsync(ct); + var (title, description) = ValidateDetails(request); + await using (var transaction = await db.BeginProposalWriteAsync(ct)) + { + var proposal = await LockProposalAsync(id, ct); + if (!proposal.IsAuthor(currentUser.Id)) + throw new ForbiddenException("Návrh může upravit jen jeho autor."); + if (!proposal.IsEditable) + throw new ConflictException("Návrh lze upravit jen ve stavu Podán."); + + if (proposal.CategoryId != request.CategoryId) + await RequireActiveCategoryAsync(request.CategoryId, ct); + + proposal.Edit(currentUser.Id, title, description, request.CategoryId); + AddEvent(proposal, ProposalEventType.Updated); + await db.SaveChangesAsync(ct); + await transaction.CommitAsync(ct); + } + + return await LoadDetailAsync(id, ct); + } + + public async Task ChangeStatusAsync(int id, ChangeProposalStatusRequest request, CancellationToken ct) + { + var role = await GetActorRoleAsync(ct); + if (role != UserRole.Management) + throw new ForbiddenException("Stav návrhu může změnit jen vedení školy."); + + var target = ParseStatus(request.Status); + var note = string.IsNullOrWhiteSpace(request.Note) ? null : request.Note.Trim(); + if (target == ProposalStatus.Rejected && note is null) + throw new BadRequestException("Zamítnutí vyžaduje vyjádření."); + if (note is not null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes) + throw new BadRequestException("Vyjádření je příliš dlouhé."); + + await using (var transaction = await db.BeginProposalWriteAsync(ct)) + { + var proposal = await LockProposalAsync(id, ct); + var previous = proposal.Status; + if (!proposal.CanTransitionTo(target)) + throw new ConflictException("Přechod do požadovaného stavu není povolen."); + + proposal.ChangeStatus(target, role, note); + AddEvent(proposal, ProposalEventType.StatusChanged, previous, note); + await notifications.ForProposalStatusAsync(proposal, currentUser.Id, ct); + await db.SaveChangesAsync(ct); + await transaction.CommitAsync(ct); + } + + return await LoadDetailAsync(id, ct); + } + + public Task SetVoteAsync(int id, int value, CancellationToken ct) + { + if (value is not (1 or -1)) + throw new BadRequestException("Hlas musí mít hodnotu 1 nebo -1."); + + return ChangeVoteAsync(id, (sbyte)value, ct); + } + + public Task RemoveVoteAsync(int id, CancellationToken ct) => ChangeVoteAsync(id, null, ct); + + private async Task ChangeVoteAsync(int id, sbyte? value, CancellationToken ct) + { + await GetActorRoleAsync(ct); + var actorId = currentUser.Id; + await using var transaction = await db.BeginProposalWriteAsync(ct); + var proposal = await LockProposalAsync(id, ct); + if (proposal.IsAuthor(actorId)) + throw new ForbiddenException("Autor nemůže hlasovat o vlastním návrhu."); + if (!proposal.IsVotingOpen) + throw new ConflictException("Hlasování je uzavřeno."); + + var vote = await db.ProposalVotes.SingleOrDefaultAsync(v => v.ProposalId == id && v.UserId == actorId, ct); + if (value is sbyte newValue) + { + var now = clock.GetUtcNow().UtcDateTime; + if (vote is null) + db.ProposalVotes.Add(new ProposalVote(proposal, actorId, newValue, now)); + else + vote.SetValue(proposal, newValue, now); + } + else if (vote is not null) + { + db.ProposalVotes.Remove(vote); + } + + await db.SaveChangesAsync(ct); + await transaction.CommitAsync(ct); + } + + private async Task GetActorRoleAsync(CancellationToken ct) + { + var id = currentUser.Id; + return await db.Users.Where(u => u.Id == id && u.IsActive).Select(u => (UserRole?)u.Role).SingleOrDefaultAsync(ct) + ?? throw new UnauthorizedException("Účet není aktivní."); + } + + private async Task LockProposalAsync(int id, CancellationToken ct) => + await db.LockProposalAsync(id, ct) ?? throw new NotFoundException("Návrh neexistuje."); + + private async Task RequireActiveCategoryAsync(int id, CancellationToken ct) + { + if (!await db.ProposalCategories.AnyAsync(c => c.Id == id && c.IsActive, ct)) + throw new BadRequestException("Vyberte aktivní oblast návrhu."); + } + + private static (string Title, string Description) ValidateDetails(SaveProposalRequest request) + { + var title = request.Title?.Trim(); + var description = request.Description?.Trim(); + if (string.IsNullOrEmpty(title) || title.Length > 200) + throw new BadRequestException("Název návrhu musí mít 1 až 200 znaků."); + if (string.IsNullOrEmpty(description) || Encoding.UTF8.GetByteCount(description) > MaxTextBytes) + throw new BadRequestException("Vyplňte popis návrhu v povolené délce."); + return (title, description); + } + + private void AddEvent(Proposal proposal, ProposalEventType type, ProposalStatus? previous = null, string? note = null) => + db.ProposalEvents.Add(new ProposalEvent(proposal, type, previous, currentUser.Id, note, clock.GetUtcNow().UtcDateTime)); + + private static ProposalStatus ParseStatus(string status) => + EnumCode.TryParse(status, out var value) + ? value + : throw new BadRequestException("Neplatný stav návrhu."); +} diff --git a/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs b/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs deleted file mode 100644 index 144c935..0000000 --- a/backend/src/Helpdesk.Domain/Issues/IssueNotification.cs +++ /dev/null @@ -1,41 +0,0 @@ -namespace Helpdesk.Domain.Issues; - -public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged } -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 int? ProposalId { 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 DateTime? ReadAt { get; private 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/Notifications/Notification.cs b/backend/src/Helpdesk.Domain/Notifications/Notification.cs new file mode 100644 index 0000000..53b1b46 --- /dev/null +++ b/backend/src/Helpdesk.Domain/Notifications/Notification.cs @@ -0,0 +1,63 @@ +using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Proposals; + +namespace Helpdesk.Domain.Notifications; + +public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged } +public enum DeliveryChannel { Email, Push } +public enum DeliveryStatus { Pending, Skipped } + +public sealed class Notification : IHasCreatedAt +{ + private Notification() { } + + public Notification(Issue issue, int userId, NotificationType type, string title, string message) + : this(userId, type, title, message) + { + Issue = issue; + } + + public Notification(Proposal proposal, int userId, string title) + : this(userId, NotificationType.ProposalStatusChanged, title, proposal.Title) + { + ProposalId = proposal.Id; + } + + private Notification(int userId, NotificationType type, string title, string message) + { + UserId = userId; + Type = type; + Title = title; + Message = message; + } + + public int Id { get; private set; } + public int? IssueId { get; private set; } + public int? ProposalId { get; private set; } + public Issue? Issue { get; private set; } + public int UserId { get; private set; } + public NotificationType Type { get; private set; } + public string Title { get; private set; } = null!; + public string Message { get; private set; } = null!; + public DateTime CreatedAt { get; set; } + public DateTime? ReadAt { get; private set; } +} + +public sealed class NotificationDelivery( + Notification 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 Notification 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/Proposals/Proposal.cs b/backend/src/Helpdesk.Domain/Proposals/Proposal.cs new file mode 100644 index 0000000..1c17a07 --- /dev/null +++ b/backend/src/Helpdesk.Domain/Proposals/Proposal.cs @@ -0,0 +1,64 @@ +using Helpdesk.Domain.Users; + +namespace Helpdesk.Domain.Proposals; + +public enum ProposalStatus { Submitted, UnderReview, Accepted, Rejected, Implemented } +public enum ProposalEventType { Created, Updated, StatusChanged } + +public sealed class Proposal : IHasCreatedAt +{ + private Proposal() { } + + public Proposal(int authorId, string title, string description, int categoryId) + { + AuthorId = authorId; + SetDetails(title, description, categoryId); + } + + public int Id { get; private set; } + public int AuthorId { get; private set; } + public string Title { get; private set; } = null!; + public string Description { get; private set; } = null!; + public int CategoryId { get; private set; } + public ProposalStatus Status { get; private set; } = ProposalStatus.Submitted; + public DateTime CreatedAt { get; set; } + + public bool IsAuthor(int userId) => AuthorId == userId; + public bool IsEditable => Status == ProposalStatus.Submitted; + public bool IsVotingOpen => Status is ProposalStatus.Submitted or ProposalStatus.UnderReview; + public bool CanEdit(int userId) => IsAuthor(userId) && IsEditable; + public bool CanVote(int userId) => !IsAuthor(userId) && IsVotingOpen; + + public bool CanTransitionTo(ProposalStatus target) => Status switch + { + ProposalStatus.Submitted => target is ProposalStatus.UnderReview or ProposalStatus.Accepted or ProposalStatus.Rejected, + ProposalStatus.UnderReview => target is ProposalStatus.Accepted or ProposalStatus.Rejected, + ProposalStatus.Accepted => target == ProposalStatus.Implemented, + _ => false, + }; + + public void Edit(int actorId, string title, string description, int categoryId) + { + if (!CanEdit(actorId)) + throw new InvalidOperationException("Návrh nelze upravit."); + + SetDetails(title, description, categoryId); + } + + public void ChangeStatus(ProposalStatus target, UserRole role, string? note) + { + if (role != UserRole.Management || !CanTransitionTo(target)) + throw new InvalidOperationException("Stav návrhu nelze změnit."); + if (target == ProposalStatus.Rejected && string.IsNullOrWhiteSpace(note)) + throw new ArgumentException("Zamítnutí vyžaduje vyjádření.", nameof(note)); + + Status = target; + } + + private void SetDetails(string title, string description, int categoryId) + { + Title = title; + Description = description; + CategoryId = categoryId; + } +} diff --git a/backend/src/Helpdesk.Domain/Proposals/ProposalRecords.cs b/backend/src/Helpdesk.Domain/Proposals/ProposalRecords.cs new file mode 100644 index 0000000..aa6932e --- /dev/null +++ b/backend/src/Helpdesk.Domain/Proposals/ProposalRecords.cs @@ -0,0 +1,66 @@ +namespace Helpdesk.Domain.Proposals; + +public sealed class ProposalEvent +{ + private ProposalEvent() { } + + public ProposalEvent(Proposal proposal, ProposalEventType eventType, ProposalStatus? fromStatus, int actorId, + string? note, DateTime occurredAt) + { + Proposal = proposal; + EventType = eventType; + FromStatus = fromStatus; + ToStatus = proposal.Status; + ActorId = actorId; + Note = note; + OccurredAt = occurredAt; + } + + public int Id { get; private set; } + public int ProposalId { get; private set; } + public Proposal Proposal { get; private set; } = null!; + public ProposalEventType EventType { get; private set; } + public ProposalStatus? FromStatus { get; private set; } + public ProposalStatus 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 ProposalVote +{ + private ProposalVote() { } + + public ProposalVote(Proposal proposal, int userId, sbyte value, DateTime now) + { + ProposalId = proposal.Id; + UserId = userId; + SetValue(proposal, value, now); + } + + public int ProposalId { get; private set; } + public int UserId { get; private set; } + public sbyte Value { get; private set; } + public DateTime VotedAt { get; private set; } + + public void SetValue(Proposal proposal, sbyte value, DateTime now) + { + if (proposal.Id != ProposalId || !proposal.CanVote(UserId)) + throw new InvalidOperationException("O návrhu nelze hlasovat."); + if (value is not (1 or -1)) + throw new ArgumentOutOfRangeException(nameof(value)); + if (Value == value) + return; + + Value = value; + VotedAt = now; + } +} + +public sealed class ProposalScore +{ + public int ProposalId { get; private set; } + public decimal VotesFor { get; private set; } + public decimal VotesAgainst { get; private set; } + public decimal Score { get; private set; } +} diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs index d964065..2645811 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs @@ -1,10 +1,14 @@ +using System.Data; using Helpdesk.Application.Abstractions; using Helpdesk.Domain.Auth; using Helpdesk.Domain.Catalogs; using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; +using Helpdesk.Domain.Proposals; using Helpdesk.Domain.Users; using Helpdesk.Infrastructure.Security; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Helpdesk.Infrastructure.Persistence; @@ -24,10 +28,24 @@ public sealed class HelpdeskDbContext(DbContextOptions option public DbSet Issues => Set(); public DbSet IssueEvents => Set(); public DbSet Attachments => Set(); - public DbSet IssueNotifications => Set(); + public DbSet Proposals => Set(); + public DbSet ProposalEvents => Set(); + public DbSet ProposalVotes => Set(); + public DbSet ProposalScores => Set(); + public DbSet Notifications => Set(); public DbSet NotificationDeliveries => Set(); public DbSet PushDevices => Set(); + public Task BeginProposalWriteAsync(CancellationToken ct) => + Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct); + + public async Task LockProposalAsync(int id, CancellationToken ct) + { + // Všechny zápisy nad návrhem zamykají stejný řádek před čtením stavu a hlasů. + var rows = await Proposals.FromSql($"SELECT * FROM proposal WHERE id = {id} FOR UPDATE").ToListAsync(ct); + return rows.SingleOrDefault(); + } + protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplyConfiguration(new UserConfiguration(encryptor)); @@ -38,7 +56,11 @@ public sealed class HelpdeskDbContext(DbContextOptions option modelBuilder.ApplyConfiguration(new IssueConfiguration()); modelBuilder.ApplyConfiguration(new IssueEventConfiguration()); modelBuilder.ApplyConfiguration(new AttachmentConfiguration()); - modelBuilder.ApplyConfiguration(new IssueNotificationConfiguration()); + modelBuilder.ApplyConfiguration(new ProposalConfiguration()); + modelBuilder.ApplyConfiguration(new ProposalEventConfiguration()); + modelBuilder.ApplyConfiguration(new ProposalVoteConfiguration()); + modelBuilder.Entity().HasNoKey().ToView("v_proposal_score"); + modelBuilder.ApplyConfiguration(new NotificationConfiguration()); modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration()); modelBuilder.Entity().ToTable("push_device"); } diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs b/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs index 6394776..6186dcd 100644 --- a/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs +++ b/backend/src/Helpdesk.Infrastructure/Persistence/IssueConfigurations.cs @@ -1,5 +1,7 @@ using Helpdesk.Domain.Catalogs; using Helpdesk.Domain.Issues; +using Helpdesk.Domain.Notifications; +using Helpdesk.Domain.Proposals; using Helpdesk.Domain.Users; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; @@ -50,15 +52,16 @@ internal sealed class AttachmentConfiguration : IEntityTypeConfiguration +internal sealed class NotificationConfiguration : IEntityTypeConfiguration { - public void Configure(EntityTypeBuilder b) + 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.ProposalId); b.HasOne().WithMany().HasForeignKey(x => x.UserId); } } diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/ProposalConfigurations.cs b/backend/src/Helpdesk.Infrastructure/Persistence/ProposalConfigurations.cs new file mode 100644 index 0000000..1394d9e --- /dev/null +++ b/backend/src/Helpdesk.Infrastructure/Persistence/ProposalConfigurations.cs @@ -0,0 +1,46 @@ +using Helpdesk.Domain.Catalogs; +using Helpdesk.Domain.Proposals; +using Helpdesk.Domain.Users; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Helpdesk.Infrastructure.Persistence; + +internal sealed class ProposalConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("proposal"); + b.Property(x => x.Title).HasMaxLength(200); + b.Property(x => x.Description).HasColumnType("text"); + b.Property(x => x.Status).HasConversion>().HasMaxLength(30); + b.HasOne().WithMany().HasForeignKey(x => x.CategoryId); + b.HasOne().WithMany().HasForeignKey(x => x.AuthorId); + } +} + +internal sealed class ProposalEventConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("proposal_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.Proposal).WithMany().HasForeignKey(x => x.ProposalId); + b.HasOne().WithMany().HasForeignKey(x => x.ActorId); + } +} + +internal sealed class ProposalVoteConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder b) + { + b.ToTable("proposal_vote"); + b.HasKey(x => new { x.ProposalId, x.UserId }); + b.Property(x => x.Value).HasColumnType("tinyint"); + b.HasOne().WithMany().HasForeignKey(x => x.ProposalId); + b.HasOne().WithMany().HasForeignKey(x => x.UserId); + } +} diff --git a/backend/tests/Helpdesk.UnitTests/ProposalTests.cs b/backend/tests/Helpdesk.UnitTests/ProposalTests.cs new file mode 100644 index 0000000..7fa42f5 --- /dev/null +++ b/backend/tests/Helpdesk.UnitTests/ProposalTests.cs @@ -0,0 +1,98 @@ +using Helpdesk.Domain.Proposals; +using Helpdesk.Domain.Users; + +namespace Helpdesk.UnitTests; + +public sealed class ProposalTests +{ + private const int Author = 1; + private const int Voter = 2; + + [Theory] + [InlineData(ProposalStatus.Submitted, ProposalStatus.UnderReview, ProposalStatus.Accepted, ProposalStatus.Rejected)] + [InlineData(ProposalStatus.UnderReview, ProposalStatus.Accepted, ProposalStatus.Rejected)] + [InlineData(ProposalStatus.Accepted, ProposalStatus.Implemented)] + [InlineData(ProposalStatus.Rejected)] + [InlineData(ProposalStatus.Implemented)] + public void EnforcesTransitionTable(ProposalStatus from, params ProposalStatus[] permitted) + { + foreach (var target in Enum.GetValues()) + { + var proposal = At(from); + var allowed = permitted.Contains(target); + Assert.Equal(allowed, proposal.CanTransitionTo(target)); + if (allowed) + { + proposal.ChangeStatus(target, UserRole.Management, "Vyjádření"); + Assert.Equal(target, proposal.Status); + } + else + { + Assert.Throws(() => proposal.ChangeStatus(target, UserRole.Management, null)); + Assert.Equal(from, proposal.Status); + } + } + } + + [Fact] + public void ReviewRequiresManagementAndRejectionRequiresNote() + { + var proposal = At(ProposalStatus.Submitted); + Assert.Throws(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null)); + Assert.Throws(() => proposal.ChangeStatus(ProposalStatus.Rejected, UserRole.Management, " ")); + Assert.Equal(ProposalStatus.Submitted, proposal.Status); + } + + [Theory] + [InlineData(ProposalStatus.Submitted, true, true)] + [InlineData(ProposalStatus.UnderReview, false, true)] + [InlineData(ProposalStatus.Accepted, false, false)] + [InlineData(ProposalStatus.Rejected, false, false)] + [InlineData(ProposalStatus.Implemented, false, false)] + public void AuthorEditsAndOtherUserVotesOnlyInEligibleStates(ProposalStatus state, bool mayEdit, bool mayVote) + { + var proposal = At(state); + Assert.Equal(mayEdit, proposal.CanEdit(Author)); + Assert.False(proposal.CanEdit(Voter)); + Assert.False(proposal.CanVote(Author)); + Assert.Equal(mayVote, proposal.CanVote(Voter)); + Assert.Throws(() => proposal.Edit(Voter, "Změna", "Popis", 1)); + if (mayEdit) + { + proposal.Edit(Author, "Změna", "Popis", 1); + Assert.Equal("Změna", proposal.Title); + } + else + { + Assert.Throws(() => proposal.Edit(Author, "Změna", "Popis", 1)); + } + } + + [Fact] + public void RepeatingVotePreservesTimestampAndClosingPreventsChanges() + { + var proposal = At(ProposalStatus.Submitted); + var now = DateTime.UnixEpoch; + Assert.Throws(() => new ProposalVote(proposal, Author, 1, now)); + Assert.Throws(() => new ProposalVote(proposal, Voter, 0, now)); + + var vote = new ProposalVote(proposal, Voter, 1, now); + vote.SetValue(proposal, 1, now.AddMinutes(1)); + Assert.Equal(now, vote.VotedAt); + vote.SetValue(proposal, -1, now.AddMinutes(2)); + Assert.Equal((sbyte)-1, vote.Value); + Assert.Equal(now.AddMinutes(2), vote.VotedAt); + proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Management, null); + Assert.Throws(() => vote.SetValue(proposal, 1, now.AddMinutes(3))); + } + + private static Proposal At(ProposalStatus status) + { + var proposal = new Proposal(Author, "Návrh", "Popis", 1); + if (status == ProposalStatus.Implemented) + proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Management, null); + if (status != ProposalStatus.Submitted) + proposal.ChangeStatus(status, UserRole.Management, "Vyjádření"); + return proposal; + } +}