web: formulář nového hlášení závady s přílohami

Název, kategorie, budova, upřesnění místa, popis a až 5 příloh po 10 MB
(JPG, PNG, HEIC, PDF, DOCX). Přílohy jdou do API v jednom multipart
požadavku spolu s hlášením. Typ, velikost a počet souborů kontroluje už web,
obsah souboru ověřuje API. Tlačítko Nahlásit závadu v menu a v seznamu,
delší časový limit volání API kvůli nahrávání. Unit testy příloh, místa
v seznamu a odeslání formuláře.

Refs #23
This commit is contained in:
PatTheEvil committed 2026-12-02 17:34:58 +01:00
1 parent 2fe939ba5c
commit 946ff5ce12
9 files changed
+348 -12

No files matched your search

+98
View File
@@ -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<IssueSummary>([], 0, 1, 20),
CategoryNames = new Dictionary<int, string> { [2] = "Technické vybavení" },
BuildingNames = new Dictionary<int, string> { [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<HttpResponseMessage> 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"),
};
}
}
}
+9
View File
@@ -61,5 +61,14 @@ public sealed record IssueSummary(
int Id, string Title, int CategoryId, int? BuildingId, string? LocationDetail, string Status, int Id, string Title, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
string Priority, int ReporterId, int? AssigneeId, DateTimeOffset CreatedAt); string Priority, int ReporterId, int? AssigneeId, DateTimeOffset CreatedAt);
/// <summary>Nové hlášení. Přílohy jdou ve stejném požadavku (multipart, pole <c>files</c>).</summary>
public sealed record CreateIssueRequest(string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail);
/// <summary>Soubor přeposílaný z formuláře webu do API.</summary>
public sealed record UploadFile(string FileName, string ContentType, Func<Stream> OpenRead);
/// <summary>Detail závady (zatím jen pole, která web používá).</summary>
public sealed record IssueDetail(int Id, string Title, string Status, int RowVersion, IReadOnlyList<string> AllowedActions);
/// <summary>Filtry <c>GET /api/v1/issues</c>; prázdné hodnoty se do dotazu neposílají.</summary> /// <summary>Filtry <c>GET /api/v1/issues</c>; prázdné hodnoty se do dotazu neposílají.</summary>
public sealed record IssueListQuery(string? Status = null, bool Mine = false, string Sort = "newest", int Page = 1, int PageSize = 20); public sealed record IssueListQuery(string? Status = null, bool Mine = false, string Sort = "newest", int Page = 1, int PageSize = 20);
+2 -1
View File
@@ -7,5 +7,6 @@ public sealed class ApiOptions
public string BaseUrl { get; set; } = ""; public string BaseUrl { get; set; } = "";
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(15); /// <summary>Delší kvůli nahrávání příloh (až 5 × 10 MB) na pomalejším připojení.</summary>
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(100);
} }
+31
View File
@@ -1,4 +1,5 @@
using System.Globalization; using System.Globalization;
using System.Net.Http.Headers;
using System.Net.Http.Json; using System.Net.Http.Json;
using Microsoft.AspNetCore.WebUtilities; using Microsoft.AspNetCore.WebUtilities;
@@ -33,6 +34,36 @@ public sealed class HelpdeskApiClient(HttpClient http)
return await ApiResponse.ReadAsync<PagedResult<IssueSummary>>(response, ct); return await ApiResponse.ReadAsync<PagedResult<IssueSummary>>(response, ct);
} }
/// <summary>
/// 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.
/// </summary>
public async Task<IssueDetail> CreateIssueAsync(CreateIssueRequest request, IReadOnlyCollection<UploadFile> 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<IssueDetail>(response, ct);
}
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(CancellationToken ct) public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(CancellationToken ct)
{ {
using var response = await http.GetAsync("api/v1/issue-categories", ct); using var response = await http.GetAsync("api/v1/issue-categories", ct);
@@ -1,4 +1,6 @@
using System.Net;
using Helpdesk.Web.Api; using Helpdesk.Web.Api;
using Helpdesk.Web.Infrastructure;
using Helpdesk.Web.Models; using Helpdesk.Web.Models;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@@ -28,4 +30,42 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller
Status = status, Status = status,
}); });
} }
/// <summary>Formulář nového hlášení (T1 – závada vznikne ve stavu Přijata).</summary>
[HttpGet("new")]
public async Task<IActionResult> New(CancellationToken ct) => View(await WithCatalogsAsync(new NewIssueViewModel(), ct));
[HttpPost("new")]
[RequestSizeLimit(AttachmentRules.MaxRequestBytes)]
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentRules.MaxRequestBytes)]
public async Task<IActionResult> 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<NewIssueViewModel> WithCatalogsAsync(NewIssueViewModel model, CancellationToken ct)
{
model.SetCatalogs(await api.GetIssueCategoriesAsync(ct), await api.GetBuildingsAsync(ct));
return model;
}
} }
@@ -19,6 +19,7 @@ public static class Navigation
public static readonly IReadOnlyList<NavItem> Items = public static readonly IReadOnlyList<NavItem> Items =
[ [
new("Nástěnka", "Home", "Index"), new("Nástěnka", "Home", "Index"),
new("Nahlásit závadu", "Issues", "New"),
new("Moje hlášení", "Issues", "Index"), new("Moje hlášení", "Issues", "Index"),
]; ];
@@ -0,0 +1,76 @@
using System.ComponentModel.DataAnnotations;
using Helpdesk.Web.Api;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace Helpdesk.Web.Models;
/// <summary>Limity příloh – stejné jako v API (FR-11).</summary>
public static class AttachmentRules
{
public const int MaxFiles = 5;
public const long MaxFileBytes = 10 * 1024 * 1024;
/// <summary>Celý požadavek: všechny soubory plus pole formuláře.</summary>
public const long MaxRequestBytes = MaxFiles * MaxFileBytes + 1024 * 1024;
public static readonly IReadOnlyList<string> Extensions = [".jpg", ".jpeg", ".png", ".heic", ".pdf", ".docx"];
/// <summary>Atribut <c>accept</c> pro výběr souborů.</summary>
public static string Accept => string.Join(",", Extensions);
/// <summary>
/// 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.
/// </summary>
public static IEnumerable<string> Validate(IReadOnlyCollection<IFormFile> 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<IFormFile> Files { get; set; } = [];
// Nabídky pro výběr – plní je kontroler z číselníků API.
public IReadOnlyList<SelectListItem> Categories { get; set; } = [];
public IReadOnlyList<SelectListItem> Buildings { get; set; } = [];
public void SetCatalogs(IEnumerable<CategoryDto> categories, IEnumerable<BuildingDto> 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();
}
}
+18 -11
View File
@@ -9,17 +9,20 @@
<h1>Moje hlášení</h1> <h1>Moje hlášení</h1>
<p class="text-body-secondary mb-0">Závady, které jste nahlásili, a v jakém stavu je jejich řešení.</p> <p class="text-body-secondary mb-0">Závady, které jste nahlásili, a v jakém stavu je jejich řešení.</p>
</div> </div>
<form method="get" asp-action="Index" class="d-flex gap-2 align-items-center"> <div class="d-flex flex-wrap gap-2 align-items-center">
<label for="status" class="form-label mb-0 text-nowrap">Stav</label> <form method="get" asp-action="Index" class="d-flex gap-2 align-items-center">
<select id="status" name="status" class="form-select" data-autosubmit> <label for="status" class="form-label mb-0 text-nowrap">Stav</label>
<option value="">Všechny</option> <select id="status" name="status" class="form-select" data-autosubmit>
@foreach (var status in IssueListViewModel.Statuses) <option value="">Všechny</option>
{ @foreach (var status in IssueListViewModel.Statuses)
<option value="@status" selected="@(status == Model.Status)">@StatusLabels.For(status)</option> {
} <option value="@status" selected="@(status == Model.Status)">@StatusLabels.For(status)</option>
</select> }
<noscript><button type="submit" class="btn btn-outline-primary">Filtrovat</button></noscript> </select>
</form> <noscript><button type="submit" class="btn btn-outline-primary">Filtrovat</button></noscript>
</form>
<a asp-action="New" class="btn btn-primary text-nowrap">Nahlásit závadu</a>
</div>
</section> </section>
@if (result.Items.Count == 0) @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ší." ? "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í.") : "Zkuste vybrat jiný stav, nebo zobrazit všechna hlášení.")
</p> </p>
@if (Model.Status is null)
{
<a asp-action="New" class="btn btn-primary mt-3">Nahlásit závadu</a>
}
</div> </div>
} }
else else
+73
View File
@@ -0,0 +1,73 @@
@model NewIssueViewModel
@{
ViewData["Title"] = "Nahlásit závadu";
var hadFiles = Model.Files.Count > 0 && !ViewData.ModelState.IsValid;
}
<section class="app-page-head">
<h1>Nahlásit závadu</h1>
<p class="lead text-body-secondary">Popište, co nefunguje a kde. Vedení školy závadu přiřadí řešiteli a o průběhu vás budeme informovat.</p>
</section>
<div class="row">
<div class="col-lg-8">
<div class="app-card">
<partial name="_FormErrors" />
<form method="post" asp-action="New" enctype="multipart/form-data" novalidate>
<div class="mb-3">
<label asp-for="Title" class="form-label"></label>
<input asp-for="Title" class="form-control" placeholder="Např. Nefunkční projektor v učebně" autofocus />
<span asp-validation-for="Title" class="invalid-feedback d-block"></span>
</div>
<div class="row g-3 mb-3">
<div class="col-md-6">
<label asp-for="CategoryId" class="form-label"></label>
<select asp-for="CategoryId" asp-items="Model.Categories" class="form-select">
<option value="">Vyberte kategorii</option>
</select>
<span asp-validation-for="CategoryId" class="invalid-feedback d-block"></span>
</div>
<div class="col-md-6">
<label asp-for="BuildingId" class="form-label"></label>
<select asp-for="BuildingId" asp-items="Model.Buildings" class="form-select">
<option value="">Netýká se budovy</option>
</select>
<span asp-validation-for="BuildingId" class="invalid-feedback d-block"></span>
</div>
</div>
<div class="mb-3">
<label asp-for="LocationDetail" class="form-label"></label>
<input asp-for="LocationDetail" class="form-control" placeholder="Např. učebna B-205, 2. patro" />
<span asp-validation-for="LocationDetail" class="invalid-feedback d-block"></span>
</div>
<div class="mb-3">
<label asp-for="Description" class="form-label"></label>
<textarea asp-for="Description" class="form-control" rows="5"
placeholder="Co přesně nefunguje, od kdy a co jste už zkoušeli."></textarea>
<span asp-validation-for="Description" class="invalid-feedback d-block"></span>
</div>
<div class="mb-4">
<label asp-for="Files" class="form-label"></label>
<input asp-for="Files" type="file" class="form-control" multiple accept="@AttachmentRules.Accept" aria-describedby="filesHelp" />
<div id="filesHelp" class="form-text">
Nepovinné. Nejvýše @AttachmentRules.MaxFiles souborů po 10 MB – JPG, PNG, HEIC, PDF nebo DOCX.
@if (hadFiles)
{
<strong>Soubory prosím vyberte znovu.</strong>
}
</div>
<span asp-validation-for="Files" class="invalid-feedback d-block"></span>
</div>
<div class="d-flex flex-wrap gap-2">
<button type="submit" class="btn btn-primary">Odeslat hlášení</button>
<a asp-action="Index" class="btn btn-outline-primary">Zrušit</a>
</div>
</form>
</div>
</div>
</div>