202 lines
9.5 KiB
C#
202 lines
9.5 KiB
C#
using System.Globalization;
|
||
using System.Net.Http.Headers;
|
||
using System.Net.Http.Json;
|
||
using Microsoft.AspNetCore.WebUtilities;
|
||
|
||
namespace Helpdesk.Web.Api;
|
||
|
||
/// <summary>Endpointy API pro přihlášeného uživatele; access token přidává <see cref="BearerTokenHandler"/>.</summary>
|
||
public sealed class HelpdeskApiClient(HttpClient http)
|
||
{
|
||
public async Task<string> GetOpenApiAsync(CancellationToken ct)
|
||
{
|
||
using var response = await http.GetAsync("api/v1/admin/openapi/v1.json", ct);
|
||
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||
return await response.Content.ReadAsStringAsync(ct);
|
||
}
|
||
|
||
public async Task<UserDto> GetMeAsync(CancellationToken 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("users/me", request, ct);
|
||
return await ApiResponse.ReadAsync<UserDto>(response, ct);
|
||
}
|
||
|
||
public async Task<PagedResult<IssueSummary>> GetIssuesAsync(IssueListQuery query, CancellationToken ct)
|
||
{
|
||
var parameters = new Dictionary<string, string?>
|
||
{
|
||
["status"] = query.Status,
|
||
["mine"] = query.Mine ? "true" : null,
|
||
["sort"] = query.Sort,
|
||
["page"] = query.Page.ToString(CultureInfo.InvariantCulture),
|
||
["pageSize"] = query.PageSize.ToString(CultureInfo.InvariantCulture),
|
||
};
|
||
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");
|
||
|
||
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)
|
||
{
|
||
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);
|
||
}
|
||
}
|
||
|
||
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(CancellationToken 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("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("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("auth/logout", new RefreshTokenRequest(refreshToken), ct);
|
||
await ApiResponse.EnsureSuccessAsync(response, ct);
|
||
}
|
||
}
|