Merge remote-tracking branch 'origin/main' into mobile-app
This commit is contained in:
commit
a65516b810
35 files changed
+2233
-19
No files matched your search
@@ -0,0 +1,11 @@
|
|||||||
|
**
|
||||||
|
!backend/Directory.Build.props
|
||||||
|
!backend/Directory.Packages.props
|
||||||
|
!backend/src/
|
||||||
|
!db/migrations/
|
||||||
|
backend/**/bin
|
||||||
|
backend/**/obj
|
||||||
|
**/.env
|
||||||
|
**/*.env
|
||||||
|
**/*.pem
|
||||||
|
**/*.pfx
|
||||||
@@ -43,7 +43,7 @@ Při prvním startu se vytvoří účet administrátora z `ADMIN_EMAIL` / `ADMIN
|
|||||||
Vyžaduje .NET SDK 10. Unit testy:
|
Vyžaduje .NET SDK 10. Unit testy:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
dotnet test --solution backend/Helpdesk.sln
|
dotnet run --project backend/tests/Helpdesk.UnitTests/Helpdesk.UnitTests.csproj
|
||||||
```
|
```
|
||||||
|
|
||||||
## Mobilní aplikace
|
## Mobilní aplikace
|
||||||
|
|||||||
@@ -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<FileStreamResult>(StatusCodes.Status200OK, "application/octet-stream")]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||||
|
public async Task<IActionResult> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(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<PagedResult<IssueSummary>> List([FromQuery] IssueQuery query, CancellationToken ct) =>
|
||||||
|
issues.ListAsync(query, ct);
|
||||||
|
|
||||||
|
[HttpGet("{id:int}")]
|
||||||
|
public Task<IssueDetail> 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<IssueDetail>(StatusCodes.Status201Created)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
|
||||||
|
public async Task<ActionResult<IssueDetail>> 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<IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false } sizeLimit)
|
||||||
|
sizeLimit.MaxRequestBodySize = MaxJsonCreateBytes;
|
||||||
|
|
||||||
|
request = await Request.ReadFromJsonAsync<CreateIssueRequest>(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<IssueDetail> Edit(int id, EditIssueRequest request, CancellationToken ct) =>
|
||||||
|
issues.EditAsync(id, request, ct);
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/assign")]
|
||||||
|
public Task<IssueDetail> Assign(int id, AssignIssueRequest request, CancellationToken ct) =>
|
||||||
|
issues.AssignAsync(id, request, ct);
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/start")]
|
||||||
|
public Task<IssueDetail> Start(int id, IssueVersionRequest request, CancellationToken ct) =>
|
||||||
|
issues.TransitionAsync(id, IssueAction.StartWork, request.RowVersion, null, ct);
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/submit-for-verification")]
|
||||||
|
public Task<IssueDetail> SubmitForVerification(int id, VerifyIssueRequest request, CancellationToken ct) =>
|
||||||
|
issues.TransitionAsync(id, IssueAction.SubmitForVerification, request.RowVersion, request.Note, ct);
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/confirm")]
|
||||||
|
public Task<IssueDetail> Confirm(int id, IssueVersionRequest request, CancellationToken ct) =>
|
||||||
|
issues.TransitionAsync(id, IssueAction.Confirm, request.RowVersion, null, ct);
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/reopen")]
|
||||||
|
public Task<IssueDetail> Reopen(int id, IssueReasonRequest request, CancellationToken ct) =>
|
||||||
|
issues.TransitionAsync(id, IssueAction.Reopen, request.RowVersion, request.Reason, ct);
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/reject")]
|
||||||
|
public Task<IssueDetail> Reject(int id, IssueReasonRequest request, CancellationToken ct) =>
|
||||||
|
issues.TransitionAsync(id, IssueAction.Reject, request.RowVersion, request.Reason, ct);
|
||||||
|
|
||||||
|
[HttpGet("{id:int}/events")]
|
||||||
|
public Task<IReadOnlyList<IssueEventDto>> Events(int id, CancellationToken ct) => issues.GetEventsAsync(id, ct);
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/comments")]
|
||||||
|
[EnableRateLimiting(RateLimitPolicies.IssueWrites)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
|
||||||
|
public Task<IssueEventDto> 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<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
|
||||||
|
public async Task<ActionResult<IReadOnlyList<AttachmentDto>>> 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<IFormCollection> 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<FormValueProviderFactory>();
|
||||||
|
context.ValueProviderFactories.RemoveType<FormFileValueProviderFactory>();
|
||||||
|
context.ValueProviderFactories.RemoveType<JQueryFormValueProviderFactory>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnResourceExecuted(ResourceExecutedContext context) { }
|
||||||
|
}
|
||||||
@@ -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<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||||
|
public sealed class NotificationsController(NotificationService notifications) : ControllerBase
|
||||||
|
{
|
||||||
|
[HttpGet]
|
||||||
|
public Task<PagedResult<NotificationDto>> 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<UnreadCountDto> CountUnread(CancellationToken ct) => notifications.CountUnreadAsync(ct);
|
||||||
|
|
||||||
|
[HttpPost("{id:int}/read")]
|
||||||
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||||
|
public async Task<IActionResult> MarkRead(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await notifications.MarkReadAsync(id, ct);
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("read-all")]
|
||||||
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||||
|
public async Task<IActionResult> MarkAllRead(CancellationToken ct)
|
||||||
|
{
|
||||||
|
await notifications.MarkAllReadAsync(ct);
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||||
|
public sealed class ProposalsController(ProposalService proposals) : ControllerBase
|
||||||
|
{
|
||||||
|
[HttpGet]
|
||||||
|
public Task<PagedResult<ProposalSummary>> List([FromQuery] ProposalQuery query, CancellationToken ct) =>
|
||||||
|
proposals.ListAsync(query, ct);
|
||||||
|
|
||||||
|
[HttpGet("{id:int}")]
|
||||||
|
public Task<ProposalDetail> Get(int id, CancellationToken ct) => proposals.GetAsync(id, ct);
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
[RequestSizeLimit(1024 * 1024)]
|
||||||
|
[ProducesResponseType<ProposalDetail>(StatusCodes.Status201Created)]
|
||||||
|
public async Task<ActionResult<ProposalDetail>> 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<ProposalDetail> 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<IActionResult> 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<IActionResult> 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<ProposalDetail> ChangeStatus(int id, ChangeProposalStatusRequest request, CancellationToken ct) =>
|
||||||
|
proposals.ChangeStatusAsync(id, request, ct);
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Issues;
|
||||||
using Helpdesk.Application.Users;
|
using Helpdesk.Application.Users;
|
||||||
|
using Helpdesk.Api.Infrastructure;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
@@ -10,7 +12,7 @@ namespace Helpdesk.Api.Controllers;
|
|||||||
[Authorize]
|
[Authorize]
|
||||||
[Route("api/users")]
|
[Route("api/users")]
|
||||||
[Produces("application/json")]
|
[Produces("application/json")]
|
||||||
public sealed class UsersController(UserService users, ICurrentUser currentUser) : ControllerBase
|
public sealed class UsersController(UserService users, ICurrentUser currentUser, IssueService issues) : ControllerBase
|
||||||
{
|
{
|
||||||
/// <summary>Můj profil.</summary>
|
/// <summary>Můj profil.</summary>
|
||||||
[HttpGet("me")]
|
[HttpGet("me")]
|
||||||
@@ -21,4 +23,11 @@ public sealed class UsersController(UserService users, ICurrentUser currentUser)
|
|||||||
[ProducesResponseType<UserDto>(StatusCodes.Status200OK)]
|
[ProducesResponseType<UserDto>(StatusCodes.Status200OK)]
|
||||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||||
public Task<UserDto> UpdateMe(UpdateProfileRequest request, CancellationToken ct) => users.UpdateMeAsync(currentUser, request, ct);
|
public Task<UserDto> UpdateMe(UpdateProfileRequest request, CancellationToken ct) => users.UpdateMeAsync(currentUser, request, ct);
|
||||||
|
|
||||||
|
/// <summary>Aktivní řešitelé s počtem otevřených závad.</summary>
|
||||||
|
[HttpGet("assignable")]
|
||||||
|
[Authorize(Roles = Roles.Management)]
|
||||||
|
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||||
|
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||||
|
public Task<IReadOnlyList<AssignableUserDto>> GetAssignable(CancellationToken ct) => issues.GetAssignableAsync(ct);
|
||||||
}
|
}
|
||||||
@@ -21,6 +21,7 @@ internal sealed class AppExceptionHandler(IProblemDetailsService problemDetails)
|
|||||||
Title = "Neplatná vstupní data.",
|
Title = "Neplatná vstupní data.",
|
||||||
},
|
},
|
||||||
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message },
|
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message },
|
||||||
|
BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode },
|
||||||
_ => null,
|
_ => null,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -42,4 +42,5 @@ public static class AuthenticationSetup
|
|||||||
public static class RateLimitPolicies
|
public static class RateLimitPolicies
|
||||||
{
|
{
|
||||||
public const string Auth = "auth";
|
public const string Auth = "auth";
|
||||||
|
public const string IssueWrites = "issue-writes";
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
using Microsoft.OpenApi;
|
using Microsoft.OpenApi;
|
||||||
|
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||||
|
using Helpdesk.Api.Controllers;
|
||||||
|
using Helpdesk.Application.Issues;
|
||||||
|
|
||||||
namespace Helpdesk.Api.Infrastructure;
|
namespace Helpdesk.Api.Infrastructure;
|
||||||
|
|
||||||
@@ -30,6 +33,7 @@ public static class SwaggerSetup
|
|||||||
{
|
{
|
||||||
[new OpenApiSecuritySchemeReference(SchemeId, document)] = [],
|
[new OpenApiSecuritySchemeReference(SchemeId, document)] = [],
|
||||||
});
|
});
|
||||||
|
options.OperationFilter<IssueRequestBody>();
|
||||||
|
|
||||||
var xml = Path.Combine(AppContext.BaseDirectory, "Helpdesk.Api.xml");
|
var xml = Path.Combine(AppContext.BaseDirectory, "Helpdesk.Api.xml");
|
||||||
if (File.Exists(xml))
|
if (File.Exists(xml))
|
||||||
@@ -38,3 +42,63 @@ public static class SwaggerSetup
|
|||||||
return services;
|
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<string, IOpenApiSchema>
|
||||||
|
{
|
||||||
|
["files"] = new OpenApiSchema
|
||||||
|
{
|
||||||
|
Type = JsonSchemaType.Array,
|
||||||
|
MinItems = 1,
|
||||||
|
MaxItems = AttachmentLimits.MaxFiles,
|
||||||
|
Items = new OpenApiSchema { Type = JsonSchemaType.String, Format = "binary" },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
var required = new HashSet<string> { "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<string, OpenApiMediaType>
|
||||||
|
{
|
||||||
|
["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,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ using Helpdesk.Api.Infrastructure;
|
|||||||
using Helpdesk.Application;
|
using Helpdesk.Application;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Infrastructure;
|
using Helpdesk.Infrastructure;
|
||||||
|
using Microsoft.IdentityModel.JsonWebTokens;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
@@ -20,13 +21,21 @@ builder.Services.AddProblemDetails();
|
|||||||
builder.Services.AddExceptionHandler<AppExceptionHandler>();
|
builder.Services.AddExceptionHandler<AppExceptionHandler>();
|
||||||
builder.Services.AddHelpdeskSwagger();
|
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 =>
|
builder.Services.AddRateLimiter(options =>
|
||||||
{
|
{
|
||||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter(
|
options.AddPolicy(RateLimitPolicies.Auth, http => RateLimitPartition.GetFixedWindowLimiter(
|
||||||
http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
|
http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
|
||||||
_ => new FixedWindowRateLimiterOptions { PermitLimit = 20, Window = TimeSpan.FromMinutes(1) }));
|
_ => 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();
|
var app = builder.Build();
|
||||||
@@ -41,9 +50,9 @@ app.UseSwaggerUI(options =>
|
|||||||
options.DocumentTitle = "Helpdesk API";
|
options.DocumentTitle = "Helpdesk API";
|
||||||
});
|
});
|
||||||
|
|
||||||
app.UseRateLimiter();
|
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
app.UseRateLimiter();
|
||||||
|
|
||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
using Helpdesk.Domain.Auth;
|
using Helpdesk.Domain.Auth;
|
||||||
using Helpdesk.Domain.Catalogs;
|
using Helpdesk.Domain.Catalogs;
|
||||||
|
using Helpdesk.Domain.Issues;
|
||||||
|
using Helpdesk.Domain.Notifications;
|
||||||
|
using Helpdesk.Domain.Proposals;
|
||||||
using Helpdesk.Domain.Users;
|
using Helpdesk.Domain.Users;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage;
|
||||||
|
|
||||||
namespace Helpdesk.Application.Abstractions;
|
namespace Helpdesk.Application.Abstractions;
|
||||||
|
|
||||||
@@ -12,8 +16,20 @@ public interface IAppDbContext
|
|||||||
DbSet<Building> Buildings { get; }
|
DbSet<Building> Buildings { get; }
|
||||||
DbSet<IssueCategory> IssueCategories { get; }
|
DbSet<IssueCategory> IssueCategories { get; }
|
||||||
DbSet<ProposalCategory> ProposalCategories { get; }
|
DbSet<ProposalCategory> ProposalCategories { get; }
|
||||||
|
DbSet<Issue> Issues { get; }
|
||||||
|
DbSet<IssueEvent> IssueEvents { get; }
|
||||||
|
DbSet<Attachment> Attachments { get; }
|
||||||
|
DbSet<Proposal> Proposals { get; }
|
||||||
|
DbSet<ProposalEvent> ProposalEvents { get; }
|
||||||
|
DbSet<ProposalVote> ProposalVotes { get; }
|
||||||
|
DbSet<ProposalScore> ProposalScores { get; }
|
||||||
|
DbSet<Notification> Notifications { get; }
|
||||||
|
DbSet<NotificationDelivery> NotificationDeliveries { get; }
|
||||||
|
DbSet<PushDevice> PushDevices { get; }
|
||||||
|
|
||||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct);
|
||||||
|
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
public interface IPasswordHasher
|
public interface IPasswordHasher
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
using FluentValidation;
|
using FluentValidation;
|
||||||
using Helpdesk.Application.Auth;
|
using Helpdesk.Application.Auth;
|
||||||
using Helpdesk.Application.Catalogs;
|
using Helpdesk.Application.Catalogs;
|
||||||
|
using Helpdesk.Application.Issues;
|
||||||
|
using Helpdesk.Application.Notifications;
|
||||||
|
using Helpdesk.Application.Proposals;
|
||||||
using Helpdesk.Application.Users;
|
using Helpdesk.Application.Users;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
@@ -18,6 +21,10 @@ public static class DependencyInjection
|
|||||||
services.AddScoped<AuthService>();
|
services.AddScoped<AuthService>();
|
||||||
services.AddScoped<UserService>();
|
services.AddScoped<UserService>();
|
||||||
services.AddScoped<CatalogService>();
|
services.AddScoped<CatalogService>();
|
||||||
|
services.AddScoped<IssueService>();
|
||||||
|
services.AddScoped<NotificationService>();
|
||||||
|
services.AddScoped<NotificationWriter>();
|
||||||
|
services.AddScoped<ProposalService>();
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using Helpdesk.Domain;
|
||||||
|
using Helpdesk.Domain.Issues;
|
||||||
|
|
||||||
|
namespace Helpdesk.Application.Issues;
|
||||||
|
|
||||||
|
public record CreateIssueRequest(
|
||||||
|
[Required, StringLength(200)] string Title,
|
||||||
|
[Required] string Description,
|
||||||
|
[Range(1, int.MaxValue)] int CategoryId,
|
||||||
|
[Range(1, int.MaxValue)] int? BuildingId,
|
||||||
|
[StringLength(255)] string? LocationDetail);
|
||||||
|
|
||||||
|
public sealed record EditIssueRequest(
|
||||||
|
string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail,
|
||||||
|
[Required, Range(0, int.MaxValue)] int? RowVersion)
|
||||||
|
: CreateIssueRequest(Title, Description, CategoryId, BuildingId, LocationDetail);
|
||||||
|
|
||||||
|
public sealed record AssignIssueRequest(
|
||||||
|
int AssigneeId, string? Priority, [Required, Range(0, int.MaxValue)] int? RowVersion);
|
||||||
|
|
||||||
|
public record IssueVersionRequest([Required, Range(0, int.MaxValue)] int? RowVersion);
|
||||||
|
public sealed record VerifyIssueRequest(int? RowVersion, string? Note) : IssueVersionRequest(RowVersion);
|
||||||
|
public sealed record IssueReasonRequest(int? RowVersion, string Reason) : IssueVersionRequest(RowVersion);
|
||||||
|
public sealed record CommentRequest(string Text);
|
||||||
|
|
||||||
|
public sealed class IssueQuery
|
||||||
|
{
|
||||||
|
public string? Status { get; init; }
|
||||||
|
public int? CategoryId { get; init; }
|
||||||
|
public int? BuildingId { get; init; }
|
||||||
|
public int? AssigneeId { get; init; }
|
||||||
|
public int? ReporterId { get; init; }
|
||||||
|
public DateTimeOffset? From { get; init; }
|
||||||
|
public DateTimeOffset? To { get; init; }
|
||||||
|
public string? Q { get; init; }
|
||||||
|
public bool Mine { get; init; }
|
||||||
|
public string? Sort { get; init; }
|
||||||
|
public int Page { get; init; } = 1;
|
||||||
|
public int PageSize { get; init; } = 20;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record IssueSummary(
|
||||||
|
int Id, string Title, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
|
||||||
|
string Priority, int ReporterId, int? AssigneeId, DateTime CreatedAt)
|
||||||
|
{
|
||||||
|
internal static IssueSummary From(Issue issue) => new(
|
||||||
|
issue.Id, issue.Title, issue.CategoryId, issue.BuildingId, issue.LocationDetail, issue.Status.ToCode(),
|
||||||
|
issue.Priority.ToCode(), issue.ReporterId, issue.AssigneeId, issue.CreatedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record IssueDetail(
|
||||||
|
int Id, string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
|
||||||
|
string Priority, int ReporterId, int? AssigneeId, DateTime CreatedAt, int RowVersion,
|
||||||
|
IReadOnlyList<string> AllowedActions, IReadOnlyList<AttachmentDto> Attachments);
|
||||||
|
|
||||||
|
public sealed record IssueEventDto(
|
||||||
|
int Id, string EventType, string? FromStatus, string ToStatus, int ActorId, string ActorName, string? Note,
|
||||||
|
DateTime OccurredAt);
|
||||||
|
|
||||||
|
public sealed record AssignableUserDto(int Id, string FirstName, string LastName, string Role, int OpenIssues);
|
||||||
|
|
||||||
|
public sealed record AttachmentDto(int Id, string FileName, string ContentType, long SizeBytes, DateTime CreatedAt)
|
||||||
|
{
|
||||||
|
internal static AttachmentDto From(Attachment attachment) => new(
|
||||||
|
attachment.Id, attachment.OriginalFileName, attachment.ContentType, attachment.SizeBytes, attachment.CreatedAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record AttachmentUpload(string FileName, long SizeBytes, Func<Stream> OpenRead);
|
||||||
|
public sealed record StoredAttachment(string OriginalFileName, string StoredFileName, string ContentType, long SizeBytes);
|
||||||
|
public sealed record AttachmentDownload(Stream Content, string FileName, string ContentType);
|
||||||
|
|
||||||
|
public interface IAttachmentStore
|
||||||
|
{
|
||||||
|
Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct);
|
||||||
|
Stream OpenRead(string storedFileName);
|
||||||
|
void Delete(string storedFileName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class AttachmentLimits
|
||||||
|
{
|
||||||
|
public const int MaxFiles = 5;
|
||||||
|
public const int MaxFileBytes = 10 * 1024 * 1024;
|
||||||
|
public const int MaxRequestBytes = MaxFiles * MaxFileBytes + 1024 * 1024;
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Domain;
|
||||||
|
using Helpdesk.Domain.Issues;
|
||||||
|
using Helpdesk.Domain.Users;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Helpdesk.Application.Issues;
|
||||||
|
|
||||||
|
public sealed partial class IssueService
|
||||||
|
{
|
||||||
|
public async Task<PagedResult<IssueSummary>> ListAsync(IssueQuery filters, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var actor = await GetActorAsync(ct);
|
||||||
|
var issues = db.Issues.AsNoTracking();
|
||||||
|
if (filters.Mine || !Issue.CanReadAll(actor.Role))
|
||||||
|
issues = issues.Where(i => i.ReporterId == actor.Id);
|
||||||
|
|
||||||
|
if (filters.Status is { } statusCode)
|
||||||
|
{
|
||||||
|
var status = ParseCode<IssueStatus>(statusCode);
|
||||||
|
issues = issues.Where(i => i.Status == status);
|
||||||
|
}
|
||||||
|
if (filters.CategoryId is int categoryId)
|
||||||
|
issues = issues.Where(i => i.CategoryId == categoryId);
|
||||||
|
if (filters.BuildingId is int buildingId)
|
||||||
|
issues = issues.Where(i => i.BuildingId == buildingId);
|
||||||
|
if (filters.AssigneeId is int assigneeId)
|
||||||
|
issues = issues.Where(i => i.AssigneeId == assigneeId);
|
||||||
|
if (filters.ReporterId is int reporterId)
|
||||||
|
issues = issues.Where(i => i.ReporterId == reporterId);
|
||||||
|
if (filters.From >= filters.To)
|
||||||
|
throw new BadRequestException("Začátek období musí předcházet jeho konci.");
|
||||||
|
if (filters.From?.UtcDateTime is DateTime from)
|
||||||
|
issues = issues.Where(i => i.CreatedAt >= from);
|
||||||
|
if (filters.To?.UtcDateTime is DateTime to)
|
||||||
|
issues = issues.Where(i => i.CreatedAt < to);
|
||||||
|
if (!string.IsNullOrWhiteSpace(filters.Q))
|
||||||
|
{
|
||||||
|
var term = filters.Q.Trim();
|
||||||
|
issues = issues.Where(i => i.Title.Contains(term) || i.Description.Contains(term));
|
||||||
|
}
|
||||||
|
|
||||||
|
var ordered = filters.Sort switch
|
||||||
|
{
|
||||||
|
null or "newest" => issues.OrderByDescending(i => i.CreatedAt).ThenByDescending(i => i.Id),
|
||||||
|
"oldest" => issues.OrderBy(i => i.CreatedAt).ThenBy(i => i.Id),
|
||||||
|
_ => throw new BadRequestException("Řazení musí být newest nebo oldest."),
|
||||||
|
};
|
||||||
|
var page = Math.Max(1, filters.Page);
|
||||||
|
var pageSize = Math.Clamp(filters.PageSize, 1, 100);
|
||||||
|
var total = await issues.CountAsync(ct);
|
||||||
|
var offset = (long)(page - 1) * pageSize;
|
||||||
|
if (offset >= total)
|
||||||
|
return new PagedResult<IssueSummary>([], total, page, pageSize);
|
||||||
|
|
||||||
|
var pageItems = await ordered.Skip((int)offset).Take(pageSize).ToListAsync(ct);
|
||||||
|
return new PagedResult<IssueSummary>(pageItems.Select(IssueSummary.From).ToArray(), total, page, pageSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IssueDetail> GetAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var actor = await GetActorAsync(ct);
|
||||||
|
var issue = await LoadIssueAsync(id, actor, tracking: false, ct);
|
||||||
|
return await LoadDetailAsync(issue, actor, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<IssueEventDto>> GetEventsAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var actor = await GetActorAsync(ct);
|
||||||
|
await LoadIssueAsync(id, actor, tracking: false, ct);
|
||||||
|
var entries = await (
|
||||||
|
from entry in db.IssueEvents.AsNoTracking()
|
||||||
|
join user in db.Users on entry.ActorId equals user.Id
|
||||||
|
where entry.IssueId == id
|
||||||
|
orderby entry.OccurredAt, entry.Id
|
||||||
|
select new { Entry = entry, user.FirstName, user.LastName }).ToListAsync(ct);
|
||||||
|
return entries.Select(entry => ToEvent(entry.Entry, $"{entry.FirstName} {entry.LastName}")).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<AssignableUserDto>> GetAssignableAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
var actor = await GetActorAsync(ct);
|
||||||
|
if (actor.Role != UserRole.Management)
|
||||||
|
throw new ForbiddenException("Přehled řešitelů je určen vedení.");
|
||||||
|
|
||||||
|
var users = await db.Users.Where(u => u.IsActive && (u.Role == UserRole.Management || u.Role == UserRole.FacilityManager))
|
||||||
|
.OrderBy(u => u.LastName).ThenBy(u => u.FirstName).ThenBy(u => u.Id)
|
||||||
|
.Select(u => new
|
||||||
|
{
|
||||||
|
u.Id, u.FirstName, u.LastName, u.Role,
|
||||||
|
OpenIssues = db.Issues.Count(i => i.AssigneeId == u.Id &&
|
||||||
|
(i.Status == IssueStatus.Assigned || i.Status == IssueStatus.InProgress || i.Status == IssueStatus.PendingVerification)),
|
||||||
|
}).ToListAsync(ct);
|
||||||
|
return users.Select(u => new AssignableUserDto(u.Id, u.FirstName, u.LastName, u.Role.ToCode(), u.OpenIssues)).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<AttachmentDownload> DownloadAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var actor = await GetActorAsync(ct);
|
||||||
|
var attachment = await db.Attachments.AsNoTracking().Include(a => a.Issue).SingleOrDefaultAsync(a => a.Id == id, ct)
|
||||||
|
?? throw new NotFoundException("Příloha neexistuje.");
|
||||||
|
if (!attachment.Issue.CanRead(actor.Id, actor.Role))
|
||||||
|
throw new ForbiddenException("K příloze nemáte přístup.");
|
||||||
|
return new AttachmentDownload(files.OpenRead(attachment.StoredFileName), attachment.OriginalFileName, attachment.ContentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<IssueDetail> LoadDetailAsync(Issue issue, User actor, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var attachments = await db.Attachments.AsNoTracking().Where(a => a.IssueId == issue.Id).OrderBy(a => a.Id)
|
||||||
|
.Select(a => new AttachmentDto(a.Id, a.OriginalFileName, a.ContentType, a.SizeBytes, a.CreatedAt)).ToListAsync(ct);
|
||||||
|
return ToDetail(issue, actor, attachments);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IssueDetail ToDetail(Issue issue, User actor, IReadOnlyList<AttachmentDto> attachments)
|
||||||
|
{
|
||||||
|
var actions = Enum.GetValues<IssueAction>()
|
||||||
|
.Where(action => issue.Availability(action, actor.Id, actor.Role) == IssueActionAvailability.Allowed)
|
||||||
|
.Select(action => action.ToCode()).ToArray();
|
||||||
|
|
||||||
|
return new IssueDetail(issue.Id, issue.Title, issue.Description, issue.CategoryId, issue.BuildingId, issue.LocationDetail,
|
||||||
|
issue.Status.ToCode(), issue.Priority.ToCode(), issue.ReporterId, issue.AssigneeId, issue.CreatedAt,
|
||||||
|
issue.RowVersion, actions, attachments);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IssueEventDto ToEvent(IssueEvent entry, string actorName) =>
|
||||||
|
new(entry.Id, entry.EventType.ToCode(), entry.FromStatus?.ToCode(), entry.ToStatus.ToCode(),
|
||||||
|
entry.ActorId, actorName, entry.Note, entry.OccurredAt);
|
||||||
|
}
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
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, NotificationWriter notificationWriter)
|
||||||
|
{
|
||||||
|
public async Task<IssueDetail> CreateAsync(CreateIssueRequest request, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var actor = await GetActorAsync(ct);
|
||||||
|
await ValidateDetailsAsync(request, null, ct);
|
||||||
|
var issue = new Issue(actor.Id, request.Title, request.Description, request.CategoryId, request.BuildingId, request.LocationDetail);
|
||||||
|
db.Issues.Add(issue);
|
||||||
|
AddEvent(issue, IssueEventType.Created, null, actor, null);
|
||||||
|
var managementIds = await db.Users.Where(u => u.IsActive && u.Role == UserRole.Management)
|
||||||
|
.Select(u => u.Id).ToArrayAsync(ct);
|
||||||
|
await 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());
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IssueDetail> EditAsync(int id, EditIssueRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var (issue, actor) = await LoadActionAsync(id, IssueAction.Edit, ct);
|
||||||
|
CheckVersion(issue, request.RowVersion);
|
||||||
|
await ValidateDetailsAsync(request, issue, ct);
|
||||||
|
issue.Edit(actor.Id, actor.Role, request.Title, request.Description, request.CategoryId, request.BuildingId, request.LocationDetail);
|
||||||
|
AddEvent(issue, IssueEventType.Updated, null, actor, null);
|
||||||
|
await SaveAsync(ct);
|
||||||
|
return await LoadDetailAsync(issue, actor, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IssueDetail> AssignAsync(int id, AssignIssueRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var (issue, actor) = await LoadActionAsync(id, IssueAction.Assign, ct);
|
||||||
|
CheckVersion(issue, request.RowVersion);
|
||||||
|
var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct);
|
||||||
|
if (assignee is null || !Issue.CanBeAssigned(assignee.Role))
|
||||||
|
throw new BadRequestException("Vyberte aktivního správce budov nebo člena vedení.");
|
||||||
|
if (issue.AssigneeId == assignee.Id)
|
||||||
|
throw new ConflictException("Závada je již přiřazena tomuto řešiteli.");
|
||||||
|
|
||||||
|
IssuePriority? priority = request.Priority is null ? null : ParseCode<IssuePriority>(request.Priority);
|
||||||
|
var from = issue.Status;
|
||||||
|
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
|
||||||
|
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName);
|
||||||
|
await 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 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IssueDetail> TransitionAsync(int id, IssueAction action, int? version, string? note, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var (issue, actor) = await LoadActionAsync(id, action, ct);
|
||||||
|
CheckVersion(issue, version);
|
||||||
|
note = action is IssueAction.Reopen or IssueAction.Reject
|
||||||
|
? RequiredText(note, "Důvod", MaxTextBytes)
|
||||||
|
: OptionalText(note, "Poznámka", MaxTextBytes);
|
||||||
|
|
||||||
|
var from = issue.Status;
|
||||||
|
issue.Transition(action, actor.Id, actor.Role, note);
|
||||||
|
AddEvent(issue, IssueEventType.StatusChanged, from, actor, note);
|
||||||
|
int? recipient = action is IssueAction.Confirm or IssueAction.Reopen ? issue.AssigneeId : issue.ReporterId;
|
||||||
|
if (recipient is int recipientId)
|
||||||
|
{
|
||||||
|
var (type, title) = action == IssueAction.Reopen
|
||||||
|
? (NotificationType.IssueReopened, "Závada byla znovu otevřena")
|
||||||
|
: (NotificationType.IssueStatusChanged, "Stav závady se změnil");
|
||||||
|
await notificationWriter.ForIssueAsync(issue, actor.Id, [recipientId], type, title, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
await SaveAsync(ct);
|
||||||
|
return await LoadDetailAsync(issue, actor, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IssueEventDto> CommentAsync(int id, CommentRequest request, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var (issue, actor) = await LoadActionAsync(id, IssueAction.Comment, ct);
|
||||||
|
var text = RequiredText(request.Text, "Komentář", MaxTextBytes);
|
||||||
|
issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role);
|
||||||
|
var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text);
|
||||||
|
int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId];
|
||||||
|
await notificationWriter.ForIssueAsync(issue, actor.Id, recipients, NotificationType.IssueCommentAdded, "Nový komentář k závadě", ct);
|
||||||
|
await SaveAsync(ct);
|
||||||
|
return ToEvent(entry, actor.FullName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<AttachmentDto>> AddAttachmentsAsync(
|
||||||
|
int id, Func<CancellationToken, Task<AttachmentUpload[]>> readUploads, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var (issue, actor) = await LoadActionAsync(id, IssueAction.AddAttachments, ct);
|
||||||
|
var uploads = await readUploads(ct);
|
||||||
|
if (uploads.Length == 0)
|
||||||
|
throw new BadRequestException("Vyberte alespoň jeden soubor.");
|
||||||
|
|
||||||
|
issue.RecordParticipation(IssueAction.AddAttachments, actor.Id, actor.Role);
|
||||||
|
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
|
||||||
|
return attachments.Select(AttachmentDto.From).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<IReadOnlyList<Attachment>> SaveWithAttachmentsAsync(
|
||||||
|
Issue issue, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (uploads.Count > AttachmentLimits.MaxFiles)
|
||||||
|
throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů.");
|
||||||
|
|
||||||
|
var attachments = new List<Attachment>(uploads.Count);
|
||||||
|
var saving = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var upload in uploads)
|
||||||
|
{
|
||||||
|
var stored = await files.SaveAsync(upload, ct);
|
||||||
|
var attachment = new Attachment(issue, stored.OriginalFileName, stored.StoredFileName,
|
||||||
|
stored.ContentType, stored.SizeBytes);
|
||||||
|
attachments.Add(attachment);
|
||||||
|
db.Attachments.Add(attachment);
|
||||||
|
}
|
||||||
|
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
saving = true;
|
||||||
|
await SaveAsync(ct);
|
||||||
|
return attachments;
|
||||||
|
}
|
||||||
|
catch (Exception exception) when (!saving || exception is ConflictException)
|
||||||
|
{
|
||||||
|
// Po chybě s neznámým výsledkem commitu soubory ponecháme, aby metadata nemohla odkazovat na smazaná data.
|
||||||
|
foreach (var attachment in attachments)
|
||||||
|
files.Delete(attachment.StoredFileName);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<User> GetActorAsync(CancellationToken ct) =>
|
||||||
|
await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == currentUser.Id && u.IsActive, ct)
|
||||||
|
?? throw new UnauthorizedException("Účet není aktivní.");
|
||||||
|
|
||||||
|
private async Task<Issue> LoadIssueAsync(int id, User actor, bool tracking, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var query = tracking ? db.Issues : db.Issues.AsNoTracking();
|
||||||
|
var issue = await query.SingleOrDefaultAsync(i => i.Id == id, ct)
|
||||||
|
?? throw new NotFoundException("Závada neexistuje.");
|
||||||
|
if (!issue.CanRead(actor.Id, actor.Role))
|
||||||
|
throw new ForbiddenException("K závadě nemáte přístup.");
|
||||||
|
return issue;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<(Issue Issue, User Actor)> LoadActionAsync(int id, IssueAction action, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var actor = await GetActorAsync(ct);
|
||||||
|
var issue = await LoadIssueAsync(id, actor, tracking: true, ct);
|
||||||
|
switch (issue.Availability(action, actor.Id, actor.Role))
|
||||||
|
{
|
||||||
|
case IssueActionAvailability.Forbidden:
|
||||||
|
throw new ForbiddenException("Tuto akci nemůžete provést.");
|
||||||
|
case IssueActionAvailability.InvalidState:
|
||||||
|
throw new ConflictException("Akce není v aktuálním stavu závady možná.");
|
||||||
|
}
|
||||||
|
return (issue, actor);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ValidateDetailsAsync(CreateIssueRequest request, Issue? original, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var title = RequiredText(request.Title, "Název", MaxTextBytes);
|
||||||
|
RequiredText(request.Description, "Popis", MaxTextBytes);
|
||||||
|
if (title.Length > 200 || request.LocationDetail?.Trim().Length > 255)
|
||||||
|
throw new BadRequestException("Název smí mít nejvýše 200 znaků a upřesnění místa 255 znaků.");
|
||||||
|
|
||||||
|
if (original?.CategoryId != request.CategoryId &&
|
||||||
|
!await db.IssueCategories.AnyAsync(c => c.Id == request.CategoryId && c.IsActive, ct))
|
||||||
|
throw new BadRequestException("Vyberte aktivní kategorii závady.");
|
||||||
|
|
||||||
|
if (request.BuildingId is int buildingId && original?.BuildingId != buildingId &&
|
||||||
|
!await db.Buildings.AnyAsync(b => b.Id == buildingId && b.IsActive, ct))
|
||||||
|
throw new BadRequestException("Vyberte aktivní budovu.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private IssueEvent AddEvent(Issue issue, IssueEventType type, IssueStatus? fromStatus, User actor, string? note)
|
||||||
|
{
|
||||||
|
var entry = new IssueEvent(issue, type, fromStatus, actor.Id, note, clock.GetUtcNow().UtcDateTime);
|
||||||
|
db.IssueEvents.Add(entry);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SaveAsync(CancellationToken ct)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
}
|
||||||
|
catch (DbUpdateConcurrencyException)
|
||||||
|
{
|
||||||
|
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CheckVersion(Issue issue, int? supplied)
|
||||||
|
{
|
||||||
|
if (supplied is null or < 0)
|
||||||
|
throw new BadRequestException("Zadejte platnou hodnotu rowVersion.");
|
||||||
|
if (issue.RowVersion != supplied)
|
||||||
|
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private const int MaxTextBytes = 65_535;
|
||||||
|
|
||||||
|
private static string RequiredText(string? input, string name, int maxBytes) =>
|
||||||
|
OptionalText(input, name, maxBytes) ?? throw new BadRequestException($"{name}: hodnota je povinná.");
|
||||||
|
|
||||||
|
private static string? OptionalText(string? input, string name, int maxBytes)
|
||||||
|
{
|
||||||
|
var text = input?.Trim();
|
||||||
|
if (string.IsNullOrEmpty(text))
|
||||||
|
return null;
|
||||||
|
if (Encoding.UTF8.GetByteCount(text) > maxBytes)
|
||||||
|
throw new BadRequestException($"{name}: hodnota je příliš dlouhá.");
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static T ParseCode<T>(string code) where T : struct, Enum =>
|
||||||
|
EnumCode.TryParse<T>(code, out var result)
|
||||||
|
? result
|
||||||
|
: throw new BadRequestException($"Neplatný kód '{code}'.");
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Domain;
|
||||||
|
using Helpdesk.Domain.Notifications;
|
||||||
|
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<PagedResult<NotificationDto>> 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<NotificationDto>([], 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<NotificationDto>(items, total, page, pageSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<UnreadCountDto> 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<Notification> Inbox()
|
||||||
|
{
|
||||||
|
var userId = currentUser.Id;
|
||||||
|
return db.Notifications.Where(n => n.UserId == userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<int> MarkUnreadRowsAsync(IQueryable<Notification> query, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var now = clock.GetUtcNow().UtcDateTime;
|
||||||
|
return query.Where(n => n.ReadAt == null)
|
||||||
|
.ExecuteUpdateAsync(update => update.SetProperty(n => n.ReadAt, now), ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>Připraví notifikace a záznamy outboxu pro uložení spolu s událostí.</summary>
|
||||||
|
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<User> eligibleUsers, int actorId, int[] recipientIds,
|
||||||
|
Func<int, Notification> 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<ProposalEventDto> 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);
|
||||||
@@ -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<PagedResult<ProposalSummary>> 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<ProposalSummary>([], total, page, pageSize);
|
||||||
|
|
||||||
|
var pageRows = await ordered.Skip((int)offset).Take(pageSize).ToListAsync(ct);
|
||||||
|
return new PagedResult<ProposalSummary>(pageRows.Select(ToSummary).ToArray(), total, page, pageSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ProposalDetail> GetAsync(int id, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await GetActorRoleAsync(ct);
|
||||||
|
return await LoadDetailAsync(id, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<ProposalDetail> 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<ScoredProposal> WithScores(IQueryable<Proposal> 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; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<ProposalDetail> 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<ProposalDetail> 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<ProposalDetail> 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<UserRole> 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<Proposal> 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<ProposalStatus>(status, out var value)
|
||||||
|
? value
|
||||||
|
: throw new BadRequestException("Neplatný stav návrhu.");
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Issues;
|
||||||
using Helpdesk.Infrastructure.Background;
|
using Helpdesk.Infrastructure.Background;
|
||||||
using Helpdesk.Infrastructure.Email;
|
using Helpdesk.Infrastructure.Email;
|
||||||
|
using Helpdesk.Infrastructure.Files;
|
||||||
using Helpdesk.Infrastructure.Persistence;
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
using Helpdesk.Infrastructure.Security;
|
using Helpdesk.Infrastructure.Security;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
@@ -32,6 +34,7 @@ public static class DependencyInjection
|
|||||||
services.AddSingleton<ITokenService, JwtTokenService>();
|
services.AddSingleton<ITokenService, JwtTokenService>();
|
||||||
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
|
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
|
||||||
services.AddSingleton<IEmailSender, LoggingEmailSender>();
|
services.AddSingleton<IEmailSender, LoggingEmailSender>();
|
||||||
|
services.AddSingleton<IAttachmentStore, FileAttachmentStore>();
|
||||||
|
|
||||||
services.AddHostedService<RevokedTokenStoreLoader>();
|
services.AddHostedService<RevokedTokenStoreLoader>();
|
||||||
services.AddHostedService<AdminSeeder>();
|
services.AddHostedService<AdminSeeder>();
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Email;
|
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ývojová náhrada odesílání e-mailů – obsah zapíše do logu (odkaz pro ověření e-mailu je tak vidět
|
||||||
/// v <c>docker compose logs api</c>). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi.
|
/// v <c>docker compose logs api</c>). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger) : IEmailSender
|
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger, IHostEnvironment environment) : IEmailSender
|
||||||
{
|
{
|
||||||
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
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;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
[LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")]
|
[LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")]
|
||||||
private partial void LogEmail(string to, string subject, string 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();
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
using System.Buffers.Binary;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Issues;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace Helpdesk.Infrastructure.Files;
|
||||||
|
|
||||||
|
internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) : IAttachmentStore
|
||||||
|
{
|
||||||
|
private readonly string directory = Path.Combine(AppContext.BaseDirectory, "uploads");
|
||||||
|
|
||||||
|
public async Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (upload.SizeBytes is <= 0 or > AttachmentLimits.MaxFileBytes)
|
||||||
|
throw new BadRequestException("Příloha musí mít velikost od 1 B do 10 MB.");
|
||||||
|
|
||||||
|
var name = Path.GetFileName(upload.FileName.Replace('\\', '/')).Trim();
|
||||||
|
if (name.Length is 0 or > 255 || name.Any(char.IsControl))
|
||||||
|
throw new BadRequestException("Neplatný název přílohy.");
|
||||||
|
|
||||||
|
var extension = Path.GetExtension(name).ToLowerInvariant();
|
||||||
|
var contentType = extension switch
|
||||||
|
{
|
||||||
|
".jpg" or ".jpeg" => "image/jpeg",
|
||||||
|
".png" => "image/png",
|
||||||
|
".heic" => "image/heic",
|
||||||
|
".pdf" => "application/pdf",
|
||||||
|
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
|
_ => throw new BadRequestException("Tento typ přílohy není povolen."),
|
||||||
|
};
|
||||||
|
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
var key = Guid.NewGuid().ToString("D");
|
||||||
|
var path = FilePath(key);
|
||||||
|
|
||||||
|
var created = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await using var input = upload.OpenRead();
|
||||||
|
await using var output = new FileStream(path, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None,
|
||||||
|
bufferSize: 64 * 1024, useAsync: true);
|
||||||
|
created = true;
|
||||||
|
|
||||||
|
var buffer = new byte[64 * 1024];
|
||||||
|
long written = 0;
|
||||||
|
int read;
|
||||||
|
while ((read = await input.ReadAsync(buffer, ct)) > 0)
|
||||||
|
{
|
||||||
|
written += read;
|
||||||
|
if (written > upload.SizeBytes)
|
||||||
|
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
|
||||||
|
await output.WriteAsync(buffer.AsMemory(0, read), ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (written != upload.SizeBytes)
|
||||||
|
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
|
||||||
|
|
||||||
|
output.Position = 0;
|
||||||
|
if (!await HasExpectedFormatAsync(output, extension, ct))
|
||||||
|
throw new BadRequestException("Obsah přílohy neodpovídá její příponě.");
|
||||||
|
|
||||||
|
return new StoredAttachment(name, key, contentType, written);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
if (created)
|
||||||
|
Delete(key);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Stream OpenRead(string storedFileName)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return new FileStream(FilePath(storedFileName), FileMode.Open, FileAccess.Read, FileShare.Read,
|
||||||
|
bufferSize: 64 * 1024, useAsync: true);
|
||||||
|
}
|
||||||
|
catch (IOException exception) when (exception is FileNotFoundException or DirectoryNotFoundException)
|
||||||
|
{
|
||||||
|
logger.LogError(exception, "Soubor přílohy {AttachmentKey} v úložišti chybí.", storedFileName);
|
||||||
|
throw new NotFoundException("Soubor přílohy není dostupný.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Delete(string storedFileName)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.Delete(FilePath(storedFileName));
|
||||||
|
}
|
||||||
|
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
logger.LogError(exception, "Soubor přílohy {AttachmentKey} se nepodařilo uklidit.", storedFileName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private string FilePath(string key) => Guid.TryParseExact(key, "D", out _)
|
||||||
|
? Path.Combine(directory, key)
|
||||||
|
: throw new InvalidOperationException("Neplatný klíč souboru přílohy.");
|
||||||
|
|
||||||
|
private static async Task<bool> HasExpectedFormatAsync(Stream stream, string extension, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var header = new byte[(int)Math.Min(stream.Length, 512)];
|
||||||
|
await stream.ReadExactlyAsync(header, ct);
|
||||||
|
return extension switch
|
||||||
|
{
|
||||||
|
".jpg" or ".jpeg" => header.AsSpan().StartsWith(new byte[] { 0xff, 0xd8, 0xff }),
|
||||||
|
".png" => header.AsSpan().StartsWith(new byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a }),
|
||||||
|
".pdf" => header.AsSpan().StartsWith("%PDF-"u8),
|
||||||
|
".heic" => IsHeic(header, stream.Length),
|
||||||
|
".docx" => IsDocx(stream, header),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsHeic(ReadOnlySpan<byte> header, long length)
|
||||||
|
{
|
||||||
|
if (header.Length < 16 || !header.Slice(4, 4).SequenceEqual("ftyp"u8))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var boxLength = BinaryPrimitives.ReadUInt32BigEndian(header);
|
||||||
|
if (boxLength < 16 || boxLength > length)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
for (var offset = 8; offset + 4 <= Math.Min(boxLength, header.Length); offset += 4)
|
||||||
|
{
|
||||||
|
if (offset == 12)
|
||||||
|
continue; // minor_version
|
||||||
|
var brand = header.Slice(offset, 4);
|
||||||
|
if (brand.SequenceEqual("heic"u8) || brand.SequenceEqual("heix"u8) ||
|
||||||
|
brand.SequenceEqual("hevc"u8) || brand.SequenceEqual("hevx"u8))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsDocx(Stream stream, ReadOnlySpan<byte> header)
|
||||||
|
{
|
||||||
|
if (!header.StartsWith(new byte[] { 0x50, 0x4b, 0x03, 0x04 }))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
stream.Position = 0;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var zip = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: true);
|
||||||
|
return zip.GetEntry("[Content_Types].xml") is not null && zip.GetEntry("word/document.xml") is not null;
|
||||||
|
}
|
||||||
|
catch (InvalidDataException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,14 @@
|
|||||||
|
using System.Data;
|
||||||
using Helpdesk.Application.Abstractions;
|
using Helpdesk.Application.Abstractions;
|
||||||
using Helpdesk.Domain.Auth;
|
using Helpdesk.Domain.Auth;
|
||||||
using Helpdesk.Domain.Catalogs;
|
using Helpdesk.Domain.Catalogs;
|
||||||
|
using Helpdesk.Domain.Issues;
|
||||||
|
using Helpdesk.Domain.Notifications;
|
||||||
|
using Helpdesk.Domain.Proposals;
|
||||||
using Helpdesk.Domain.Users;
|
using Helpdesk.Domain.Users;
|
||||||
using Helpdesk.Infrastructure.Security;
|
using Helpdesk.Infrastructure.Security;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage;
|
||||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
namespace Helpdesk.Infrastructure.Persistence;
|
namespace Helpdesk.Infrastructure.Persistence;
|
||||||
@@ -20,6 +25,26 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
public DbSet<Building> Buildings => Set<Building>();
|
public DbSet<Building> Buildings => Set<Building>();
|
||||||
public DbSet<IssueCategory> IssueCategories => Set<IssueCategory>();
|
public DbSet<IssueCategory> IssueCategories => Set<IssueCategory>();
|
||||||
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
|
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
|
||||||
|
public DbSet<Issue> Issues => Set<Issue>();
|
||||||
|
public DbSet<IssueEvent> IssueEvents => Set<IssueEvent>();
|
||||||
|
public DbSet<Attachment> Attachments => Set<Attachment>();
|
||||||
|
public DbSet<Proposal> Proposals => Set<Proposal>();
|
||||||
|
public DbSet<ProposalEvent> ProposalEvents => Set<ProposalEvent>();
|
||||||
|
public DbSet<ProposalVote> ProposalVotes => Set<ProposalVote>();
|
||||||
|
public DbSet<ProposalScore> ProposalScores => Set<ProposalScore>();
|
||||||
|
public DbSet<Notification> Notifications => Set<Notification>();
|
||||||
|
public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>();
|
||||||
|
public DbSet<PushDevice> PushDevices => Set<PushDevice>();
|
||||||
|
|
||||||
|
public Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct) =>
|
||||||
|
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
||||||
|
|
||||||
|
public async Task<Proposal?> 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)
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
{
|
{
|
||||||
@@ -28,6 +53,16 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
|||||||
modelBuilder.ApplyConfiguration(new BuildingConfiguration());
|
modelBuilder.ApplyConfiguration(new BuildingConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new IssueCategoryConfiguration());
|
modelBuilder.ApplyConfiguration(new IssueCategoryConfiguration());
|
||||||
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
|
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
|
||||||
|
modelBuilder.ApplyConfiguration(new IssueConfiguration());
|
||||||
|
modelBuilder.ApplyConfiguration(new IssueEventConfiguration());
|
||||||
|
modelBuilder.ApplyConfiguration(new AttachmentConfiguration());
|
||||||
|
modelBuilder.ApplyConfiguration(new ProposalConfiguration());
|
||||||
|
modelBuilder.ApplyConfiguration(new ProposalEventConfiguration());
|
||||||
|
modelBuilder.ApplyConfiguration(new ProposalVoteConfiguration());
|
||||||
|
modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score");
|
||||||
|
modelBuilder.ApplyConfiguration(new NotificationConfiguration());
|
||||||
|
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
|
||||||
|
modelBuilder.Entity<PushDevice>().ToTable("push_device");
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
|
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
namespace Helpdesk.Infrastructure.Persistence;
|
||||||
|
|
||||||
|
internal sealed class IssueConfiguration : IEntityTypeConfiguration<Issue>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<Issue> b)
|
||||||
|
{
|
||||||
|
b.ToTable("issue");
|
||||||
|
b.Property(x => x.Title).HasMaxLength(200);
|
||||||
|
b.Property(x => x.Description).HasColumnType("text");
|
||||||
|
b.Property(x => x.LocationDetail).HasMaxLength(255);
|
||||||
|
b.Property(x => x.Status).HasConversion<EnumCodeConverter<IssueStatus>>().HasMaxLength(30);
|
||||||
|
b.Property(x => x.Priority).HasConversion<EnumCodeConverter<IssuePriority>>().HasMaxLength(10);
|
||||||
|
b.Property(x => x.RowVersion).IsConcurrencyToken();
|
||||||
|
b.HasOne<IssueCategory>().WithMany().HasForeignKey(x => x.CategoryId);
|
||||||
|
b.HasOne<Building>().WithMany().HasForeignKey(x => x.BuildingId);
|
||||||
|
b.HasOne<User>().WithMany().HasForeignKey(x => x.ReporterId);
|
||||||
|
b.HasOne<User>().WithMany().HasForeignKey(x => x.AssigneeId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class IssueEventConfiguration : IEntityTypeConfiguration<IssueEvent>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<IssueEvent> b)
|
||||||
|
{
|
||||||
|
b.ToTable("issue_event");
|
||||||
|
b.Property(x => x.EventType).HasConversion<EnumCodeConverter<IssueEventType>>().HasMaxLength(20);
|
||||||
|
b.Property(x => x.FromStatus).HasConversion<EnumCodeConverter<IssueStatus>>().HasMaxLength(30);
|
||||||
|
b.Property(x => x.ToStatus).HasConversion<EnumCodeConverter<IssueStatus>>().HasMaxLength(30);
|
||||||
|
b.Property(x => x.Note).HasColumnType("text");
|
||||||
|
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId);
|
||||||
|
b.HasOne<User>().WithMany().HasForeignKey(x => x.ActorId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class AttachmentConfiguration : IEntityTypeConfiguration<Attachment>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<Attachment> b)
|
||||||
|
{
|
||||||
|
b.ToTable("attachment");
|
||||||
|
b.Property(x => x.OriginalFileName).HasMaxLength(255);
|
||||||
|
b.Property(x => x.StoredFileName).HasMaxLength(36);
|
||||||
|
b.Property(x => x.ContentType).HasMaxLength(100);
|
||||||
|
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class NotificationConfiguration : IEntityTypeConfiguration<Notification>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<Notification> b)
|
||||||
|
{
|
||||||
|
b.ToTable("notification");
|
||||||
|
b.Property(x => x.Type).HasConversion<EnumCodeConverter<NotificationType>>().HasMaxLength(40);
|
||||||
|
b.Property(x => x.Title).HasMaxLength(200);
|
||||||
|
b.Property(x => x.Message).HasMaxLength(1000);
|
||||||
|
b.HasOne(x => x.Issue).WithMany().HasForeignKey(x => x.IssueId).IsRequired(false);
|
||||||
|
b.HasOne<Proposal>().WithMany().HasForeignKey(x => x.ProposalId);
|
||||||
|
b.HasOne<User>().WithMany().HasForeignKey(x => x.UserId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class NotificationDeliveryConfiguration : IEntityTypeConfiguration<NotificationDelivery>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<NotificationDelivery> b)
|
||||||
|
{
|
||||||
|
b.ToTable("notification_delivery");
|
||||||
|
b.Property(x => x.Channel).HasConversion<EnumCodeConverter<DeliveryChannel>>().HasMaxLength(10);
|
||||||
|
b.Property(x => x.Status).HasConversion<EnumCodeConverter<DeliveryStatus>>().HasMaxLength(10);
|
||||||
|
b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<Proposal>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<Proposal> b)
|
||||||
|
{
|
||||||
|
b.ToTable("proposal");
|
||||||
|
b.Property(x => x.Title).HasMaxLength(200);
|
||||||
|
b.Property(x => x.Description).HasColumnType("text");
|
||||||
|
b.Property(x => x.Status).HasConversion<EnumCodeConverter<ProposalStatus>>().HasMaxLength(30);
|
||||||
|
b.HasOne<ProposalCategory>().WithMany().HasForeignKey(x => x.CategoryId);
|
||||||
|
b.HasOne<User>().WithMany().HasForeignKey(x => x.AuthorId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class ProposalEventConfiguration : IEntityTypeConfiguration<ProposalEvent>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<ProposalEvent> b)
|
||||||
|
{
|
||||||
|
b.ToTable("proposal_event");
|
||||||
|
b.Property(x => x.EventType).HasConversion<EnumCodeConverter<ProposalEventType>>().HasMaxLength(20);
|
||||||
|
b.Property(x => x.FromStatus).HasConversion<EnumCodeConverter<ProposalStatus>>().HasMaxLength(30);
|
||||||
|
b.Property(x => x.ToStatus).HasConversion<EnumCodeConverter<ProposalStatus>>().HasMaxLength(30);
|
||||||
|
b.Property(x => x.Note).HasColumnType("text");
|
||||||
|
b.HasOne(x => x.Proposal).WithMany().HasForeignKey(x => x.ProposalId);
|
||||||
|
b.HasOne<User>().WithMany().HasForeignKey(x => x.ActorId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class ProposalVoteConfiguration : IEntityTypeConfiguration<ProposalVote>
|
||||||
|
{
|
||||||
|
public void Configure(EntityTypeBuilder<ProposalVote> b)
|
||||||
|
{
|
||||||
|
b.ToTable("proposal_vote");
|
||||||
|
b.HasKey(x => new { x.ProposalId, x.UserId });
|
||||||
|
b.Property(x => x.Value).HasColumnType("tinyint");
|
||||||
|
b.HasOne<Proposal>().WithMany().HasForeignKey(x => x.ProposalId);
|
||||||
|
b.HasOne<User>().WithMany().HasForeignKey(x => x.UserId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<InvalidOperationException>(() => 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<ArgumentException>(() => 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<ArgumentException>(() =>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<ProposalStatus>())
|
||||||
|
{
|
||||||
|
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<InvalidOperationException>(() => proposal.ChangeStatus(target, UserRole.Management, null));
|
||||||
|
Assert.Equal(from, proposal.Status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReviewRequiresManagementAndRejectionRequiresNote()
|
||||||
|
{
|
||||||
|
var proposal = At(ProposalStatus.Submitted);
|
||||||
|
Assert.Throws<InvalidOperationException>(() => proposal.ChangeStatus(ProposalStatus.Accepted, UserRole.Admin, null));
|
||||||
|
Assert.Throws<ArgumentException>(() => 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<InvalidOperationException>(() => 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<InvalidOperationException>(() => proposal.Edit(Author, "Změna", "Popis", 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RepeatingVotePreservesTimestampAndClosingPreventsChanges()
|
||||||
|
{
|
||||||
|
var proposal = At(ProposalStatus.Submitted);
|
||||||
|
var now = DateTime.UnixEpoch;
|
||||||
|
Assert.Throws<InvalidOperationException>(() => new ProposalVote(proposal, Author, 1, now));
|
||||||
|
Assert.Throws<ArgumentOutOfRangeException>(() => 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<InvalidOperationException>(() => 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
-13
@@ -90,9 +90,9 @@ Legenda: ✅ povoleno, 🔸 povoleno s podmínkou, — nepovoleno
|
|||||||
| Centrální přehled všech závad (filtry) | — | ✅ (jen čtení) | ✅ | — |
|
| Centrální přehled všech závad (filtry) | — | ✅ (jen čtení) | ✅ | — |
|
||||||
| Přiřadit / přeřadit závadu řešiteli, nastavit prioritu | — | — | ✅ | — |
|
| 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 | — |
|
| 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* | — |
|
| 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č | — |
|
| 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í | — |
|
| 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í | ✅ | ✅ | ✅ | ✅ |
|
| Podat návrh na zlepšení | ✅ | ✅ | ✅ | ✅ |
|
||||||
| Zobrazit všechny návrhy | ✅ | ✅ | ✅ | ✅ |
|
| Zobrazit všechny návrhy | ✅ | ✅ | ✅ | ✅ |
|
||||||
| Hlasovat pro návrh | 🔸 ne pro vlastní | 🔸 | 🔸 | 🔸 |
|
| Hlasovat pro návrh | 🔸 ne pro vlastní | 🔸 | 🔸 | 🔸 |
|
||||||
@@ -512,6 +512,7 @@ Větvení: `main` (stabilní), `develop`, feature větve `feature/<nazev>`, 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). |
|
| 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. |
|
| Š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ě. |
|
| 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). |
|
| 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. |
|
| 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
|
### Hlášení závad
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| 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í. |
|
| 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) |
|
| 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` |
|
| 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}/assign` | vedení | `{ assigneeId, priority?, rowVersion }` (T2, T3) |
|
||||||
| POST | `/issues/{id}/start` | řešitel | T4 |
|
| POST | `/issues/{id}/start` | řešitel | `{ rowVersion }` (T4) |
|
||||||
| POST | `/issues/{id}/submit-for-verification` | řešitel | `{ note? }` (T5) |
|
| POST | `/issues/{id}/submit-for-verification` | řešitel | `{ rowVersion, note? }` (T5) |
|
||||||
| POST | `/issues/{id}/confirm` | hlásič | T6 |
|
| POST | `/issues/{id}/confirm` | hlásič | `{ rowVersion }` (T6) |
|
||||||
| POST | `/issues/{id}/reopen` | hlásič | `{ reason }` (T7) |
|
| POST | `/issues/{id}/reopen` | hlásič | `{ rowVersion, reason }` (T7) |
|
||||||
| POST | `/issues/{id}/reject` | řešitel / vedení | `{ reason }` (T8, T9) |
|
| 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`) |
|
| 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}/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 | `/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 |
|
| 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.
|
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í
|
### Návrhy na zlepšení
|
||||||
| Metoda | Endpoint | Role | Popis |
|
| Metoda | Endpoint | Role | Popis |
|
||||||
@@ -1164,7 +1166,7 @@ flowchart LR
|
|||||||
|
|
||||||
| Služba | Image | Sítě | Porty | Úložiště | Poznámka |
|
| 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) |
|
| `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 |
|
| `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čí |
|
| `migrator` | vlastní (`dotnet/runtime`) | backend | — | — | aplikuje nové migrace z `db/migrations` a skončí |
|
||||||
|
|||||||
Reference in new issue
Block a user