diff --git a/web/Helpdesk.Web.Tests/IssueTests.cs b/web/Helpdesk.Web.Tests/IssueTests.cs new file mode 100644 index 0000000..b918ef3 --- /dev/null +++ b/web/Helpdesk.Web.Tests/IssueTests.cs @@ -0,0 +1,98 @@ +using System.Net; +using System.Text; +using Helpdesk.Web.Api; +using Helpdesk.Web.Models; +using Microsoft.AspNetCore.Http; + +namespace Helpdesk.Web.Tests; + +public class AttachmentRulesTests +{ + private static IFormFile File(string name, long length) => + new FormFile(new MemoryStream(new byte[Math.Min(length, 16)]), 0, length, "Files", name); + + [Fact] + public void Povolene_soubory_projdou() => + Assert.Empty(AttachmentRules.Validate([File("projektor.JPG", 2_000_000), File("protokol.pdf", 300_000)])); + + [Fact] + public void Vic_nez_pet_souboru_neprojde() => + Assert.Contains(AttachmentRules.Validate(Enumerable.Range(1, 6).Select(i => File($"foto{i}.png", 1000)).ToList()), + e => e.Contains("nejvýše 5")); + + [Theory] + [InlineData("virus.exe", "povolený typ")] + [InlineData("velka.jpg", "10 MB")] + [InlineData("prazdny.png", "prázdný")] + public void Nepovoleny_soubor_ma_srozumitelnou_chybu(string name, string expected) + { + var length = name switch { "velka.jpg" => AttachmentRules.MaxFileBytes + 1, "prazdny.png" => 0, _ => 100 }; + Assert.Contains(AttachmentRules.Validate([File(name, length)]), e => e.Contains(expected)); + } +} + +public class IssueListViewModelTests +{ + private static readonly IssueListViewModel Model = new() + { + Issues = new PagedResult([], 0, 1, 20), + CategoryNames = new Dictionary { [2] = "Technické vybavení" }, + BuildingNames = new Dictionary { [2] = "Budova B" }, + }; + + private static IssueSummary Issue(int? buildingId, string? detail) => + new(1, "Projektor", 2, buildingId, detail, "RECEIVED", "NORMAL", 1, null, DateTimeOffset.UnixEpoch); + + [Theory] + [InlineData(2, "učebna B-205", "Budova B – učebna B-205")] + [InlineData(2, null, "Budova B")] + [InlineData(null, "venku u vchodu", "venku u vchodu")] + [InlineData(null, null, null)] + public void Misto_spoji_budovu_a_upresneni(int? buildingId, string? detail, string? expected) => + Assert.Equal(expected, Model.Location(Issue(buildingId, detail))); + + [Fact] + public void Neznama_kategorie_neshodi_stranku() => Assert.Equal("Neznámá kategorie", Model.CategoryName(99)); +} + +public class CreateIssueRequestTests +{ + [Fact] + public async Task Hlaseni_s_prilohou_jde_do_API_jako_multipart() + { + var handler = new RecordingHandler(); + var api = new HelpdeskApiClient(new HttpClient(handler) { BaseAddress = new Uri("http://api/") }); + + var issue = await api.CreateIssueAsync( + new CreateIssueRequest("Projektor", "Bliká.", 2, BuildingId: null, LocationDetail: "B-205"), + [new UploadFile("foto.jpg", "image/jpeg", () => new MemoryStream([0xFF, 0xD8, 0xFF]))], + CancellationToken.None); + + Assert.Equal(7, issue.Id); + Assert.Equal("/api/v1/issues", handler.Path); + Assert.StartsWith("multipart/form-data", handler.ContentType); + Assert.Contains("name=title", handler.Body); + Assert.Contains("name=categoryId", handler.Body); + Assert.Contains("name=files; filename=foto.jpg", handler.Body); + Assert.DoesNotContain("name=buildingId", handler.Body); // nepovinná pole bez hodnoty se neposílají + } + + private sealed class RecordingHandler : HttpMessageHandler + { + public string? Path { get; private set; } + public string? ContentType { get; private set; } + public string Body { get; private set; } = ""; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + Path = request.RequestUri!.AbsolutePath; + ContentType = request.Content!.Headers.ContentType!.ToString(); + Body = await request.Content.ReadAsStringAsync(ct); + return new HttpResponseMessage(HttpStatusCode.Created) + { + Content = new StringContent("""{"id":7,"title":"Projektor","status":"RECEIVED","rowVersion":0,"allowedActions":["EDIT"]}""", + Encoding.UTF8, "application/json"), + }; + } + } +} diff --git a/web/Helpdesk.Web/Api/ApiModels.cs b/web/Helpdesk.Web/Api/ApiModels.cs index 96751ce..fd5fb9d 100644 --- a/web/Helpdesk.Web/Api/ApiModels.cs +++ b/web/Helpdesk.Web/Api/ApiModels.cs @@ -61,5 +61,14 @@ public sealed record IssueSummary( int Id, string Title, int CategoryId, int? BuildingId, string? LocationDetail, string Status, string Priority, int ReporterId, int? AssigneeId, DateTimeOffset CreatedAt); +/// Nové hlášení. Přílohy jdou ve stejném požadavku (multipart, pole files). +public sealed record CreateIssueRequest(string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail); + +/// Soubor přeposílaný z formuláře webu do API. +public sealed record UploadFile(string FileName, string ContentType, Func OpenRead); + +/// Detail závady (zatím jen pole, která web používá). +public sealed record IssueDetail(int Id, string Title, string Status, int RowVersion, IReadOnlyList AllowedActions); + /// Filtry GET /api/v1/issues; prázdné hodnoty se do dotazu neposílají. public sealed record IssueListQuery(string? Status = null, bool Mine = false, string Sort = "newest", int Page = 1, int PageSize = 20); diff --git a/web/Helpdesk.Web/Api/ApiOptions.cs b/web/Helpdesk.Web/Api/ApiOptions.cs index 89ab774..1a9dacb 100644 --- a/web/Helpdesk.Web/Api/ApiOptions.cs +++ b/web/Helpdesk.Web/Api/ApiOptions.cs @@ -7,5 +7,6 @@ public sealed class ApiOptions public string BaseUrl { get; set; } = ""; - public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(15); + /// Delší kvůli nahrávání příloh (až 5 × 10 MB) na pomalejším připojení. + public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(100); } diff --git a/web/Helpdesk.Web/Api/HelpdeskApiClient.cs b/web/Helpdesk.Web/Api/HelpdeskApiClient.cs index 35ea6cc..025b37e 100644 --- a/web/Helpdesk.Web/Api/HelpdeskApiClient.cs +++ b/web/Helpdesk.Web/Api/HelpdeskApiClient.cs @@ -1,4 +1,5 @@ using System.Globalization; +using System.Net.Http.Headers; using System.Net.Http.Json; using Microsoft.AspNetCore.WebUtilities; @@ -33,6 +34,36 @@ public sealed class HelpdeskApiClient(HttpClient http) return await ApiResponse.ReadAsync>(response, ct); } + /// + /// Nahlásí závadu i s přílohami jedním požadavkem (multipart). Soubory se z formuláře + /// posílají rovnou dál jako proud, web je celé nenačítá do paměti. + /// + public async Task CreateIssueAsync(CreateIssueRequest request, IReadOnlyCollection files, CancellationToken ct) + { + using var content = new MultipartFormDataContent + { + { new StringContent(request.Title), "title" }, + { new StringContent(request.Description), "description" }, + { new StringContent(request.CategoryId.ToString(CultureInfo.InvariantCulture)), "categoryId" }, + }; + if (request.BuildingId is { } buildingId) + content.Add(new StringContent(buildingId.ToString(CultureInfo.InvariantCulture)), "buildingId"); + if (!string.IsNullOrWhiteSpace(request.LocationDetail)) + content.Add(new StringContent(request.LocationDetail), "locationDetail"); + + foreach (var file in files) + { + var part = new StreamContent(file.OpenRead()); + part.Headers.ContentType = MediaTypeHeaderValue.TryParse(file.ContentType, out var type) + ? type + : new MediaTypeHeaderValue("application/octet-stream"); + content.Add(part, "files", file.FileName); + } + + using var response = await http.PostAsync("api/v1/issues", content, ct); + return await ApiResponse.ReadAsync(response, ct); + } + public async Task> GetIssueCategoriesAsync(CancellationToken ct) { using var response = await http.GetAsync("api/v1/issue-categories", ct); diff --git a/web/Helpdesk.Web/Controllers/IssuesController.cs b/web/Helpdesk.Web/Controllers/IssuesController.cs index f62c033..41bc49c 100644 --- a/web/Helpdesk.Web/Controllers/IssuesController.cs +++ b/web/Helpdesk.Web/Controllers/IssuesController.cs @@ -1,4 +1,6 @@ +using System.Net; using Helpdesk.Web.Api; +using Helpdesk.Web.Infrastructure; using Helpdesk.Web.Models; using Microsoft.AspNetCore.Mvc; @@ -28,4 +30,42 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller Status = status, }); } + + /// Formulář nového hlášení (T1 – závada vznikne ve stavu Přijata). + [HttpGet("new")] + public async Task New(CancellationToken ct) => View(await WithCatalogsAsync(new NewIssueViewModel(), ct)); + + [HttpPost("new")] + [RequestSizeLimit(AttachmentRules.MaxRequestBytes)] + [RequestFormLimits(MultipartBodyLengthLimit = AttachmentRules.MaxRequestBytes)] + public async Task New(NewIssueViewModel model, CancellationToken ct) + { + foreach (var error in AttachmentRules.Validate(model.Files)) + ModelState.AddModelError(nameof(NewIssueViewModel.Files), error); + if (!ModelState.IsValid) + return View(await WithCatalogsAsync(model, ct)); + + try + { + var issue = await api.CreateIssueAsync( + new CreateIssueRequest(model.Title.Trim(), model.Description.Trim(), model.CategoryId!.Value, model.BuildingId, model.LocationDetail?.Trim()), + model.Files.Select(f => new UploadFile(f.FileName, f.ContentType, f.OpenReadStream)).ToList(), + ct); + TempData.SetSuccess($"Závada #{issue.Id} je nahlášená. Vedení školy ji přiřadí řešiteli."); + return RedirectToAction(nameof(Index)); + } + catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.RequestEntityTooLarge + or HttpStatusCode.UnsupportedMediaType or HttpStatusCode.TooManyRequests) + { + // 400 validace nebo nepovolený obsah souboru, 413 příliš velké přílohy, 429 limit zápisů (10/min). + ModelState.AddApiErrors(ex, typeof(NewIssueViewModel)); + return View(await WithCatalogsAsync(model, ct)); + } + } + + private async Task WithCatalogsAsync(NewIssueViewModel model, CancellationToken ct) + { + model.SetCatalogs(await api.GetIssueCategoriesAsync(ct), await api.GetBuildingsAsync(ct)); + return model; + } } diff --git a/web/Helpdesk.Web/Infrastructure/Navigation.cs b/web/Helpdesk.Web/Infrastructure/Navigation.cs index 386b998..71a603a 100644 --- a/web/Helpdesk.Web/Infrastructure/Navigation.cs +++ b/web/Helpdesk.Web/Infrastructure/Navigation.cs @@ -19,6 +19,7 @@ public static class Navigation public static readonly IReadOnlyList Items = [ new("Nástěnka", "Home", "Index"), + new("Nahlásit závadu", "Issues", "New"), new("Moje hlášení", "Issues", "Index"), ]; diff --git a/web/Helpdesk.Web/Models/NewIssueViewModel.cs b/web/Helpdesk.Web/Models/NewIssueViewModel.cs new file mode 100644 index 0000000..ed86386 --- /dev/null +++ b/web/Helpdesk.Web/Models/NewIssueViewModel.cs @@ -0,0 +1,76 @@ +using System.ComponentModel.DataAnnotations; +using Helpdesk.Web.Api; +using Microsoft.AspNetCore.Mvc.Rendering; + +namespace Helpdesk.Web.Models; + +/// Limity příloh – stejné jako v API (FR-11). +public static class AttachmentRules +{ + public const int MaxFiles = 5; + public const long MaxFileBytes = 10 * 1024 * 1024; + /// Celý požadavek: všechny soubory plus pole formuláře. + public const long MaxRequestBytes = MaxFiles * MaxFileBytes + 1024 * 1024; + + public static readonly IReadOnlyList Extensions = [".jpg", ".jpeg", ".png", ".heic", ".pdf", ".docx"]; + + /// Atribut accept pro výběr souborů. + public static string Accept => string.Join(",", Extensions); + + /// + /// Rychlá kontrola na webu, aby uživatel nečekal na nahrání 50 MB jen kvůli špatnému typu. + /// Skutečný obsah souboru (signaturu) ověřuje API. + /// + public static IEnumerable Validate(IReadOnlyCollection files) + { + if (files.Count > MaxFiles) + yield return $"Najednou můžete přiložit nejvýše {MaxFiles} souborů."; + + foreach (var file in files) + { + if (!Extensions.Contains(Path.GetExtension(file.FileName).ToLowerInvariant())) + yield return $"Soubor {file.FileName} nemá povolený typ. Povolené jsou JPG, PNG, HEIC, PDF a DOCX."; + else if (file.Length > MaxFileBytes) + yield return $"Soubor {file.FileName} je větší než 10 MB."; + else if (file.Length == 0) + yield return $"Soubor {file.FileName} je prázdný."; + } + } +} + +public sealed class NewIssueViewModel +{ + [Required(ErrorMessage = "Zadejte název.")] + [StringLength(200, ErrorMessage = "Název může mít nejvýše 200 znaků.")] + [Display(Name = "Co se stalo")] + public string Title { get; set; } = ""; + + [Required(ErrorMessage = "Popište závadu.")] + [StringLength(4000, ErrorMessage = "Popis může mít nejvýše 4000 znaků.")] + [Display(Name = "Popis")] + public string Description { get; set; } = ""; + + [Required(ErrorMessage = "Vyberte kategorii.")] + [Display(Name = "Kategorie")] + public int? CategoryId { get; set; } + + [Display(Name = "Budova")] + public int? BuildingId { get; set; } + + [StringLength(255, ErrorMessage = "Upřesnění místa může mít nejvýše 255 znaků.")] + [Display(Name = "Upřesnění místa")] + public string? LocationDetail { get; set; } + + [Display(Name = "Fotografie nebo soubory")] + public List Files { get; set; } = []; + + // Nabídky pro výběr – plní je kontroler z číselníků API. + public IReadOnlyList Categories { get; set; } = []; + public IReadOnlyList Buildings { get; set; } = []; + + public void SetCatalogs(IEnumerable categories, IEnumerable buildings) + { + Categories = categories.Select(c => new SelectListItem(c.Name, c.Id.ToString())).ToList(); + Buildings = buildings.Select(b => new SelectListItem(b.Name, b.Id.ToString())).ToList(); + } +} diff --git a/web/Helpdesk.Web/Views/Issues/Index.cshtml b/web/Helpdesk.Web/Views/Issues/Index.cshtml index 6f1849e..598e8ec 100644 --- a/web/Helpdesk.Web/Views/Issues/Index.cshtml +++ b/web/Helpdesk.Web/Views/Issues/Index.cshtml @@ -9,17 +9,20 @@

Moje hlášení

Závady, které jste nahlásili, a v jakém stavu je jejich řešení.

-
- - - -
+
+
+ + + +
+ Nahlásit závadu +
@if (result.Items.Count == 0) @@ -31,6 +34,10 @@ ? "Až nahlásíte závadu, uvidíte ji tady i s tím, jak se řeší." : "Zkuste vybrat jiný stav, nebo zobrazit všechna hlášení.")

+ @if (Model.Status is null) + { + Nahlásit závadu + } } else diff --git a/web/Helpdesk.Web/Views/Issues/New.cshtml b/web/Helpdesk.Web/Views/Issues/New.cshtml new file mode 100644 index 0000000..dbe10ec --- /dev/null +++ b/web/Helpdesk.Web/Views/Issues/New.cshtml @@ -0,0 +1,73 @@ +@model NewIssueViewModel +@{ + ViewData["Title"] = "Nahlásit závadu"; + var hadFiles = Model.Files.Count > 0 && !ViewData.ModelState.IsValid; +} + +
+

Nahlásit závadu

+

Popište, co nefunguje a kde. Vedení školy závadu přiřadí řešiteli a o průběhu vás budeme informovat.

+
+ +
+
+
+ +
+
+ + + +
+ +
+
+ + + +
+
+ + + +
+
+ +
+ + + +
+ +
+ + + +
+ +
+ + +
+ Nepovinné. Nejvýše @AttachmentRules.MaxFiles souborů po 10 MB – JPG, PNG, HEIC, PDF nebo DOCX. + @if (hadFiles) + { + Soubory prosím vyberte znovu. + } +
+ +
+ +
+ + Zrušit +
+
+
+
+