web: detail závady s průběhem řešení, komentáři, přílohami a akcemi

This commit is contained in:
PatTheEvil committed 2026-12-03 00:14:53 +01:00
1 parent 5d8b71c435
commit ac3ec6aff7
14 files changed
+1006 -56

No files matched your search

+174
View File
@@ -0,0 +1,174 @@
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json.Nodes;
using Helpdesk.Web.Api;
using Helpdesk.Web.Models;
namespace Helpdesk.Web.Tests;
public class IssueDetailViewModelTests
{
private static readonly DateTimeOffset T = DateTimeOffset.UnixEpoch;
private static IssueEventDto Event(string type, string? from, string to, string actor, string? note = null) =>
new(1, type, from, to, 1, actor, note, T);
private static IssueDetailViewModel Model(int? assigneeId, params IssueEventDto[] events) => new()
{
Issue = new IssueDetail(42, "Projektor", "Bliká.", 2, null, null, "IN_PROGRESS", "HIGH", 5, assigneeId, T, 3,
[IssueActions.SubmitForVerification, IssueActions.Reject, IssueActions.Comment], []),
Events = events,
CategoryName = "Technické vybavení",
};
[Fact]
public void Jmena_hlasice_a_resitele_vezme_z_casove_osy()
{
var model = Model(7,
Event("CREATED", null, "RECEIVED", "Jan Novák"),
Event("ASSIGNED", "RECEIVED", "ASSIGNED", "Vedení Školy", "Petr Svoboda"),
Event("ASSIGNED", "ASSIGNED", "ASSIGNED", "Vedení Školy", "Eva Malá"));
Assert.Equal("Jan Novák", model.ReporterName);
Assert.Equal("Eva Malá", model.AssigneeName); // po přeřazení platí poslední přiřazení
}
[Fact]
public void Nepriprazena_zavada_nema_resitele() => Assert.Null(Model(null, Event("CREATED", null, "RECEIVED", "Jan")).AssigneeName);
[Fact]
public void Akce_zmeny_stavu_jsou_jen_povolene_a_v_poradi_zivotniho_cyklu() =>
Assert.Equal([IssueActions.SubmitForVerification, IssueActions.Reject], Model(7).Transitions);
[Theory]
[InlineData("CREATED", null, "RECEIVED", null, "nahlásil/a závadu", null)]
[InlineData("ASSIGNED", "RECEIVED", "ASSIGNED", "Petr Svoboda", "přiřadil/a závadu řešiteli Petr Svoboda", null)]
[InlineData("ASSIGNED", "IN_PROGRESS", "ASSIGNED", "Eva Malá", "přeřadil/a závadu na Eva Malá", null)]
[InlineData("STATUS_CHANGED", "ASSIGNED", "IN_PROGRESS", null, "zahájil/a řešení", null)]
[InlineData("STATUS_CHANGED", "PENDING_VERIFICATION", "IN_PROGRESS", "Pořád bliká", "znovu otevřel/a závadu", "Důvod")]
[InlineData("STATUS_CHANGED", "IN_PROGRESS", "PENDING_VERIFICATION", "Vyměněna lampa", "předal/a závadu k ověření", "Poznámka")]
[InlineData("STATUS_CHANGED", "IN_PROGRESS", "REJECTED", "Duplicitní hlášení", "zamítl/a závadu", "Důvod")]
[InlineData("COMMENTED", null, "IN_PROGRESS", "Funguje HDMI?", "napsal/a komentář", null)]
public void Udalost_casove_osy_ma_srozumitelny_popis(string type, string? from, string to, string? note, string text, string? noteLabel)
{
var entry = TimelineEntry.From(Event(type, from, to, "Někdo", note));
Assert.Equal(text, entry.Text);
Assert.Equal(noteLabel, entry.NoteLabel);
}
[Fact]
public void Komentar_nema_stitek_stavu()
{
var entry = TimelineEntry.From(Event("COMMENTED", null, "IN_PROGRESS", "Jan", "Funguje HDMI?"));
Assert.True(entry.IsComment);
Assert.Null(entry.Status);
Assert.Equal("Funguje HDMI?", entry.Note);
}
[Theory]
[InlineData(900, "900 B")]
[InlineData(300_000, "293 kB")]
[InlineData(2_500_000, "2,4 MB")]
public void Velikost_prilohy_je_citelna(long bytes, string expected) =>
Assert.Equal(expected, IssueDetailViewModel.FileSize(bytes).Replace('.', ','));
}
public class IssueActionsApiTests
{
[Theory]
[InlineData(IssueActions.StartWork, null, "/api/v1/issues/42/start", """{"rowVersion":3}""")]
[InlineData(IssueActions.SubmitForVerification, "Hotovo", "/api/v1/issues/42/submit-for-verification", """{"rowVersion":3,"note":"Hotovo"}""")]
[InlineData(IssueActions.Confirm, null, "/api/v1/issues/42/confirm", """{"rowVersion":3}""")]
[InlineData(IssueActions.Reopen, "Bliká dál", "/api/v1/issues/42/reopen", """{"rowVersion":3,"reason":"Bliká dál"}""")]
[InlineData(IssueActions.Reject, "Duplicita", "/api/v1/issues/42/reject", """{"rowVersion":3,"reason":"Duplicita"}""")]
public async Task Zmena_stavu_jde_na_akcni_endpoint_s_rowVersion(string action, string? text, string path, string body)
{
var handler = new RecordingHandler(DetailJson);
await Client(handler).TransitionIssueAsync(42, action, 3, text, CancellationToken.None);
Assert.Equal(HttpMethod.Post, handler.Method);
Assert.Equal(path, handler.Path);
Assert.True(JsonNode.DeepEquals(JsonNode.Parse(body), JsonNode.Parse(handler.Body!)), handler.Body);
}
[Fact]
public async Task Neznama_akce_se_do_API_neposle() =>
await Assert.ThrowsAsync<ArgumentException>(() =>
Client(new RecordingHandler(DetailJson)).TransitionIssueAsync(42, "DELETE", 3, null, CancellationToken.None));
[Fact]
public async Task Prirazeni_posle_resitele_prioritu_a_verzi()
{
var handler = new RecordingHandler(DetailJson);
await Client(handler).AssignIssueAsync(42, new AssignIssueRequest(7, "HIGH", 3), CancellationToken.None);
Assert.Equal("/api/v1/issues/42/assign", handler.Path);
Assert.Equal("""{"assigneeId":7,"priority":"HIGH","rowVersion":3}""", handler.Body);
}
[Fact]
public async Task Detail_nacte_akce_i_prilohy()
{
var issue = await Client(new RecordingHandler(DetailJson)).GetIssueAsync(42, CancellationToken.None);
Assert.True(issue.Can(IssueActions.Comment));
Assert.False(issue.Can(IssueActions.Assign));
Assert.Equal("foto.jpg", Assert.Single(issue.Attachments).FileName);
}
[Fact]
public async Task Priloha_si_zachova_cesky_nazev_souboru()
{
var handler = new RecordingHandler("", response =>
{
response.Content = new ByteArrayContent([0xFF, 0xD8, 0xFF]);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileNameStar = "učebna B-205.jpg" };
});
using var file = await Client(handler).DownloadAttachmentAsync(9, CancellationToken.None);
Assert.Equal("/api/v1/attachments/9", handler.Path);
Assert.Equal("učebna B-205.jpg", file.FileName);
Assert.Equal("image/jpeg", file.ContentType);
}
[Fact]
public void Chyby_poli_z_API_se_spoji_do_jedne_zpravy()
{
var ex = new ApiException(HttpStatusCode.BadRequest, "One or more validation errors occurred.",
new Dictionary<string, string[]> { ["reason"] = ["Důvod je povinný."], ["rowVersion"] = ["Chybí verze."] });
Assert.Equal("Důvod je povinný. Chybí verze.", ex.AllMessages);
}
private const string DetailJson = """
{"id":42,"title":"Projektor","description":"Bliká.","categoryId":2,"buildingId":null,"locationDetail":null,
"status":"IN_PROGRESS","priority":"NORMAL","reporterId":5,"assigneeId":7,"createdAt":"2026-10-03T08:00:00Z",
"rowVersion":4,"allowedActions":["COMMENT","ADD_ATTACHMENTS"],
"attachments":[{"id":9,"fileName":"foto.jpg","contentType":"image/jpeg","sizeBytes":3,"createdAt":"2026-10-03T08:00:00Z"}]}
""";
private static HelpdeskApiClient Client(HttpMessageHandler handler) =>
new(new HttpClient(handler) { BaseAddress = new ApiOptions { BaseUrl = "http://api/" }.VersionedBaseAddress() });
private sealed class RecordingHandler(string json, Action<HttpResponseMessage>? customize = null) : HttpMessageHandler
{
public HttpMethod? Method { get; private set; }
public string? Path { get; private set; }
public string? Body { get; private set; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
Method = request.Method;
Path = request.RequestUri!.AbsolutePath;
Body = request.Content is null ? null : await request.Content.ReadAsStringAsync(ct);
var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
customize?.Invoke(response);
return response;
}
}
}
+5
View File
@@ -25,6 +25,11 @@ public sealed class ApiException(HttpStatusCode statusCode, string? title, IRead
_ => "Požadavek se nepodařilo zpracovat. Zkuste to prosím znovu.", _ => "Požadavek se nepodařilo zpracovat. Zkuste to prosím znovu.",
}; };
/// <summary>Chyby polí, pokud je API poslalo, jinak <see cref="UserMessage"/> – pro zprávu mimo formulář.</summary>
public string AllMessages => Errors.Count == 0
? UserMessage
: string.Join(" ", Errors.Values.SelectMany(messages => messages).Distinct());
public static async Task<ApiException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct) public static async Task<ApiException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
{ {
string? title = null; string? title = null;
+99 -2
View File
@@ -67,8 +67,105 @@ public sealed record CreateIssueRequest(string Title, string Description, int Ca
/// <summary>Soubor přeposílaný z formuláře webu do API.</summary> /// <summary>Soubor přeposílaný z formuláře webu do API.</summary>
public sealed record UploadFile(string FileName, string ContentType, Func<Stream> OpenRead); public sealed record UploadFile(string FileName, string ContentType, Func<Stream> OpenRead);
/// <summary>Detail závady (zatím jen pole, která web používá).</summary> /// <summary>
public sealed record IssueDetail(int Id, string Title, string Status, int RowVersion, IReadOnlyList<string> AllowedActions); /// Detail závady. <c>AllowedActions</c> říká, co smí aktuální uživatel udělat (kódy z <see cref="IssueActions"/>),
/// <c>RowVersion</c> se posílá zpět s každou úpravou a změnou stavu (optimistické zamykání, jinak 409).
/// </summary>
public sealed record IssueDetail(
int Id, string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail, string Status,
string Priority, int ReporterId, int? AssigneeId, DateTimeOffset CreatedAt, int RowVersion,
IReadOnlyList<string> AllowedActions, IReadOnlyList<AttachmentDto> Attachments)
{
public bool Can(string action) => AllowedActions?.Contains(action) == true;
}
public sealed record AttachmentDto(int Id, string FileName, string ContentType, long SizeBytes, DateTimeOffset CreatedAt);
/// <summary>Událost na časové ose závady – vytvoření, přiřazení, změna stavu i komentář (FR-17).</summary>
public sealed record IssueEventDto(
int Id, string EventType, string? FromStatus, string ToStatus, int ActorId, string ActorName, string? Note,
DateTimeOffset OccurredAt);
/// <summary>Možný řešitel (jen pro vedení) s počtem jeho otevřených závad (FR-13).</summary>
public sealed record AssignableUserDto(int Id, string FirstName, string LastName, string Role, int OpenIssues)
{
public string FullName => $"{FirstName} {LastName}";
}
public sealed record EditIssueRequest(
string Title, string Description, int CategoryId, int? BuildingId, string? LocationDetail, int RowVersion);
public sealed record AssignIssueRequest(int AssigneeId, string? Priority, int RowVersion);
public sealed record CommentRequest(string Text);
/// <summary>Stažená příloha. Proud čte přímo odpověď API a uvolní se spolu s ní.</summary>
public sealed class ApiFile(Stream content, string contentType, string fileName, IDisposable response) : IDisposable
{
public Stream Content { get; } = content;
public string ContentType { get; } = contentType;
public string FileName { get; } = fileName;
public void Dispose() => response.Dispose();
}
/// <summary>Kódy akcí z <c>allowedActions</c> v detailu závady.</summary>
public static class IssueActions
{
public const string Edit = "EDIT";
public const string Assign = "ASSIGN";
public const string StartWork = "START_WORK";
public const string SubmitForVerification = "SUBMIT_FOR_VERIFICATION";
public const string Confirm = "CONFIRM";
public const string Reopen = "REOPEN";
public const string Reject = "REJECT";
public const string Comment = "COMMENT";
public const string AddAttachments = "ADD_ATTACHMENTS";
/// <summary>Změny stavu v pořadí, v jakém je web nabízí (T4 – T9).</summary>
public static readonly IReadOnlyList<string> Transitions = [StartWork, SubmitForVerification, Confirm, Reopen, Reject];
/// <summary>Akční endpoint <c>POST /issues/{id}/…</c> pro změnu stavu.</summary>
public static string? TransitionPath(string? action) => action switch
{
StartWork => "start",
SubmitForVerification => "submit-for-verification",
Confirm => "confirm",
Reopen => "reopen",
Reject => "reject",
_ => null,
};
/// <summary>Zamítnutí a znovuotevření vyžadují důvod (T7 – T9).</summary>
public static bool RequiresReason(string action) => action is Reopen or Reject;
/// <summary>Předání k ověření má nepovinnou poznámku (T5).</summary>
public static bool AcceptsText(string action) => action is SubmitForVerification || RequiresReason(action);
/// <summary>Texty tlačítek – stejné jako v mobilní aplikaci.</summary>
public static string Label(string action) => action switch
{
StartWork => "Zahájit řešení",
SubmitForVerification => "Předat k ověření",
Confirm => "Potvrdit vyřešení",
Reopen => "Znovu otevřít závadu",
Reject => "Zamítnout závadu",
_ => action,
};
}
/// <summary>Priorita závady; názvy jako v mobilní aplikaci.</summary>
public static class IssuePriorities
{
public static readonly IReadOnlyList<string> All = ["LOW", "NORMAL", "HIGH"];
public static string Label(string? priority) => priority switch
{
"LOW" => "Nízká",
"HIGH" => "Vysoká",
_ => "Běžná",
};
}
/// <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);
+105 -3
View File
@@ -51,6 +51,111 @@ public sealed class HelpdeskApiClient(HttpClient http)
if (!string.IsNullOrWhiteSpace(request.LocationDetail)) if (!string.IsNullOrWhiteSpace(request.LocationDetail))
content.Add(new StringContent(request.LocationDetail), "locationDetail"); content.Add(new StringContent(request.LocationDetail), "locationDetail");
AddFiles(content, files);
using var response = await http.PostAsync("issues", content, ct);
return await ApiResponse.ReadAsync<IssueDetail>(response, ct);
}
/// <summary>Detail včetně <c>allowedActions</c> a aktuální <c>rowVersion</c>.</summary>
public async Task<IssueDetail> GetIssueAsync(int id, CancellationToken ct)
{
using var response = await http.GetAsync(IssuePath(id), ct);
return await ApiResponse.ReadAsync<IssueDetail>(response, ct);
}
/// <summary>Časová osa – změny stavu i komentáře od nejstarších.</summary>
public async Task<IReadOnlyList<IssueEventDto>> GetIssueEventsAsync(int id, CancellationToken ct)
{
using var response = await http.GetAsync(IssuePath(id, "events"), ct);
return await ApiResponse.ReadAsync<List<IssueEventDto>>(response, ct);
}
/// <summary>Úprava hlášení hlásičem, dokud je ve stavu Přijata.</summary>
public async Task<IssueDetail> EditIssueAsync(int id, EditIssueRequest request, CancellationToken ct)
{
using var response = await http.PutAsJsonAsync(IssuePath(id), request, ct);
return await ApiResponse.ReadAsync<IssueDetail>(response, ct);
}
/// <summary>Přiřazení nebo přeřazení řešiteli (T2, T3), jen vedení.</summary>
public async Task<IssueDetail> AssignIssueAsync(int id, AssignIssueRequest request, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync(IssuePath(id, "assign"), request, ct);
return await ApiResponse.ReadAsync<IssueDetail>(response, ct);
}
/// <summary>
/// Změna stavu přes akční endpoint (T4 – T9). <paramref name="text"/> je důvod u zamítnutí
/// a znovuotevření, nebo nepovinná poznámka u předání k ověření.
/// </summary>
public async Task<IssueDetail> TransitionIssueAsync(int id, string action, int rowVersion, string? text, CancellationToken ct)
{
var path = IssueActions.TransitionPath(action) ?? throw new ArgumentException($"Neznámá akce {action}.", nameof(action));
object body = action switch
{
IssueActions.SubmitForVerification => new { rowVersion, note = text },
IssueActions.Reopen or IssueActions.Reject => new { rowVersion, reason = text },
_ => new { rowVersion },
};
using var response = await http.PostAsJsonAsync(IssuePath(id, path), body, ct);
return await ApiResponse.ReadAsync<IssueDetail>(response, ct);
}
public async Task<IssueEventDto> AddCommentAsync(int id, string text, CancellationToken ct)
{
using var response = await http.PostAsJsonAsync(IssuePath(id, "comments"), new CommentRequest(text), ct);
return await ApiResponse.ReadAsync<IssueEventDto>(response, ct);
}
/// <summary>Doplnění příloh k existující závadě (FR-11), 1–5 souborů.</summary>
public async Task<IReadOnlyList<AttachmentDto>> AddAttachmentsAsync(int id, IReadOnlyCollection<UploadFile> files, CancellationToken ct)
{
using var content = new MultipartFormDataContent();
AddFiles(content, files);
using var response = await http.PostAsync(IssuePath(id, "attachments"), content, ct);
return await ApiResponse.ReadAsync<List<AttachmentDto>>(response, ct);
}
/// <summary>
/// Stažení přílohy. Odpověď se nečte do paměti – web ji jako proud předá prohlížeči
/// a po odeslání ji uvolní (<see cref="ApiFile.Dispose"/>).
/// </summary>
public async Task<ApiFile> DownloadAttachmentAsync(int attachmentId, CancellationToken ct)
{
var response = await http.GetAsync($"attachments/{attachmentId.ToString(CultureInfo.InvariantCulture)}",
HttpCompletionOption.ResponseHeadersRead, ct);
try
{
await ApiResponse.EnsureSuccessAsync(response, ct);
var disposition = response.Content.Headers.ContentDisposition;
var fileName = (disposition?.FileNameStar ?? disposition?.FileName)?.Trim('"');
return new ApiFile(
await response.Content.ReadAsStreamAsync(ct),
response.Content.Headers.ContentType?.MediaType ?? "application/octet-stream",
string.IsNullOrWhiteSpace(fileName) ? $"priloha-{attachmentId}" : fileName,
response);
}
catch
{
response.Dispose();
throw;
}
}
/// <summary>Řešitelé s počtem otevřených závad – jen pro vedení.</summary>
public async Task<IReadOnlyList<AssignableUserDto>> GetAssignableUsersAsync(CancellationToken ct)
{
using var response = await http.GetAsync("users/assignable", ct);
return await ApiResponse.ReadAsync<List<AssignableUserDto>>(response, ct);
}
private static string IssuePath(int id, string? action = null) =>
action is null ? $"issues/{id.ToString(CultureInfo.InvariantCulture)}" : $"issues/{id.ToString(CultureInfo.InvariantCulture)}/{action}";
/// <summary>Soubory z formuláře jdou do API jako proud v poli <c>files</c>, web je nenačítá do paměti.</summary>
private static void AddFiles(MultipartFormDataContent content, IEnumerable<UploadFile> files)
{
foreach (var file in files) foreach (var file in files)
{ {
var part = new StreamContent(file.OpenRead()); var part = new StreamContent(file.OpenRead());
@@ -59,9 +164,6 @@ public sealed class HelpdeskApiClient(HttpClient http)
: new MediaTypeHeaderValue("application/octet-stream"); : new MediaTypeHeaderValue("application/octet-stream");
content.Add(part, "files", file.FileName); 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) public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(CancellationToken ct)
@@ -3,6 +3,7 @@ using Helpdesk.Web.Api;
using Helpdesk.Web.Infrastructure; using Helpdesk.Web.Infrastructure;
using Helpdesk.Web.Models; using Helpdesk.Web.Models;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
namespace Helpdesk.Web.Controllers; namespace Helpdesk.Web.Controllers;
@@ -49,21 +50,195 @@ public sealed class IssuesController(HelpdeskApiClient api) : Controller
{ {
var issue = await api.CreateIssueAsync( var issue = await api.CreateIssueAsync(
new CreateIssueRequest(model.Title.Trim(), model.Description.Trim(), model.CategoryId!.Value, model.BuildingId, model.LocationDetail?.Trim()), 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(), ToUploads(model.Files),
ct); ct);
TempData.SetSuccess($"Závada #{issue.Id} je nahlášená. Vedení školy ji přiřadí řešiteli."); TempData.SetSuccess($"Závada #{issue.Id} je nahlášená. Vedení školy ji přiřadí řešiteli.");
return RedirectToAction(nameof(Index)); return RedirectToAction(nameof(Detail), new { id = issue.Id });
} }
catch (ApiException ex) when (ex.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.RequestEntityTooLarge catch (ApiException ex) when (IsUserError(ex))
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)); ModelState.AddApiErrors(ex, typeof(NewIssueViewModel));
return View(await WithCatalogsAsync(model, ct)); return View(await WithCatalogsAsync(model, ct));
} }
} }
private async Task<NewIssueViewModel> WithCatalogsAsync(NewIssueViewModel model, CancellationToken ct) /// <summary>Detail závady s časovou osou, přílohami a akcemi podle <c>allowedActions</c>.</summary>
[HttpGet("{id:int}")]
public async Task<IActionResult> Detail(int id, CancellationToken ct)
{
// Postupně, ne paralelně: všechna volání sdílejí HttpContext (token v cookie, jeho obnova).
var issue = await api.GetIssueAsync(id, ct);
var events = await api.GetIssueEventsAsync(id, ct);
var categories = await api.GetIssueCategoriesAsync(ct);
var buildings = await api.GetBuildingsAsync(ct);
IReadOnlyList<AssignableUserDto> assignees = issue.Can(IssueActions.Assign) ? await api.GetAssignableUsersAsync(ct) : [];
return View(new IssueDetailViewModel
{
Issue = issue,
Events = events,
CategoryName = categories.FirstOrDefault(c => c.Id == issue.CategoryId)?.Name ?? "Neznámá kategorie",
Location = IssueListViewModel.FormatLocation(buildings.FirstOrDefault(b => b.Id == issue.BuildingId)?.Name, issue.LocationDetail),
Assignees = assignees,
});
}
/// <summary>Změna stavu: zahájit, předat k ověření, potvrdit, znovu otevřít, zamítnout (T4 – T9).</summary>
[HttpPost("{id:int}/transition")]
public async Task<IActionResult> Transition(int id, IssueActionForm form, CancellationToken ct)
{
var action = form.Action ?? "";
if (IssueActions.TransitionPath(action) is null)
return BadRequest();
var text = string.IsNullOrWhiteSpace(form.Text) || !IssueActions.AcceptsText(action) ? null : form.Text.Trim();
if (IssueActions.RequiresReason(action) && text is null)
return BackToDetail(id, error: "Napište prosím důvod.");
if (text?.Length > IssueActionForm.MaxTextLength)
return BackToDetail(id, error: $"Text může mít nejvýše {IssueActionForm.MaxTextLength} znaků.");
return await RunAsync(id, () => api.TransitionIssueAsync(id, action, form.RowVersion, text, ct), action switch
{
IssueActions.StartWork => "Řešení závady je zahájené.",
IssueActions.SubmitForVerification => "Závada je předaná k ověření. Hlásič potvrdí, jestli je vyřešená.",
IssueActions.Confirm => "Děkujeme, závada je vyřešená.",
IssueActions.Reopen => "Závada je znovu otevřená a vrací se řešiteli.",
_ => "Závada je zamítnutá.",
});
}
/// <summary>Přiřazení nebo přeřazení řešiteli (T2, T3) – jen vedení.</summary>
[HttpPost("{id:int}/assign")]
public async Task<IActionResult> Assign(int id, IssueActionForm form, CancellationToken ct)
{
if (form.AssigneeId is not { } assigneeId)
return BackToDetail(id, error: "Vyberte řešitele.");
var priority = IssuePriorities.All.Contains(form.Priority) ? form.Priority : null;
return await RunAsync(id, () => api.AssignIssueAsync(id, new AssignIssueRequest(assigneeId, priority, form.RowVersion), ct),
"Závada je přiřazená řešiteli.");
}
/// <summary>Komentář hlásiče nebo řešitele (FR-16).</summary>
[HttpPost("{id:int}/comments")]
public async Task<IActionResult> Comment(int id, IssueActionForm form, CancellationToken ct)
{
var text = form.Text?.Trim();
if (string.IsNullOrEmpty(text))
return BackToDetail(id, error: "Napište text komentáře.", fragment: "komentar");
if (text.Length > IssueActionForm.MaxTextLength)
return BackToDetail(id, error: $"Komentář může mít nejvýše {IssueActionForm.MaxTextLength} znaků.", fragment: "komentar");
return await RunAsync(id, () => api.AddCommentAsync(id, text, ct), "Komentář je odeslaný.", fragment: "komentar");
}
/// <summary>Doplnění příloh k závadě v průběhu řešení (FR-11).</summary>
[HttpPost("{id:int}/attachments")]
[RequestSizeLimit(AttachmentRules.MaxRequestBytes)]
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentRules.MaxRequestBytes)]
public async Task<IActionResult> Attachments(int id, IssueActionForm form, CancellationToken ct)
{
var error = form.Files.Count == 0 ? "Vyberte alespoň jeden soubor." : AttachmentRules.Validate(form.Files).FirstOrDefault();
if (error is not null)
return BackToDetail(id, error: error, fragment: "prilohy");
return await RunAsync(id, () => api.AddAttachmentsAsync(id, ToUploads(form.Files), ct),
form.Files.Count == 1 ? "Příloha je nahraná." : "Přílohy jsou nahrané.", fragment: "prilohy");
}
/// <summary>
/// Příloha přes web: prohlížeč nemá access token, proto ji web stáhne z API a pošle dál jako proud.
/// Oprávnění kontroluje API (jen ten, kdo vidí závadu).
/// </summary>
[HttpGet("attachments/{attachmentId:int}")]
public async Task<IActionResult> Attachment(int attachmentId, CancellationToken ct)
{
var file = await api.DownloadAttachmentAsync(attachmentId, ct);
HttpContext.Response.RegisterForDispose(file);
// filename i filename* (RFC 6266), aby prohlížeč zachoval diakritiku v názvu souboru.
var disposition = new ContentDispositionHeaderValue(IssueDetailViewModel.OpensInBrowser(file.ContentType) ? "inline" : "attachment");
disposition.SetHttpFileName(file.FileName);
Response.Headers.ContentDisposition = disposition.ToString();
return File(file.Content, file.ContentType);
}
/// <summary>Úprava hlášení, dokud je ve stavu Přijata (jen hlásič).</summary>
[HttpGet("{id:int}/edit")]
public async Task<IActionResult> Edit(int id, CancellationToken ct)
{
var issue = await api.GetIssueAsync(id, ct);
if (!issue.Can(IssueActions.Edit))
return BackToDetail(id, error: "Hlášení už nejde upravit – vedení ho mezitím převzalo. Doplňující informace napište do komentáře.");
return View(await WithCatalogsAsync(EditIssueViewModel.From(issue), ct));
}
[HttpPost("{id:int}/edit")]
public async Task<IActionResult> Edit(int id, EditIssueViewModel model, CancellationToken ct)
{
model.Id = id;
if (!ModelState.IsValid)
return View(await WithCatalogsAsync(model, ct));
try
{
await api.EditIssueAsync(id, new EditIssueRequest(model.Title.Trim(), model.Description.Trim(), model.CategoryId!.Value,
model.BuildingId, model.LocationDetail?.Trim(), model.RowVersion), ct);
return BackToDetail(id, success: "Změny hlášení jsou uložené.");
}
catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
{
return BackToDetail(id, error: ConflictMessage);
}
catch (ApiException ex) when (IsUserError(ex))
{
ModelState.AddApiErrors(ex, typeof(EditIssueViewModel));
return View(await WithCatalogsAsync(model, ct));
}
}
private const string ConflictMessage =
"Závadu mezitím někdo změnil. Níže je její aktuální stav – zkontrolujte ho a akci případně zopakujte.";
/// <summary>
/// Provede akci a vrátí uživatele na detail se zprávou (Post/Redirect/Get). Chyby, které může
/// uživatel napravit, ukáže nad detailem; 401/403/404 zpracuje <see cref="ApiExceptionFilter"/>.
/// </summary>
private async Task<IActionResult> RunAsync(int id, Func<Task> action, string success, string? fragment = null)
{
try
{
await action();
return BackToDetail(id, success: success, fragment: fragment);
}
catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
{
// 409: jiná rowVersion (někdo závadu mezitím změnil), nebo akce v aktuálním stavu už nejde.
return BackToDetail(id, error: ConflictMessage);
}
catch (ApiException ex) when (IsUserError(ex))
{
return BackToDetail(id, error: ex.AllMessages, fragment: fragment);
}
}
private RedirectToActionResult BackToDetail(int id, string? success = null, string? error = null, string? fragment = null)
{
if (success is not null)
TempData.SetSuccess(success);
if (error is not null)
TempData.SetError(error);
return RedirectToAction(nameof(Detail), null, new { id }, fragment);
}
/// <summary>400 validace nebo nepovolený obsah souboru, 413 příliš velké přílohy, 415, 429 limit zápisů (10/min).</summary>
private static bool IsUserError(ApiException ex) => ex.StatusCode is HttpStatusCode.BadRequest
or HttpStatusCode.RequestEntityTooLarge or HttpStatusCode.UnsupportedMediaType or HttpStatusCode.TooManyRequests;
private static List<UploadFile> ToUploads(IEnumerable<IFormFile> files) =>
files.Select(f => new UploadFile(f.FileName, f.ContentType, f.OpenReadStream)).ToList();
private async Task<T> WithCatalogsAsync<T>(T model, CancellationToken ct) where T : IssueFormViewModel
{ {
model.SetCatalogs(await api.GetIssueCategoriesAsync(ct), await api.GetBuildingsAsync(ct)); model.SetCatalogs(await api.GetIssueCategoriesAsync(ct), await api.GetBuildingsAsync(ct));
return model; return model;
@@ -0,0 +1,112 @@
using Helpdesk.Web.Api;
namespace Helpdesk.Web.Models;
/// <summary>Detail závady: údaje, akce podle <c>allowedActions</c>, přílohy a časová osa (kap. 13.2 návrhu).</summary>
public sealed class IssueDetailViewModel
{
public required IssueDetail Issue { get; init; }
public required IReadOnlyList<IssueEventDto> Events { get; init; }
public required string CategoryName { get; init; }
public string? Location { get; init; }
/// <summary>Možní řešitelé – načítají se jen pro vedení, když smí závadu přiřadit.</summary>
public IReadOnlyList<AssignableUserDto> Assignees { get; init; } = [];
public bool Can(string action) => Issue.Can(action);
public IEnumerable<string> Transitions => IssueActions.Transitions.Where(Can);
/// <summary>API vrací u závady jen ID lidí; jméno hlásiče je u události vytvoření.</summary>
public string ReporterName =>
Events.FirstOrDefault(e => e.EventType == IssueEventTypes.Created)?.ActorName ?? $"Uživatel #{Issue.ReporterId}";
/// <summary>Jméno řešitele zapisuje API do poznámky poslední události přiřazení.</summary>
public string? AssigneeName => Issue.AssigneeId is not { } assigneeId
? null
: Events.LastOrDefault(e => e.EventType == IssueEventTypes.Assigned)?.Note ?? $"Uživatel #{assigneeId}";
/// <summary>Řešitelé kromě současného – přeřadit na stejného API nedovolí.</summary>
public IEnumerable<AssignableUserDto> OtherAssignees => Assignees.Where(a => a.Id != Issue.AssigneeId);
public IEnumerable<TimelineEntry> Timeline => Events.Select(TimelineEntry.From);
public bool IsClosed => Issue.Status is "RESOLVED" or "REJECTED";
/// <summary>Co se se závadou děje, když uživatel sám nemá žádnou akci.</summary>
public string NextStepText => Issue.Status switch
{
"RECEIVED" => "Závada čeká, až ji vedení školy přiřadí řešiteli.",
"ASSIGNED" => "Závada je přiřazená řešiteli, ten ji zatím nezačal řešit.",
"IN_PROGRESS" => "Řešitel na závadě pracuje.",
"PENDING_VERIFICATION" => "Řešitel závadu opravil a čeká, až hlásič potvrdí, že je vyřešená.",
"RESOLVED" => "Závada je vyřešená a uzavřená.",
"REJECTED" => "Závada je zamítnutá a uzavřená. Důvod najdete v průběhu řešení.",
_ => "Stav závady se nepodařilo určit.",
};
public static string FileSize(long bytes) => bytes switch
{
< 1024 => $"{bytes} B",
< 1024 * 1024 => $"{Math.Round(bytes / 1024d)} kB",
_ => $"{bytes / (1024d * 1024):0.#} MB",
};
/// <summary>Fotky a PDF otevře prohlížeč rovnou, ostatní (DOCX, HEIC) se stáhnou.</summary>
public static bool OpensInBrowser(string contentType) => contentType is "image/jpeg" or "image/png" or "application/pdf";
}
public static class IssueEventTypes
{
public const string Created = "CREATED";
public const string Updated = "UPDATED";
public const string Assigned = "ASSIGNED";
public const string StatusChanged = "STATUS_CHANGED";
public const string Commented = "COMMENTED";
}
/// <summary>
/// Jedna položka časové osy pro zobrazení: co se stalo („zahájil/a řešení“), případně poznámka
/// s popiskem („Důvod“) a stav, do kterého závada přešla.
/// </summary>
public sealed record TimelineEntry(IssueEventDto Event, string Text, string? NoteLabel, string? Note, string? Status)
{
public bool IsComment => Event.EventType == IssueEventTypes.Commented;
public static TimelineEntry From(IssueEventDto e) => e.EventType switch
{
IssueEventTypes.Created => new(e, "nahlásil/a závadu", null, null, e.ToStatus),
IssueEventTypes.Updated => new(e, "upravil/a údaje hlášení", null, null, null),
IssueEventTypes.Assigned => new(e,
e.FromStatus is "ASSIGNED" or "IN_PROGRESS" ? $"přeřadil/a závadu na {e.Note}" : $"přiřadil/a závadu řešiteli {e.Note}",
null, null, e.ToStatus),
IssueEventTypes.Commented => new(e, "napsal/a komentář", null, e.Note, null),
IssueEventTypes.StatusChanged => e.ToStatus switch
{
"IN_PROGRESS" when e.FromStatus == "PENDING_VERIFICATION" => new(e, "znovu otevřel/a závadu", "Důvod", e.Note, e.ToStatus),
"IN_PROGRESS" => new(e, "zahájil/a řešení", null, e.Note, e.ToStatus),
"PENDING_VERIFICATION" => new(e, "předal/a závadu k ověření", "Poznámka", e.Note, e.ToStatus),
"RESOLVED" => new(e, "potvrdil/a vyřešení", null, e.Note, e.ToStatus),
"REJECTED" => new(e, "zamítl/a závadu", "Důvod", e.Note, e.ToStatus),
_ => new(e, "změnil/a stav", null, e.Note, e.ToStatus),
},
_ => new(e, "provedl/a změnu", null, e.Note, null),
};
}
/// <summary>Formuláře akcí na detailu závady. Každý POST použije jen svá pole.</summary>
public sealed class IssueActionForm
{
public int RowVersion { get; set; }
public string? Action { get; set; }
/// <summary>Důvod (zamítnutí, znovuotevření) nebo poznámka (předání k ověření).</summary>
public string? Text { get; set; }
public int? AssigneeId { get; set; }
public string? Priority { get; set; }
public List<IFormFile> Files { get; set; } = [];
public const int MaxTextLength = 5000;
}
@@ -16,10 +16,12 @@ public sealed class IssueListViewModel
public string CategoryName(int id) => CategoryNames.GetValueOrDefault(id, "Neznámá kategorie"); public string CategoryName(int id) => CategoryNames.GetValueOrDefault(id, "Neznámá kategorie");
/// <summary>Budova a upřesnění místa, např. „Budova B – učebna B-205“.</summary> /// <summary>Budova a upřesnění místa, např. „Budova B – učebna B-205“.</summary>
public string? Location(IssueSummary issue) public string? Location(IssueSummary issue) =>
FormatLocation(issue.BuildingId is { } id ? BuildingNames.GetValueOrDefault(id) : null, issue.LocationDetail);
public static string? FormatLocation(string? building, string? locationDetail)
{ {
var building = issue.BuildingId is { } id ? BuildingNames.GetValueOrDefault(id) : null; return (building, locationDetail) switch
return (building, issue.LocationDetail) switch
{ {
(null, null or "") => null, (null, null or "") => null,
(null, var detail) => detail, (null, var detail) => detail,
+29 -5
View File
@@ -38,7 +38,8 @@ public static class AttachmentRules
} }
} }
public sealed class NewIssueViewModel /// <summary>Údaje hlášení společné pro nové hlášení i jeho úpravu (partial <c>_IssueFields</c>).</summary>
public abstract class IssueFormViewModel
{ {
[Required(ErrorMessage = "Zadejte název.")] [Required(ErrorMessage = "Zadejte název.")]
[StringLength(200, ErrorMessage = "Název může mít nejvýše 200 znaků.")] [StringLength(200, ErrorMessage = "Název může mít nejvýše 200 znaků.")]
@@ -46,7 +47,7 @@ public sealed class NewIssueViewModel
public string Title { get; set; } = ""; public string Title { get; set; } = "";
[Required(ErrorMessage = "Popište závadu.")] [Required(ErrorMessage = "Popište závadu.")]
[StringLength(4000, ErrorMessage = "Popis může mít nejvýše 4000 znaků.")] [StringLength(10_000, ErrorMessage = "Popis může mít nejvýše 10 000 znaků.")] // stejně jako v mobilu
[Display(Name = "Popis")] [Display(Name = "Popis")]
public string Description { get; set; } = ""; public string Description { get; set; } = "";
@@ -61,9 +62,6 @@ public sealed class NewIssueViewModel
[Display(Name = "Upřesnění místa")] [Display(Name = "Upřesnění místa")]
public string? LocationDetail { get; set; } 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. // Nabídky pro výběr – plní je kontroler z číselníků API.
public IReadOnlyList<SelectListItem> Categories { get; set; } = []; public IReadOnlyList<SelectListItem> Categories { get; set; } = [];
public IReadOnlyList<SelectListItem> Buildings { get; set; } = []; public IReadOnlyList<SelectListItem> Buildings { get; set; } = [];
@@ -74,3 +72,29 @@ public sealed class NewIssueViewModel
Buildings = buildings.Select(b => new SelectListItem(b.Name, b.Id.ToString())).ToList(); Buildings = buildings.Select(b => new SelectListItem(b.Name, b.Id.ToString())).ToList();
} }
} }
public sealed class NewIssueViewModel : IssueFormViewModel
{
[Display(Name = "Fotografie nebo soubory")]
public List<IFormFile> Files { get; set; } = [];
}
/// <summary>Úprava hlášení hlásičem, dokud ho vedení nepřiřadí (stav Přijata).</summary>
public sealed class EditIssueViewModel : IssueFormViewModel
{
public int Id { get; set; }
/// <summary>Verze, kterou uživatel upravuje; když se závada mezitím změní, API vrátí 409.</summary>
public int RowVersion { get; set; }
public static EditIssueViewModel From(IssueDetail issue) => new()
{
Id = issue.Id,
RowVersion = issue.RowVersion,
Title = issue.Title,
Description = issue.Description,
CategoryId = issue.CategoryId,
BuildingId = issue.BuildingId,
LocationDetail = issue.LocationDetail,
};
}
+195
View File
@@ -0,0 +1,195 @@
@using Helpdesk.Web.Api
@model IssueDetailViewModel
@{
var issue = Model.Issue;
ViewData["Title"] = $"Závada #{issue.Id}";
var transitions = Model.Transitions.ToList();
var canAssign = Model.Can(IssueActions.Assign);
}
<section class="app-page-head">
<a asp-action="Index" class="app-back-link">Moje hlášení</a>
<span class="app-issue-id d-block mt-2">Hlášení #@issue.Id</span>
<div class="d-flex flex-wrap align-items-center gap-3">
<h1 class="mb-0">@issue.Title</h1>
<partial name="_StatusBadge" model="new StatusBadgeModel(issue.Status)" />
</div>
</section>
<div class="row g-4">
<div class="col-lg-8 d-grid gap-4 align-content-start">
<section class="app-card" aria-labelledby="udaje">
<h2 id="udaje" class="visually-hidden">Údaje hlášení</h2>
<dl class="app-facts">
<dt>Kategorie</dt>
<dd>@Model.CategoryName</dd>
<dt>Místo</dt>
<dd>@(Model.Location ?? "Neuvedeno")</dd>
<dt>Nahlásil/a</dt>
<dd>@Model.ReporterName</dd>
<dt>Řešitel</dt>
<dd>@(Model.AssigneeName ?? "Zatím nepřiřazen")</dd>
<dt>Priorita</dt>
<dd>@IssuePriorities.Label(issue.Priority)</dd>
<dt>Nahlášeno</dt>
<dd><time datetime="@issue.CreatedAt.ToString("O")">@DisplayTime.Format(issue.CreatedAt)</time></dd>
</dl>
<h3 class="h6 fw-bold">Popis</h3>
<p class="app-text mb-0">@issue.Description</p>
@if (Model.Can(IssueActions.Edit))
{
<a asp-action="Edit" asp-route-id="@issue.Id" class="btn btn-outline-primary btn-sm mt-3">Upravit hlášení</a>
}
</section>
<section class="app-card" id="prilohy" aria-labelledby="prilohy-nadpis">
<h2 id="prilohy-nadpis" class="h5 fw-bold">Přílohy</h2>
@if (issue.Attachments.Count == 0)
{
<p class="text-body-secondary">Bez příloh.</p>
}
else
{
<ul class="app-attachments">
@foreach (var file in issue.Attachments)
{
var opens = IssueDetailViewModel.OpensInBrowser(file.ContentType);
<li>
<a asp-action="Attachment" asp-route-attachmentId="@file.Id"
target="@(opens ? "_blank" : null)" rel="@(opens ? "noopener" : null)">@file.FileName</a>
<span class="text-body-secondary">@IssueDetailViewModel.FileSize(file.SizeBytes)</span>
</li>
}
</ul>
}
@if (Model.Can(IssueActions.AddAttachments))
{
<form method="post" asp-action="Attachments" asp-route-id="@issue.Id" enctype="multipart/form-data" class="mt-3">
<label for="files" class="form-label">Doplnit fotografie nebo soubory</label>
<div class="d-flex flex-wrap gap-2">
<input id="files" name="Files" type="file" class="form-control w-auto flex-grow-1" multiple required
accept="@AttachmentRules.Accept" aria-describedby="filesHelp" />
<button type="submit" class="btn btn-outline-primary">Nahrát</button>
</div>
<div id="filesHelp" class="form-text">Nejvýše @AttachmentRules.MaxFiles souborů po 10 MB – JPG, PNG, HEIC, PDF nebo DOCX.</div>
</form>
}
</section>
<section class="app-card" id="prubeh" aria-labelledby="prubeh-nadpis">
<h2 id="prubeh-nadpis" class="h5 fw-bold mb-3">Průběh řešení a komentáře</h2>
<ol class="app-timeline">
@foreach (var entry in Model.Timeline)
{
<li class="app-timeline-item @(entry.IsComment ? "is-comment" : "")">
<div class="app-timeline-head">
<span><strong>@entry.Event.ActorName</strong> @entry.Text</span>
<time datetime="@entry.Event.OccurredAt.ToString("O")">@DisplayTime.Format(entry.Event.OccurredAt)</time>
</div>
@if (entry.IsComment)
{
<p class="app-comment app-text">@entry.Note</p>
}
else if (!string.IsNullOrWhiteSpace(entry.Note))
{
<p class="app-timeline-note">
@if (entry.NoteLabel is not null)
{
<strong>@entry.NoteLabel:</strong>
}
<span class="app-text">@entry.Note</span>
</p>
}
@if (entry.Status is not null)
{
<partial name="_StatusBadge" model="new StatusBadgeModel(entry.Status)" />
}
</li>
}
</ol>
@if (Model.Can(IssueActions.Comment))
{
<form method="post" asp-action="Comment" asp-route-id="@issue.Id" id="komentar" class="mt-4">
<label for="comment" class="form-label">Napsat komentář</label>
<textarea id="comment" name="Text" class="form-control" rows="3" required maxlength="@IssueActionForm.MaxTextLength"
placeholder="Doplňující informace, dotaz na řešitele nebo hlásiče…"></textarea>
<button type="submit" class="btn btn-primary mt-2">Odeslat komentář</button>
</form>
}
else if (Model.IsClosed)
{
<p class="text-body-secondary mt-3 mb-0">Závada je uzavřená, komentáře už nejde přidávat.</p>
}
</section>
</div>
<aside class="col-lg-4">
<section class="app-card app-next-step" aria-labelledby="dalsi-krok">
<h2 id="dalsi-krok" class="h5 fw-bold">Další krok</h2>
@if (transitions.Count == 0 && !canAssign)
{
<p class="text-body-secondary mb-0">@Model.NextStepText</p>
}
@foreach (var action in transitions)
{
var primary = action is IssueActions.StartWork or IssueActions.SubmitForVerification or IssueActions.Confirm;
var buttonClass = primary ? "btn-primary" : action == IssueActions.Reject ? "btn-outline-danger" : "btn-outline-primary";
if (!IssueActions.AcceptsText(action))
{
<form method="post" asp-action="Transition" asp-route-id="@issue.Id">
<input type="hidden" name="Action" value="@action" />
<input type="hidden" name="RowVersion" value="@issue.RowVersion" />
<button type="submit" class="btn @buttonClass w-100">@IssueActions.Label(action)</button>
</form>
}
else
{
var required = IssueActions.RequiresReason(action);
var textId = $"text-{action.ToLowerInvariant()}";
@* <details> rozbalí formulář s důvodem bez JavaScriptu (CSP nepovoluje inline skripty). *@
<details class="app-action">
<summary class="btn @buttonClass w-100">@IssueActions.Label(action)…</summary>
<form method="post" asp-action="Transition" asp-route-id="@issue.Id" class="app-action-form">
<input type="hidden" name="Action" value="@action" />
<input type="hidden" name="RowVersion" value="@issue.RowVersion" />
<label for="@textId" class="form-label">@(required ? "Důvod" : "Poznámka pro hlásiče (nepovinná)")</label>
<textarea id="@textId" name="Text" class="form-control" rows="3" maxlength="@IssueActionForm.MaxTextLength"
required="@required"></textarea>
<button type="submit" class="btn @buttonClass mt-2">@IssueActions.Label(action)</button>
</form>
</details>
}
}
@if (canAssign)
{
<form method="post" asp-action="Assign" asp-route-id="@issue.Id" class="app-assign @(transitions.Count > 0 ? "mt-3 pt-3 border-top" : "")">
<input type="hidden" name="RowVersion" value="@issue.RowVersion" />
<div class="mb-2">
<label for="assignee" class="form-label">@(issue.AssigneeId is null ? "Přiřadit řešiteli" : "Přeřadit na jiného řešitele")</label>
<select id="assignee" name="AssigneeId" class="form-select" required>
<option value="">Vyberte řešitele</option>
@foreach (var person in Model.OtherAssignees)
{
<option value="@person.Id">@person.FullName (@UserRoles.DisplayName(person.Role).ToLowerInvariant(), otevřené: @person.OpenIssues)</option>
}
</select>
</div>
<div class="mb-2">
<label for="priority" class="form-label">Priorita</label>
<select id="priority" name="Priority" class="form-select">
@foreach (var priority in IssuePriorities.All)
{
<option value="@priority" selected="@(priority == issue.Priority)">@IssuePriorities.Label(priority)</option>
}
</select>
</div>
<button type="submit" class="btn btn-primary w-100">@(issue.AssigneeId is null ? "Přiřadit" : "Přeřadit")</button>
</form>
}
</section>
</aside>
</div>
+27
View File
@@ -0,0 +1,27 @@
@model EditIssueViewModel
@{
ViewData["Title"] = $"Upravit hlášení #{Model.Id}";
}
<section class="app-page-head">
<a asp-action="Detail" asp-route-id="@Model.Id" class="app-back-link">Zpět na závadu #@Model.Id</a>
<h1>Upravit hlášení</h1>
<p class="lead text-body-secondary">Upřesněte údaje, aby se závada vyřešila rychleji. Upravovat jde jen do chvíle, než ji vedení přiřadí řešiteli.</p>
</section>
<div class="row">
<div class="col-lg-8">
<div class="app-card">
<partial name="_FormErrors" />
<form method="post" asp-action="Edit" asp-route-id="@Model.Id" novalidate>
<input type="hidden" asp-for="RowVersion" />
<partial name="_IssueFields" model="Model" />
<div class="d-flex flex-wrap gap-2 mt-4">
<button type="submit" class="btn btn-primary">Uložit změny</button>
<a asp-action="Detail" asp-route-id="@Model.Id" class="btn btn-outline-primary">Zrušit</a>
</div>
</form>
</div>
</div>
</div>
+2 -2
View File
@@ -46,10 +46,10 @@ else
@foreach (var issue in result.Items) @foreach (var issue in result.Items)
{ {
var location = Model.Location(issue); var location = Model.Location(issue);
<li class="app-card app-issue"> <li class="app-card app-issue position-relative">
<div class="app-issue-main"> <div class="app-issue-main">
<span class="app-issue-id">#@issue.Id</span> <span class="app-issue-id">#@issue.Id</span>
<h2 class="app-issue-title">@issue.Title</h2> <h2 class="app-issue-title"><a asp-action="Detail" asp-route-id="@issue.Id" class="app-issue-link stretched-link">@issue.Title</a></h2>
<p class="app-issue-meta"> <p class="app-issue-meta">
@Model.CategoryName(issue.CategoryId) @Model.CategoryName(issue.CategoryId)
@if (location is not null) @if (location is not null)
+1 -35
View File
@@ -14,41 +14,7 @@
<div class="app-card"> <div class="app-card">
<partial name="_FormErrors" /> <partial name="_FormErrors" />
<form method="post" asp-action="New" enctype="multipart/form-data" novalidate> <form method="post" asp-action="New" enctype="multipart/form-data" novalidate>
<div class="mb-3"> <partial name="_IssueFields" model="Model" />
<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"> <div class="mb-4">
<label asp-for="Files" class="form-label"></label> <label asp-for="Files" class="form-label"></label>
@@ -0,0 +1,38 @@
@model IssueFormViewModel
@* Pole hlášení společná pro nové hlášení a jeho úpravu. *@
<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>
+33
View File
@@ -118,6 +118,39 @@ body { min-height: 100vh; display: flex; flex-direction: column; }
.app-issue-side { display: flex; flex-direction: column; align-items: flex-end; gap: .4rem; font-size: .85rem; color: var(--app-muted); font-variant-numeric: tabular-nums; } .app-issue-side { display: flex; flex-direction: column; align-items: flex-end; gap: .4rem; font-size: .85rem; color: var(--app-muted); font-variant-numeric: tabular-nums; }
@media (max-width: 575.98px) { .app-issue-side { flex-direction: row; align-items: center; width: 100%; justify-content: space-between; } } @media (max-width: 575.98px) { .app-issue-side { flex-direction: row; align-items: center; width: 100%; justify-content: space-between; } }
.app-empty-card { text-align: center; padding-block: 2.5rem; } .app-empty-card { text-align: center; padding-block: 2.5rem; }
.app-issue-link { color: inherit; text-decoration: none; }
.app-issue:hover { border-color: var(--app-accent); }
.app-issue-link:focus-visible { outline: none; }
.app-issue:has(.app-issue-link:focus-visible) { outline: 2px solid var(--app-accent); outline-offset: 2px; }
/* detail závady */
.app-back-link { font-weight: 600; text-decoration: none; }
.app-back-link::before { content: "← "; }
.app-text { white-space: pre-line; overflow-wrap: anywhere; }
.app-attachments { list-style: none; padding: 0; margin: 0; display: grid; gap: .4rem; }
.app-attachments li { display: flex; flex-wrap: wrap; gap: .25rem .75rem; align-items: baseline; }
.app-attachments a { font-weight: 600; overflow-wrap: anywhere; }
.app-attachments span { font-size: .85rem; font-variant-numeric: tabular-nums; }
.app-next-step { display: grid; gap: .6rem; }
@media (min-width: 992px) { .app-next-step { position: sticky; top: 1rem; } }
.app-action > summary { list-style: none; }
.app-action > summary::-webkit-details-marker { display: none; }
.app-action[open] > summary { margin-bottom: .6rem; }
.app-action-form { padding: .75rem; border: 1px solid var(--app-line); border-radius: 1rem; }
/* časová osa = svislá čára s tečkami, komentáře jako bubliny */
.app-timeline { list-style: none; margin: 0; padding: 0 0 0 1.25rem; border-left: 2px solid var(--app-line); display: grid; gap: 1.1rem; }
.app-timeline-item { position: relative; display: grid; gap: .35rem; justify-items: start; }
.app-timeline-item::before {
content: ""; position: absolute; left: calc(-1.25rem - 6px); top: .35rem;
width: 10px; height: 10px; border-radius: 50%; background: var(--app-accent); box-shadow: 0 0 0 3px #fff;
}
.app-timeline-item.is-comment::before { background: #fff; border: 2px solid var(--app-muted); }
.app-timeline-head { display: flex; flex-wrap: wrap; gap: .1rem .75rem; align-items: baseline; }
.app-timeline-head time { font-size: .85rem; color: var(--app-muted); font-variant-numeric: tabular-nums; }
.app-timeline-note { margin: 0; color: var(--app-muted); }
.app-comment { margin: 0; padding: .65rem .9rem; background: var(--app-surface); border-radius: 1rem; border-top-left-radius: .25rem; max-width: 100%; }
/* Štítek stavu jako StatusBadge v mobilu: tečka a text v barvě stavu na pozadí s 11 % té barvy. */ /* Štítek stavu jako StatusBadge v mobilu: tečka a text v barvě stavu na pozadí s 11 % té barvy. */
.status-badge { .status-badge {