Compare commits

..
2 Commits
Author SHA1 Message Date
PatTheEvil 5d8b71c435 web: verze API na jednom místě a číslo verze v patičce 2026-12-02 18:54:15 +01:00
PatTheEvil 946ff5ce12 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
2026-12-02 17:34:58 +01:00
17 changed files with 448 additions and 28 deletions

No files matched your search

+5
View File
@@ -68,6 +68,11 @@ dotnet test --solution web/Helpdesk.Web.sln
Schéma se mění výhradně novými číslovanými skripty `db/migrations/V{NNN}__{popis}.sql`. Provedený skript se nikdy neupravuje. Migrace spouští DbUp (`Helpdesk.Migrator`) před startem API a eviduje je v tabulce `schema_version`.
## Verzování webové aplikace
- **Verze API:** web volá REST API `/api/v1`. Verze je na jednom místě, `ApiOptions.ApiVersion` v `web/Helpdesk.Web/Api/ApiOptions.cs`. Klienti API používají jen relativní cesty (`issues`, `auth/login`), takže přechod na `/api/v2` znamená změnit tuto konstantu a upravit DTO, která se ve v2 změnila.
- **Verze webu:** `<Version>` v `web/Helpdesk.Web/Helpdesk.Web.csproj` podle semver – před vydáním 1.0 zvyšujeme MINOR za novou část aplikace (závady, návrhy, …) a PATCH za opravy. Verze se zobrazuje v patičce webu spolu s krátkým hashem commitu, ze kterého byl web sestaven.
## Technologie
Backend C# / ASP.NET Core Web API · EF Core + Pomelo (MariaDB) · DbUp · JWT (RFC 7519) · Swagger · Web ASP.NET Core MVC · Mobil Kotlin + Jetpack Compose · Docker
+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 ApiOptions { BaseUrl = "http://api/" }.VersionedBaseAddress() });
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"),
};
}
}
}
+31
View File
@@ -0,0 +1,31 @@
using Helpdesk.Web.Api;
using Helpdesk.Web.Infrastructure;
namespace Helpdesk.Web.Tests;
public class ApiVersioningTests
{
[Theory]
[InlineData("http://api:8080/")]
[InlineData("http://api:8080")]
public void Zaklad_adresy_obsahuje_verzi_API(string baseUrl) =>
Assert.Equal("http://api:8080/api/v1/", new ApiOptions { BaseUrl = baseUrl }.VersionedBaseAddress().ToString());
[Fact]
public void Relativni_cesta_se_slozi_pod_verzi()
{
var baseAddress = new ApiOptions { BaseUrl = "http://api:8080/" }.VersionedBaseAddress();
Assert.Equal("/api/v1/auth/login", new Uri(baseAddress, "auth/login").AbsolutePath);
}
}
public class AppVersionTests
{
[Theory]
[InlineData("0.2.0+6e742b4029cca8896173c0d64783b7fb7540f214", "0.2.0 (6e742b4)")]
[InlineData("0.2.0", "0.2.0")]
[InlineData(null, "neznámá")]
public void Verze_se_zobrazi_s_kratkym_hashem_commitu(string? informational, string expected) =>
Assert.Equal(expected, AppVersion.Format(informational));
}
+9
View File
@@ -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);
/// <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>
public sealed record IssueListQuery(string? Status = null, bool Mine = false, string Sort = "newest", int Page = 1, int PageSize = 20);
+15 -1
View File
@@ -5,7 +5,21 @@ public sealed class ApiOptions
{
public const string Section = "Api";
/// <summary>
/// Hlavní verze REST API, proti které je web napsaný (kap. 11 návrhu). Je jen tady:
/// klienti API používají relativní cesty (<c>issues</c>, <c>auth/login</c>) a verze je
/// součástí <see cref="HttpClient.BaseAddress"/>. Přechod na <c>v2</c> = změna této
/// konstanty a DTO, která se ve v2 změnila. Záměrně to není konfigurace – web je
/// napsaný proti konkrétní verzi a s jinou by nefungoval.
/// </summary>
public const string ApiVersion = "v1";
/// <summary>Adresa backendu bez cesty API, např. <c>http://api:8080/</c>.</summary>
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);
/// <summary>Základ pro všechna volání: <c>{BaseUrl}/api/v1/</c> (koncové lomítko je nutné pro relativní cesty).</summary>
public Uri VersionedBaseAddress() => new(new Uri(BaseUrl.EndsWith('/') ? BaseUrl : BaseUrl + "/"), $"api/{ApiVersion}/");
}
+7 -7
View File
@@ -4,47 +4,47 @@ using System.Net.Http.Json;
namespace Helpdesk.Web.Api;
/// <summary>
/// Anonymní endpointy <c>/api/v1/auth</c>. Záměrně bez <see cref="BearerTokenHandler"/>:
/// Anonymní endpointy <c>auth/*</c>. Záměrně bez <see cref="BearerTokenHandler"/>:
/// obnova tokenu běží uvnitř ověřování cookie a čtení tokenu z cookie by se zacyklilo.
/// </summary>
public sealed class AuthApiClient(HttpClient http)
{
public async Task<AuthResponse> LoginAsync(LoginRequest request, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("api/v1/auth/login", request, ct);
using var response = await http.PostAsJsonAsync("auth/login", request, ct);
return await ApiResponse.ReadAsync<AuthResponse>(response, ct);
}
/// <summary>Registrace. Roli (student / vyučující) určí API podle domény e-mailu.</summary>
public async Task<UserDto> RegisterAsync(RegisterRequest request, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("api/v1/auth/register", request, ct);
using var response = await http.PostAsJsonAsync("auth/register", request, ct);
return await ApiResponse.ReadAsync<UserDto>(response, ct);
}
public async Task ConfirmEmailAsync(string token, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("api/v1/auth/confirm-email", new EmailTokenRequest(token), ct);
using var response = await http.PostAsJsonAsync("auth/confirm-email", new EmailTokenRequest(token), ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
/// <summary>API odpoví stejně, ať účet existuje, nebo ne – stránka tak neprozradí registrované e-maily.</summary>
public async Task ForgotPasswordAsync(string email, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("api/v1/auth/forgot-password", new ForgotPasswordRequest(email), ct);
using var response = await http.PostAsJsonAsync("auth/forgot-password", new ForgotPasswordRequest(email), ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("api/v1/auth/reset-password", request, ct);
using var response = await http.PostAsJsonAsync("auth/reset-password", request, ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
/// <summary>Obnoví pár tokenů. Neplatný nebo už použitý refresh token → <c>null</c>.</summary>
public async Task<TokenSet?> RefreshAsync(string refreshToken, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("api/v1/auth/refresh", new RefreshTokenRequest(refreshToken), ct);
using var response = await http.PostAsJsonAsync("auth/refresh", new RefreshTokenRequest(refreshToken), ct);
if (response.StatusCode == HttpStatusCode.Unauthorized)
return null;
return (await ApiResponse.ReadAsync<AuthResponse>(response, ct)).Tokens;
+38 -7
View File
@@ -1,4 +1,5 @@
using System.Globalization;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using Microsoft.AspNetCore.WebUtilities;
@@ -9,13 +10,13 @@ public sealed class HelpdeskApiClient(HttpClient http)
{
public async Task<UserDto> GetMeAsync(CancellationToken ct)
{
using var response = await http.GetAsync("api/v1/users/me", ct);
using var response = await http.GetAsync("users/me", ct);
return await ApiResponse.ReadAsync<UserDto>(response, ct);
}
public async Task<UserDto> UpdateMeAsync(UpdateProfileRequest request, CancellationToken ct)
{
using var response = await http.PutAsJsonAsync("api/v1/users/me", request, ct);
using var response = await http.PutAsJsonAsync("users/me", request, ct);
return await ApiResponse.ReadAsync<UserDto>(response, ct);
}
@@ -29,33 +30,63 @@ public sealed class HelpdeskApiClient(HttpClient http)
["page"] = query.Page.ToString(CultureInfo.InvariantCulture),
["pageSize"] = query.PageSize.ToString(CultureInfo.InvariantCulture),
};
using var response = await http.GetAsync(QueryHelpers.AddQueryString("api/v1/issues", parameters.Where(p => !string.IsNullOrEmpty(p.Value))), ct);
using var response = await http.GetAsync(QueryHelpers.AddQueryString("issues", parameters.Where(p => !string.IsNullOrEmpty(p.Value))), 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("issues", content, ct);
return await ApiResponse.ReadAsync<IssueDetail>(response, 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("issue-categories", ct);
return await ApiResponse.ReadAsync<List<CategoryDto>>(response, ct);
}
public async Task<IReadOnlyList<BuildingDto>> GetBuildingsAsync(CancellationToken ct)
{
using var response = await http.GetAsync("api/v1/buildings", ct);
using var response = await http.GetAsync("buildings", ct);
return await ApiResponse.ReadAsync<List<BuildingDto>>(response, ct);
}
/// <summary>Odhlásí ze všech zařízení – API zneplatní všechny tokeny uživatele.</summary>
public async Task LogoutAllAsync(CancellationToken ct)
{
using var response = await http.PostAsync("api/v1/auth/logout-all", content: null, ct);
using var response = await http.PostAsync("auth/logout-all", content: null, ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
/// <summary>Odhlásí toto zařízení – API zneplatní aktuální access token i předaný refresh token.</summary>
public async Task LogoutAsync(string refreshToken, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync("api/v1/auth/logout", new RefreshTokenRequest(refreshToken), ct);
using var response = await http.PostAsJsonAsync("auth/logout", new RefreshTokenRequest(refreshToken), ct);
await ApiResponse.EnsureSuccessAsync(response, ct);
}
}
@@ -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,
});
}
/// <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;
}
}
+9
View File
@@ -1,5 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<!--
Verze webové aplikace (semver, před vydáním 1.0 jako 0.x):
MINOR = nová část aplikace (závady, návrhy, …), PATCH = opravy.
Zobrazuje se v patičce; při sestavení z Gitu se k ní přidá krátký hash commitu.
-->
<Version>0.2.0</Version>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="Helpdesk.Web.Tests" />
</ItemGroup>
@@ -0,0 +1,24 @@
using System.Reflection;
namespace Helpdesk.Web.Infrastructure;
/// <summary>
/// Verze běžící webové aplikace z <c>&lt;Version&gt;</c> v projektu. SDK k ní při sestavení
/// v Gitu přidá hash commitu (<c>0.2.0+6e742b4…</c>); zobrazujeme jeho prvních 7 znaků,
/// aby při ladění bylo jasné, který commit běží.
/// </summary>
public static class AppVersion
{
public static string Display { get; } = Format(
typeof(AppVersion).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion);
internal static string Format(string? informationalVersion)
{
if (string.IsNullOrWhiteSpace(informationalVersion))
return "neznámá";
var parts = informationalVersion.Split('+', 2);
var commit = parts.Length == 2 ? parts[1].Split('.')[0] : null;
return string.IsNullOrEmpty(commit) ? parts[0] : $"{parts[0]} ({commit[..Math.Min(7, commit.Length)]})";
}
}
@@ -19,6 +19,7 @@ public static class Navigation
public static readonly IReadOnlyList<NavItem> Items =
[
new("Nástěnka", "Home", "Index"),
new("Nahlásit závadu", "Issues", "New"),
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();
}
}
+1 -1
View File
@@ -31,7 +31,7 @@ builder.Services.AddOptions<ApiOptions>()
static void ConfigureApiClient(IServiceProvider services, HttpClient http)
{
var options = services.GetRequiredService<IOptions<ApiOptions>>().Value;
http.BaseAddress = new Uri(options.BaseUrl.EndsWith('/') ? options.BaseUrl : options.BaseUrl + "/");
http.BaseAddress = options.VersionedBaseAddress();
http.Timeout = options.Timeout;
}
+18 -11
View File
@@ -9,17 +9,20 @@
<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>
</div>
<form method="get" asp-action="Index" class="d-flex gap-2 align-items-center">
<label for="status" class="form-label mb-0 text-nowrap">Stav</label>
<select id="status" name="status" class="form-select" data-autosubmit>
<option value="">Všechny</option>
@foreach (var status in IssueListViewModel.Statuses)
{
<option value="@status" selected="@(status == Model.Status)">@StatusLabels.For(status)</option>
}
</select>
<noscript><button type="submit" class="btn btn-outline-primary">Filtrovat</button></noscript>
</form>
<div class="d-flex flex-wrap gap-2 align-items-center">
<form method="get" asp-action="Index" class="d-flex gap-2 align-items-center">
<label for="status" class="form-label mb-0 text-nowrap">Stav</label>
<select id="status" name="status" class="form-select" data-autosubmit>
<option value="">Všechny</option>
@foreach (var status in IssueListViewModel.Statuses)
{
<option value="@status" selected="@(status == Model.Status)">@StatusLabels.For(status)</option>
}
</select>
<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>
@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í.")
</p>
@if (Model.Status is null)
{
<a asp-action="New" class="btn btn-primary mt-3">Nahlásit závadu</a>
}
</div>
}
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>
@@ -51,6 +51,7 @@
<footer class="app-footer container-xl">
Univerzitní helpdesk a portál návrhů na zlepšení · NNPRO
<span class="app-footer-version">verze @AppVersion.Display</span>
</footer>
<script src="~/lib/bootstrap/js/bootstrap.bundle.min.js"></script>
+2 -1
View File
@@ -105,7 +105,8 @@ body { min-height: 100vh; display: flex; flex-direction: column; }
.app-empty { max-width: 32rem; margin: 3rem auto; text-align: center; }
.app-empty-code { font-size: 3rem; font-weight: 700; color: var(--app-accent); margin-bottom: 0; font-variant-numeric: tabular-nums; }
.app-footer { padding-block: 1.25rem; color: var(--app-muted); font-size: .875rem; border-top: 1px solid var(--app-line); }
.app-footer { display: flex; flex-wrap: wrap; justify-content: space-between; gap: .25rem 1rem; padding-block: 1.25rem; color: var(--app-muted); font-size: .875rem; border-top: 1px solid var(--app-line); }
.app-footer-version { font-variant-numeric: tabular-nums; }
/* seznam závad – karta jako IssueCard v mobilu */
.app-issue-list { list-style: none; padding: 0; margin: 0; display: grid; gap: .75rem; }