Merge main into mobile-app
This commit is contained in:
commit
a1bf12ba72
31 files changed
+1082
-47
No files matched your search
@@ -9,7 +9,7 @@ Univerzitní helpdesk a portál návrhů na zlepšení – semestrální práce
|
||||
| Složka / soubor | Obsah |
|
||||
|---|---|
|
||||
| [docs/navrh-aplikace.md](docs/navrh-aplikace.md) | Návrhový dokument (v1.1 – včetně zapracovaných připomínek z obhajoby) |
|
||||
| [db/migrations/](db/migrations/) | Verzované SQL migrace (MariaDB 11) – `V001` schéma, `V002` číselníky |
|
||||
| [db/migrations/](db/migrations/) | Verzované SQL migrace (MariaDB 11) – schéma, číselníky a porovnávání FCM tokenů |
|
||||
| [backend/](backend/) | ASP.NET Core Web API, DbUp migrator, unit testy (.NET 10) |
|
||||
| [mobile/](mobile/) | Android klient v Kotlinu a Jetpack Compose (Android 8+), připojení k API a ukázkový režim |
|
||||
| [deploy/](deploy/) | Docker Compose, inicializace DB účtů, šablona `.env` |
|
||||
@@ -24,7 +24,7 @@ Potřeba je jen Docker Desktop.
|
||||
cp deploy/.env.example deploy/.env
|
||||
```
|
||||
|
||||
Výchozí port API je `8080`. Pokud jej používá jiná aplikace, změňte u služby `api` v `deploy/docker-compose.yml` mapování na `8081:8080`. Port je v aktuální konfiguraci zadaný přímo.
|
||||
Výchozí port API je `8080`. Pokud jej používá jiná aplikace, nastavte v `deploy/.env` hodnotu `API_HTTP_PORT=8081`.
|
||||
|
||||
2. Spusťte databázi, migrace a API:
|
||||
|
||||
@@ -34,9 +34,17 @@ Potřeba je jen Docker Desktop.
|
||||
|
||||
3. Swagger UI: <http://localhost:8080/swagger> · stav a verze schématu: <http://localhost:8080/health>
|
||||
|
||||
Při mapování `8081:8080` použijte <http://localhost:8081/swagger> a <http://localhost:8081/health>.
|
||||
Při nastavení `API_HTTP_PORT=8081` použijte <http://localhost:8081/swagger> a <http://localhost:8081/health>.
|
||||
|
||||
Při prvním startu se vytvoří účet administrátora z `ADMIN_EMAIL` / `ADMIN_PASSWORD`. V prostředí `Development` je odesílání e-mailů zatím jen do logu – odkaz pro ověření e-mailu po registraci najdete v `docker compose -f deploy/docker-compose.yml logs api`. Mimo vývoj se obsah e-mailů neloguje a poštovní transport ještě není zapojený.
|
||||
Při prvním startu se vytvoří účet administrátora, pokud vyplníte `ADMIN_EMAIL` a `ADMIN_PASSWORD`. V režimu `Development` s prázdnými hodnotami `SMTP_MAILBOX` a `SMTP_PASSWORD` najdete ověřovací odkazy a odkazy pro obnovu hesla v logu služby `api`.
|
||||
|
||||
Pro nasazení nastavte v `deploy/.env` režim `Production`, veřejnou HTTPS adresu webu v `PUBLIC_BASE_URL` a skutečné univerzitní domény v `STUDENT_EMAIL_DOMAIN` a `TEACHER_EMAIL_DOMAIN`. Pro Email Profi vyplňte `SMTP_MAILBOX` celou adresou schránky a nastavte `SMTP_PASSWORD`. API odesílá přes `smtp.seznam.cz:465` s TLS.
|
||||
|
||||
Reverse proxy ukončuje HTTPS a předává požadavky přes HTTP na adresu `PROXY_UPSTREAM_BIND_ADDRESS` a port `API_HTTP_PORT`. Výchozí hodnoty `127.0.0.1` a `8080` odpovídají proxy běžící přímo na stejném hostiteli.
|
||||
|
||||
Pro zpracování `X-Forwarded-For` a `X-Forwarded-Proto` nastavte `TRUSTED_REVERSE_PROXY_IP` na IP bezprostředního protějšku, kterou vidí API. Tato IP se může při průchodu Docker sítí lišit od adresy, na kterou je API vázáno.
|
||||
|
||||
S nakonfigurovaným SMTP odesílá backend i e-mailové notifikace z databázové fronty. Pro mobilní push nastavte `FIREBASE_SERVICE_ACCOUNT_JSON` na jednořádkový JSON klíče servisního účtu Firebase.
|
||||
|
||||
### Vývoj bez Dockeru
|
||||
|
||||
@@ -50,7 +58,7 @@ dotnet run --project backend/tests/Helpdesk.UnitTests/Helpdesk.UnitTests.csproj
|
||||
|
||||
Otevřete složku `mobile` v Android Studiu, nechte dokončit synchronizaci Gradle a spusťte aplikaci na Androidu 8.0 nebo novějším. Na úvodní obrazovce lze zvolit **Prohlédnout ukázku** bez běžícího serveru. Vlastní backend se nastavuje přes **Nastavení serveru**; výchozí adresa pro emulátor je `http://10.0.2.2:8080/`.
|
||||
|
||||
Pokud jste port API změnili na `8081:8080`, zadejte v aplikaci `http://10.0.2.2:8081/`. Mobil je napojený na implementované API závad, návrhů a oznámení včetně příloh, hlasování a pracovního postupu řešitele; ukázkový režim je samostatná volba.
|
||||
Pokud jste nastavili `API_HTTP_PORT=8081`, zadejte v aplikaci `http://10.0.2.2:8081/`. Pro skutečný telefon ve stejné Wi-Fi nastavte také `PROXY_UPSTREAM_BIND_ADDRESS=0.0.0.0` a v aplikaci použijte LAN adresu počítače; výchozí vazba `127.0.0.1` je určená místní proxy a emulátoru. Mobil je napojený na implementované API závad, návrhů a oznámení včetně příloh, hlasování a pracovního postupu řešitele; ukázkový režim je samostatná volba.
|
||||
|
||||
Podrobný postup sestavení, rozsah funkcí a stav napojení na API: [mobile/README.md](mobile/README.md).
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@
|
||||
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.14" />
|
||||
<PackageVersion Include="Swashbuckle.AspNetCore" Version="10.3.1" />
|
||||
<PackageVersion Include="BCrypt.Net-Next" Version="4.2.0" />
|
||||
<PackageVersion Include="MailKit" Version="5.0.0" />
|
||||
<PackageVersion Include="FirebaseAdmin" Version="3.7.1" />
|
||||
<PackageVersion Include="FluentValidation" Version="12.2.0" />
|
||||
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
|
||||
<!-- testy -->
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
using Helpdesk.Api.Infrastructure;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Notifications;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Helpdesk.Api.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[Route("api/admin/notification-deliveries")]
|
||||
public sealed class AdminNotificationDeliveriesController(NotificationDeliveryService deliveries) : ControllerBase
|
||||
{
|
||||
/// <summary>Přehled doručení podle stavu, výchozí stav je FAILED.</summary>
|
||||
[HttpGet]
|
||||
[ProducesResponseType<PagedResult<NotificationDeliveryDto>>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
public Task<PagedResult<NotificationDeliveryDto>> List(
|
||||
CancellationToken ct, [FromQuery] string status = "FAILED", [FromQuery] int page = 1, [FromQuery] int pageSize = 20) =>
|
||||
deliveries.ListAsync(status, page, pageSize, ct);
|
||||
|
||||
/// <summary>Vrátí neúspěšné doručení do fronty s novým počtem pokusů.</summary>
|
||||
[HttpPost("{id:int}/retry")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public async Task<IActionResult> Retry(int id, CancellationToken ct)
|
||||
{
|
||||
await deliveries.RetryAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
||||
[ProducesResponseType<UserDto>(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status503ServiceUnavailable)]
|
||||
public async Task<ActionResult<UserDto>> Register(RegisterRequest request, CancellationToken ct)
|
||||
{
|
||||
var user = await auth.RegisterAsync(request, ct);
|
||||
@@ -74,9 +75,10 @@ public sealed class AuthController(AuthService auth) : ControllerBase
|
||||
/// <summary>Odešle e-mail s odkazem pro nastavení nového hesla. Odpověď je stejná, ať účet existuje, nebo ne.</summary>
|
||||
[HttpPost("forgot-password")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> ForgotPassword(ForgotPasswordRequest request, CancellationToken ct)
|
||||
public IActionResult ForgotPassword(ForgotPasswordRequest request, [FromServices] IHostApplicationLifetime lifetime)
|
||||
{
|
||||
await auth.ForgotPasswordAsync(request, ct);
|
||||
// Doba vyhledání účtu a doručení přes SMTP se nesmí projevit v době odpovědi.
|
||||
Response.OnCompleted(() => auth.ForgotPasswordAsync(request, lifetime.ApplicationStopping));
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
|
||||
@@ -17,12 +17,6 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
||||
public Task<IReadOnlyList<BuildingDto>> GetBuildings([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
|
||||
catalogs.GetBuildingsAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
|
||||
|
||||
[HttpGet("issue-categories")]
|
||||
public Task<IReadOnlyList<CategoryDto>> GetIssueCategories(CancellationToken ct) => catalogs.GetIssueCategoriesAsync(ct);
|
||||
|
||||
[HttpGet("proposal-categories")]
|
||||
public Task<IReadOnlyList<CategoryDto>> GetProposalCategories(CancellationToken ct) => catalogs.GetProposalCategoriesAsync(ct);
|
||||
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpPost("buildings")]
|
||||
[ProducesResponseType<BuildingDto>(StatusCodes.Status201Created)]
|
||||
@@ -51,4 +45,76 @@ public sealed class CatalogsController(CatalogService catalogs) : ControllerBase
|
||||
await catalogs.DeactivateBuildingAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>Kategorie závad. Administrátor může zobrazit i deaktivované pomocí <c>includeInactive=true</c>.</summary>
|
||||
[HttpGet("issue-categories")]
|
||||
public Task<IReadOnlyList<CategoryDto>> GetIssueCategories([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
|
||||
catalogs.GetIssueCategoriesAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
|
||||
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpPost("issue-categories")]
|
||||
[ProducesResponseType<CategoryDto>(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public async Task<ActionResult<CategoryDto>> CreateIssueCategory(SaveCategoryRequest request, CancellationToken ct)
|
||||
{
|
||||
var category = await catalogs.CreateIssueCategoryAsync(request, ct);
|
||||
return Created($"/api/issue-categories/{category.Id}", category);
|
||||
}
|
||||
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpPut("issue-categories/{id:int}")]
|
||||
[ProducesResponseType<CategoryDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public Task<CategoryDto> UpdateIssueCategory(int id, SaveCategoryRequest request, CancellationToken ct) =>
|
||||
catalogs.UpdateIssueCategoryAsync(id, request, ct);
|
||||
|
||||
/// <summary>Deaktivuje kategorii závad.</summary>
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpDelete("issue-categories/{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeactivateIssueCategory(int id, CancellationToken ct)
|
||||
{
|
||||
await catalogs.DeactivateIssueCategoryAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>Kategorie návrhů. Administrátor může zobrazit i deaktivované pomocí <c>includeInactive=true</c>.</summary>
|
||||
[HttpGet("proposal-categories")]
|
||||
public Task<IReadOnlyList<CategoryDto>> GetProposalCategories([FromQuery] bool includeInactive = false, CancellationToken ct = default) =>
|
||||
catalogs.GetProposalCategoriesAsync(includeInactive && User.IsInRole(Roles.Admin), ct);
|
||||
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpPost("proposal-categories")]
|
||||
[ProducesResponseType<CategoryDto>(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public async Task<ActionResult<CategoryDto>> CreateProposalCategory(SaveCategoryRequest request, CancellationToken ct)
|
||||
{
|
||||
var category = await catalogs.CreateProposalCategoryAsync(request, ct);
|
||||
return Created($"/api/proposal-categories/{category.Id}", category);
|
||||
}
|
||||
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpPut("proposal-categories/{id:int}")]
|
||||
[ProducesResponseType<CategoryDto>(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
|
||||
public Task<CategoryDto> UpdateProposalCategory(int id, SaveCategoryRequest request, CancellationToken ct) =>
|
||||
catalogs.UpdateProposalCategoryAsync(id, request, ct);
|
||||
|
||||
/// <summary>Deaktivuje kategorii návrhů.</summary>
|
||||
[Authorize(Roles = Roles.Admin)]
|
||||
[HttpDelete("proposal-categories/{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeactivateProposalCategory(int id, CancellationToken ct)
|
||||
{
|
||||
await catalogs.DeactivateProposalCategoryAsync(id, ct);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using Helpdesk.Application.Notifications;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Helpdesk.Api.Controllers;
|
||||
|
||||
public sealed record RegisterDeviceRequest(string Token);
|
||||
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("api/devices")]
|
||||
public sealed class DevicesController(PushDeviceService devices) : ControllerBase
|
||||
{
|
||||
/// <summary>Zaregistruje FCM token pro právě přihlášeného uživatele.</summary>
|
||||
[HttpPost]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Register(RegisterDeviceRequest request, CancellationToken ct)
|
||||
{
|
||||
await devices.RegisterAsync(request.Token, ct);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>Odregistruje token právě přihlášeného uživatele.</summary>
|
||||
[HttpDelete("{token}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
public async Task<IActionResult> Unregister(string token, CancellationToken ct)
|
||||
{
|
||||
await devices.UnregisterAsync(token, ct);
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Helpdesk.Api.Infrastructure;
|
||||
using Helpdesk.Application.Statistics;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Helpdesk.Api.Controllers;
|
||||
|
||||
/// <summary>Statistiky pro vedení školy. Období v UTC zahrnuje začátek a vylučuje konec.</summary>
|
||||
[ApiController]
|
||||
[Authorize(Roles = Roles.Management)]
|
||||
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
|
||||
[Route("api/statistics")]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status401Unauthorized)]
|
||||
[ProducesResponseType<ProblemDetails>(StatusCodes.Status403Forbidden)]
|
||||
public sealed class StatisticsController(StatisticsService statistics) : ControllerBase
|
||||
{
|
||||
/// <summary>Počty podle aktuálního stavu a průměrné časy pro závady nahlášené v období.</summary>
|
||||
[HttpGet("overview")]
|
||||
public Task<StatisticsOverview> GetOverview([FromQuery] StatisticsQuery query, CancellationToken ct) =>
|
||||
statistics.GetOverviewAsync(query.ToPeriod(), ct);
|
||||
|
||||
/// <summary>Počty nahlášených závad a průměrná doba vyřešení podle kategorie.</summary>
|
||||
[HttpGet("issues/by-category")]
|
||||
public Task<IReadOnlyList<IssueCategoryStatistics>> GetByCategory([FromQuery] StatisticsQuery query, CancellationToken ct) =>
|
||||
statistics.GetByCategoryAsync(query.ToPeriod(), ct);
|
||||
|
||||
/// <summary>Počty nahlášených závad podle budovy včetně závad bez budovy.</summary>
|
||||
[HttpGet("issues/by-building")]
|
||||
public Task<IReadOnlyList<IssueBuildingStatistics>> GetByBuilding([FromQuery] StatisticsQuery query, CancellationToken ct) =>
|
||||
statistics.GetByBuildingAsync(query.ToPeriod(), ct);
|
||||
|
||||
/// <summary>Otevřené, vyřešené a zamítnuté závady podle aktuálního řešitele.</summary>
|
||||
[HttpGet("issues/by-assignee")]
|
||||
public Task<IReadOnlyList<IssueAssigneeStatistics>> GetByAssignee([FromQuery] StatisticsQuery query, CancellationToken ct) =>
|
||||
statistics.GetByAssigneeAsync(query.ToPeriod(), ct);
|
||||
|
||||
/// <summary>Počty vytvoření a uzavření závad po měsících podle data události.</summary>
|
||||
[HttpGet("issues/trend")]
|
||||
public Task<IReadOnlyList<IssueTrendPoint>> GetTrend([FromQuery] StatisticsQuery query, CancellationToken ct,
|
||||
[FromQuery, AllowedValues("month")] string granularity = "month") =>
|
||||
statistics.GetTrendAsync(query.ToPeriod(), ct);
|
||||
|
||||
/// <summary>Návrhy podané v období podle aktuálního skóre, počtu hlasů pro a data podání.</summary>
|
||||
[HttpGet("proposals/top")]
|
||||
public Task<IReadOnlyList<TopProposal>> GetTopProposals([FromQuery] StatisticsQuery query, CancellationToken ct,
|
||||
[FromQuery, Range(1, 100)] int limit = 10) =>
|
||||
statistics.GetTopProposalsAsync(query.ToPeriod(), limit, ct);
|
||||
}
|
||||
|
||||
public sealed class StatisticsQuery
|
||||
{
|
||||
[FromQuery(Name = "from")]
|
||||
public DateTimeOffset? From { get; init; }
|
||||
|
||||
[FromQuery(Name = "to")]
|
||||
public DateTimeOffset? To { get; init; }
|
||||
|
||||
internal StatisticsPeriod ToPeriod() => new(From, To);
|
||||
}
|
||||
@@ -1,14 +1,23 @@
|
||||
using System.Net;
|
||||
using System.Threading.RateLimiting;
|
||||
using Helpdesk.Api.Infrastructure;
|
||||
using Helpdesk.Application;
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Auth;
|
||||
using Helpdesk.Infrastructure;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.IdentityModel.JsonWebTokens;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.Services.AddApplication(builder.Configuration);
|
||||
builder.Services.AddInfrastructure(builder.Configuration);
|
||||
builder.Services.AddInfrastructure(builder.Configuration, builder.Environment);
|
||||
builder.Services.AddOptions<RegistrationOptions>()
|
||||
.Validate(options => Uri.TryCreate(options.WebBaseUrl, UriKind.Absolute, out var url) &&
|
||||
(url.Scheme == Uri.UriSchemeHttps || (builder.Environment.IsDevelopment() && url.Scheme == Uri.UriSchemeHttp)) &&
|
||||
string.IsNullOrEmpty(url.UserInfo) && string.IsNullOrEmpty(url.Query) && string.IsNullOrEmpty(url.Fragment),
|
||||
"Nastavte Registration:WebBaseUrl na veřejnou HTTPS adresu webové aplikace bez parametrů.")
|
||||
.ValidateOnStart();
|
||||
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddScoped<ICurrentUser, HttpCurrentUser>();
|
||||
@@ -21,6 +30,21 @@ builder.Services.AddProblemDetails();
|
||||
builder.Services.AddExceptionHandler<AppExceptionHandler>();
|
||||
builder.Services.AddHelpdeskSwagger();
|
||||
|
||||
var trustedProxy = builder.Configuration["ReverseProxy:TrustedIp"];
|
||||
if (!string.IsNullOrWhiteSpace(trustedProxy))
|
||||
{
|
||||
if (!IPAddress.TryParse(trustedProxy, out var proxyAddress))
|
||||
throw new InvalidOperationException("Nastavte platnou IP adresu důvěryhodné reverse proxy.");
|
||||
|
||||
builder.Services.Configure<ForwardedHeadersOptions>(options =>
|
||||
{
|
||||
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
||||
options.KnownIPNetworks.Clear();
|
||||
options.KnownProxies.Clear();
|
||||
options.KnownProxies.Add(proxyAddress);
|
||||
});
|
||||
}
|
||||
|
||||
// Ochrana přihlášení a zápisů závad proti zahlcení (kap. 10).
|
||||
builder.Services.AddRateLimiter(options =>
|
||||
{
|
||||
@@ -40,6 +64,9 @@ builder.Services.AddRateLimiter(options =>
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(trustedProxy))
|
||||
app.UseForwardedHeaders();
|
||||
|
||||
app.UseExceptionHandler();
|
||||
app.UseStatusCodePages();
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using Helpdesk.Application.Statistics;
|
||||
using Helpdesk.Domain.Auth;
|
||||
using Helpdesk.Domain.Catalogs;
|
||||
using Helpdesk.Domain.Issues;
|
||||
@@ -18,6 +19,7 @@ public interface IAppDbContext
|
||||
DbSet<ProposalCategory> ProposalCategories { get; }
|
||||
DbSet<Issue> Issues { get; }
|
||||
DbSet<IssueEvent> IssueEvents { get; }
|
||||
IQueryable<IssueTiming> IssueTimings { get; }
|
||||
DbSet<Attachment> Attachments { get; }
|
||||
DbSet<Proposal> Proposals { get; }
|
||||
DbSet<ProposalEvent> ProposalEvents { get; }
|
||||
@@ -30,6 +32,7 @@ public interface IAppDbContext
|
||||
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
|
||||
Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct);
|
||||
Task<Proposal?> LockProposalAsync(int id, CancellationToken ct);
|
||||
Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct);
|
||||
}
|
||||
|
||||
public interface IPasswordHasher
|
||||
|
||||
@@ -32,12 +32,17 @@ public sealed class AuthService(
|
||||
?? throw new BadRequestException("Registrace je možná jen s univerzitním e-mailem.");
|
||||
|
||||
var normalized = User.NormalizeEmail(request.Email);
|
||||
if (await db.Users.AnyAsync(u => u.EmailNormalized == normalized, ct))
|
||||
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
|
||||
if (user is null)
|
||||
{
|
||||
user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role);
|
||||
db.Users.Add(user);
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
else if (!user.IsActive || user.EmailConfirmed || !passwordHasher.Verify(request.Password, user.PasswordHash))
|
||||
{
|
||||
throw new ConflictException("Účet s tímto e-mailem už existuje.");
|
||||
|
||||
var user = User.Create(request.Email, passwordHasher.Hash(request.Password), request.FirstName, request.LastName, role);
|
||||
db.Users.Add(user);
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
await SendEmailTokenAsync(user, TokenType.EmailConfirm, ct);
|
||||
return UserDto.From(user);
|
||||
@@ -123,8 +128,17 @@ public sealed class AuthService(
|
||||
{
|
||||
var normalized = User.NormalizeEmail(request.Email ?? "");
|
||||
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized && u.IsActive, ct);
|
||||
if (user is not null)
|
||||
if (user is null)
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
await SendEmailTokenAsync(user, TokenType.PasswordReset, ct);
|
||||
}
|
||||
catch (EmailDeliveryException)
|
||||
{
|
||||
// SMTP zapisuje typ chyby. Odpověď na obnovu hesla zůstává pro všechny adresy stejná.
|
||||
}
|
||||
}
|
||||
|
||||
public async Task ResetPasswordAsync(ResetPasswordRequest request, CancellationToken ct)
|
||||
|
||||
@@ -12,6 +12,8 @@ public sealed record CategoryDto(int Id, string Name, string? Description, bool
|
||||
|
||||
public sealed record SaveBuildingRequest(string Code, string Name, string? Address);
|
||||
|
||||
public sealed record SaveCategoryRequest(string Name, string? Description);
|
||||
|
||||
public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildingRequest>
|
||||
{
|
||||
public SaveBuildingRequestValidator()
|
||||
@@ -22,8 +24,18 @@ public sealed class SaveBuildingRequestValidator : AbstractValidator<SaveBuildin
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class SaveCategoryRequestValidator : AbstractValidator<SaveCategoryRequest>
|
||||
{
|
||||
public SaveCategoryRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.Description).MaximumLength(500);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Číselníky pro formuláře a jejich správa administrátorem. Mazání = deaktivace.</summary>
|
||||
public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequest> buildingValidator)
|
||||
public sealed class CatalogService(
|
||||
IAppDbContext db, IValidator<SaveBuildingRequest> buildingValidator, IValidator<SaveCategoryRequest> categoryValidator)
|
||||
{
|
||||
public async Task<IReadOnlyList<BuildingDto>> GetBuildingsAsync(bool includeInactive, CancellationToken ct) =>
|
||||
await db.Buildings.AsNoTracking()
|
||||
@@ -32,16 +44,16 @@ public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequ
|
||||
.Select(b => new BuildingDto(b.Id, b.Code, b.Name, b.Address, b.IsActive))
|
||||
.ToListAsync(ct);
|
||||
|
||||
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(CancellationToken ct) =>
|
||||
public async Task<IReadOnlyList<CategoryDto>> GetIssueCategoriesAsync(bool includeInactive, CancellationToken ct) =>
|
||||
await db.IssueCategories.AsNoTracking()
|
||||
.Where(c => c.IsActive)
|
||||
.Where(c => includeInactive || c.IsActive)
|
||||
.OrderBy(c => c.Id)
|
||||
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
|
||||
.ToListAsync(ct);
|
||||
|
||||
public async Task<IReadOnlyList<CategoryDto>> GetProposalCategoriesAsync(CancellationToken ct) =>
|
||||
public async Task<IReadOnlyList<CategoryDto>> GetProposalCategoriesAsync(bool includeInactive, CancellationToken ct) =>
|
||||
await db.ProposalCategories.AsNoTracking()
|
||||
.Where(c => c.IsActive)
|
||||
.Where(c => includeInactive || c.IsActive)
|
||||
.OrderBy(c => c.Id)
|
||||
.Select(c => new CategoryDto(c.Id, c.Name, c.Description, c.IsActive))
|
||||
.ToListAsync(ct);
|
||||
@@ -75,10 +87,68 @@ public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequ
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<CategoryDto> CreateIssueCategoryAsync(SaveCategoryRequest request, CancellationToken ct)
|
||||
{
|
||||
await categoryValidator.ValidateAndThrowAsync(request, ct);
|
||||
var category = new IssueCategory(request.Name, request.Description);
|
||||
db.IssueCategories.Add(category);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return ToDto(category);
|
||||
}
|
||||
|
||||
public async Task<CategoryDto> UpdateIssueCategoryAsync(int id, SaveCategoryRequest request, CancellationToken ct)
|
||||
{
|
||||
await categoryValidator.ValidateAndThrowAsync(request, ct);
|
||||
var category = await GetIssueCategoryAsync(id, ct);
|
||||
category.Update(request.Name, request.Description);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return ToDto(category);
|
||||
}
|
||||
|
||||
public async Task DeactivateIssueCategoryAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var category = await GetIssueCategoryAsync(id, ct);
|
||||
category.Deactivate();
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<CategoryDto> CreateProposalCategoryAsync(SaveCategoryRequest request, CancellationToken ct)
|
||||
{
|
||||
await categoryValidator.ValidateAndThrowAsync(request, ct);
|
||||
var category = new ProposalCategory(request.Name, request.Description);
|
||||
db.ProposalCategories.Add(category);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return ToDto(category);
|
||||
}
|
||||
|
||||
public async Task<CategoryDto> UpdateProposalCategoryAsync(int id, SaveCategoryRequest request, CancellationToken ct)
|
||||
{
|
||||
await categoryValidator.ValidateAndThrowAsync(request, ct);
|
||||
var category = await GetProposalCategoryAsync(id, ct);
|
||||
category.Update(request.Name, request.Description);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return ToDto(category);
|
||||
}
|
||||
|
||||
public async Task DeactivateProposalCategoryAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var category = await GetProposalCategoryAsync(id, ct);
|
||||
category.Deactivate();
|
||||
await db.SaveChangesAsync(ct);
|
||||
}
|
||||
|
||||
private async Task<Building> GetBuildingAsync(int id, CancellationToken ct) =>
|
||||
await db.Buildings.SingleOrDefaultAsync(b => b.Id == id, ct)
|
||||
?? throw new NotFoundException($"Budova {id} neexistuje.");
|
||||
|
||||
private async Task<IssueCategory> GetIssueCategoryAsync(int id, CancellationToken ct) =>
|
||||
await db.IssueCategories.SingleOrDefaultAsync(c => c.Id == id, ct)
|
||||
?? throw new NotFoundException($"Kategorie závad {id} neexistuje.");
|
||||
|
||||
private async Task<ProposalCategory> GetProposalCategoryAsync(int id, CancellationToken ct) =>
|
||||
await db.ProposalCategories.SingleOrDefaultAsync(c => c.Id == id, ct)
|
||||
?? throw new NotFoundException($"Kategorie návrhů {id} neexistuje.");
|
||||
|
||||
private async Task EnsureUniqueCodeAsync(string code, int? exceptId, CancellationToken ct)
|
||||
{
|
||||
var trimmed = code.Trim();
|
||||
@@ -87,4 +157,6 @@ public sealed class CatalogService(IAppDbContext db, IValidator<SaveBuildingRequ
|
||||
}
|
||||
|
||||
private static BuildingDto ToDto(Building b) => new(b.Id, b.Code, b.Name, b.Address, b.IsActive);
|
||||
private static CategoryDto ToDto(IssueCategory c) => new(c.Id, c.Name, c.Description, c.IsActive);
|
||||
private static CategoryDto ToDto(ProposalCategory c) => new(c.Id, c.Name, c.Description, c.IsActive);
|
||||
}
|
||||
@@ -31,4 +31,12 @@ public sealed class BadRequestException(string message) : AppException(message)
|
||||
public override int StatusCode => 400;
|
||||
}
|
||||
|
||||
public sealed class EmailDeliveryException(string reason, bool retryable)
|
||||
: AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.")
|
||||
{
|
||||
public string Reason { get; } = reason;
|
||||
public bool Retryable { get; } = retryable;
|
||||
public override int StatusCode => 503;
|
||||
}
|
||||
|
||||
public sealed record PagedResult<T>(IReadOnlyList<T> Items, int TotalCount, int Page, int PageSize);
|
||||
@@ -4,6 +4,7 @@ using Helpdesk.Application.Catalogs;
|
||||
using Helpdesk.Application.Issues;
|
||||
using Helpdesk.Application.Notifications;
|
||||
using Helpdesk.Application.Proposals;
|
||||
using Helpdesk.Application.Statistics;
|
||||
using Helpdesk.Application.Users;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -23,8 +24,11 @@ public static class DependencyInjection
|
||||
services.AddScoped<CatalogService>();
|
||||
services.AddScoped<IssueService>();
|
||||
services.AddScoped<NotificationService>();
|
||||
services.AddScoped<NotificationDeliveryService>();
|
||||
services.AddScoped<NotificationWriter>();
|
||||
services.AddScoped<PushDeviceService>();
|
||||
services.AddScoped<ProposalService>();
|
||||
services.AddScoped<StatisticsService>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Domain;
|
||||
using Helpdesk.Domain.Notifications;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Helpdesk.Application.Notifications;
|
||||
|
||||
public sealed record NotificationDeliveryDto(
|
||||
int Id, int NotificationId, string Channel, string Status, int AttemptCount,
|
||||
string? LastError, DateTime? NextAttemptAt, DateTime? SentAt);
|
||||
|
||||
public sealed class NotificationDeliveryService(IAppDbContext db, TimeProvider clock)
|
||||
{
|
||||
public async Task<PagedResult<NotificationDeliveryDto>> ListAsync(string status, int page, int pageSize, CancellationToken ct)
|
||||
{
|
||||
if (!EnumCode.TryParse<DeliveryStatus>(status, out var deliveryStatus))
|
||||
throw new BadRequestException("Neplatný stav doručení.");
|
||||
|
||||
page = Math.Max(1, page);
|
||||
pageSize = Math.Clamp(pageSize, 1, 100);
|
||||
var query = db.NotificationDeliveries.AsNoTracking().Where(d => d.Status == deliveryStatus);
|
||||
var count = await query.CountAsync(ct);
|
||||
var offset = (long)(page - 1) * pageSize;
|
||||
if (offset >= count)
|
||||
return new PagedResult<NotificationDeliveryDto>([], count, page, pageSize);
|
||||
|
||||
var rows = await query.OrderByDescending(d => d.Id).Skip((int)offset).Take(pageSize).ToListAsync(ct);
|
||||
var items = rows.Select(d => new NotificationDeliveryDto(d.Id, d.NotificationId, d.Channel.ToCode(),
|
||||
d.Status.ToCode(), d.AttemptCount, d.LastError, d.NextAttemptAt, d.SentAt)).ToArray();
|
||||
return new PagedResult<NotificationDeliveryDto>(items, count, page, pageSize);
|
||||
}
|
||||
|
||||
public async Task RetryAsync(int id, CancellationToken ct)
|
||||
{
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
var delivery = db.NotificationDeliveries.Where(d => d.Id == id);
|
||||
var updated = await delivery.Where(d => d.Status == DeliveryStatus.Failed)
|
||||
.ExecuteUpdateAsync(setters => setters
|
||||
.SetProperty(d => d.Status, DeliveryStatus.Pending)
|
||||
.SetProperty(d => d.AttemptCount, 0)
|
||||
.SetProperty(d => d.NextAttemptAt, now)
|
||||
.SetProperty(d => d.LastError, (string?)null)
|
||||
.SetProperty(d => d.SentAt, (DateTime?)null), ct);
|
||||
if (updated == 1)
|
||||
return;
|
||||
|
||||
if (!await delivery.AnyAsync(ct))
|
||||
throw new NotFoundException("Doručení neexistuje.");
|
||||
|
||||
throw new ConflictException("Zopakovat lze pouze neúspěšné doručení.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Helpdesk.Application.Notifications;
|
||||
|
||||
public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser)
|
||||
{
|
||||
public Task RegisterAsync(string token, CancellationToken ct)
|
||||
{
|
||||
ValidateToken(token);
|
||||
return db.RegisterPushDeviceAsync(currentUser.Id, token, ct);
|
||||
}
|
||||
|
||||
public async Task UnregisterAsync(string token, CancellationToken ct)
|
||||
{
|
||||
ValidateToken(token);
|
||||
var userId = currentUser.Id;
|
||||
await db.PushDevices.Where(d => d.UserId == userId && d.FcmToken == token).ExecuteDeleteAsync(ct);
|
||||
}
|
||||
|
||||
private static void ValidateToken(string? token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token) || token.Length > 512 || token.Any(c => char.IsWhiteSpace(c) || char.IsControl(c)))
|
||||
throw new BadRequestException("Neplatný registrační token zařízení.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using Helpdesk.Application.Common;
|
||||
|
||||
namespace Helpdesk.Application.Statistics;
|
||||
|
||||
public sealed record StatisticsPeriod(DateTimeOffset? From, DateTimeOffset? To)
|
||||
{
|
||||
internal (DateTime? From, DateTime? To) UtcBounds()
|
||||
{
|
||||
if (From >= To)
|
||||
throw new BadRequestException("Začátek období musí předcházet jeho konci.");
|
||||
|
||||
return (From?.UtcDateTime, To?.UtcDateTime);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record IssueTiming(int IssueId, long? MicrosecondsToAssignment, long? MicrosecondsToClosure);
|
||||
|
||||
public sealed record StatisticsOverview(
|
||||
int TotalIssues, IReadOnlyDictionary<string, int> IssuesByStatus,
|
||||
decimal? AverageHoursToAssignment, decimal? AverageHoursToClosure);
|
||||
|
||||
public sealed record IssueCategoryStatistics(int CategoryId, string Name, int IssueCount, decimal? AverageHoursToResolution);
|
||||
public sealed record IssueBuildingStatistics(int? BuildingId, string? Name, int IssueCount);
|
||||
public sealed record IssueAssigneeStatistics(int AssigneeId, string Name, int OpenIssues, int ResolvedIssues, int RejectedIssues);
|
||||
public sealed record IssueTrendPoint(DateOnly Month, int CreatedIssues, int ClosedIssues);
|
||||
public sealed record TopProposal(int Id, string Title, string Status, long VotesFor, long VotesAgainst, long Score);
|
||||
@@ -0,0 +1,141 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Domain;
|
||||
using Helpdesk.Domain.Issues;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Helpdesk.Application.Statistics;
|
||||
|
||||
public sealed class StatisticsService(IAppDbContext db)
|
||||
{
|
||||
private const decimal MicrosecondsPerHour = 3_600_000_000m;
|
||||
|
||||
public async Task<StatisticsOverview> GetOverviewAsync(StatisticsPeriod period, CancellationToken ct)
|
||||
{
|
||||
var byStatus = await (
|
||||
from issue in IssuesInPeriod(period)
|
||||
join timing in db.IssueTimings on issue.Id equals timing.IssueId into timings
|
||||
from timing in timings.DefaultIfEmpty()
|
||||
group timing by issue.Status into rows
|
||||
select new
|
||||
{
|
||||
Status = rows.Key,
|
||||
Count = rows.Count(),
|
||||
AssignedCount = rows.Count(t => t.MicrosecondsToAssignment != null),
|
||||
ClosedCount = rows.Count(t => t.MicrosecondsToClosure != null),
|
||||
AssignmentTime = rows.Sum(t => (decimal?)t.MicrosecondsToAssignment),
|
||||
ClosureTime = rows.Sum(t => (decimal?)t.MicrosecondsToClosure),
|
||||
}).ToDictionaryAsync(row => row.Status, ct);
|
||||
|
||||
var counts = Enum.GetValues<IssueStatus>()
|
||||
.ToDictionary(status => status.ToCode(), status => byStatus.GetValueOrDefault(status)?.Count ?? 0);
|
||||
return new StatisticsOverview(
|
||||
counts.Values.Sum(),
|
||||
counts,
|
||||
AverageHours(byStatus.Values.Sum(row => row.AssignmentTime), byStatus.Values.Sum(row => row.AssignedCount)),
|
||||
AverageHours(byStatus.Values.Sum(row => row.ClosureTime), byStatus.Values.Sum(row => row.ClosedCount)));
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<IssueCategoryStatistics>> GetByCategoryAsync(StatisticsPeriod period, CancellationToken ct)
|
||||
{
|
||||
var groups = await (
|
||||
from issue in IssuesInPeriod(period)
|
||||
join category in db.IssueCategories on issue.CategoryId equals category.Id
|
||||
join timing in db.IssueTimings on issue.Id equals timing.IssueId into timings
|
||||
from timing in timings.DefaultIfEmpty()
|
||||
group new { issue.Status, timing.MicrosecondsToClosure } by new { category.Id, category.Name } into rows
|
||||
orderby rows.Key.Id
|
||||
select new
|
||||
{
|
||||
rows.Key.Id,
|
||||
rows.Key.Name,
|
||||
Count = rows.Count(),
|
||||
ResolutionTime = rows.Average(row => row.Status == IssueStatus.Resolved
|
||||
? (decimal?)row.MicrosecondsToClosure : null),
|
||||
}).ToListAsync(ct);
|
||||
|
||||
return groups.Select(row => new IssueCategoryStatistics(
|
||||
row.Id, row.Name, row.Count, row.ResolutionTime / MicrosecondsPerHour)).ToArray();
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<IssueBuildingStatistics>> GetByBuildingAsync(StatisticsPeriod period, CancellationToken ct) =>
|
||||
await (
|
||||
from issue in IssuesInPeriod(period)
|
||||
join building in db.Buildings on issue.BuildingId equals building.Id into buildings
|
||||
from building in buildings.DefaultIfEmpty()
|
||||
group issue by new { issue.BuildingId, building.Name } into rows
|
||||
orderby rows.Key.BuildingId
|
||||
select new IssueBuildingStatistics(rows.Key.BuildingId, rows.Key.Name, rows.Count())).ToListAsync(ct);
|
||||
|
||||
public async Task<IReadOnlyList<IssueAssigneeStatistics>> GetByAssigneeAsync(StatisticsPeriod period, CancellationToken ct) =>
|
||||
await (
|
||||
from issue in IssuesInPeriod(period)
|
||||
join assignee in db.Users on issue.AssigneeId equals assignee.Id
|
||||
group issue by new { assignee.Id, assignee.FirstName, assignee.LastName } into rows
|
||||
orderby rows.Key.LastName, rows.Key.FirstName, rows.Key.Id
|
||||
select new IssueAssigneeStatistics(
|
||||
rows.Key.Id,
|
||||
rows.Key.FirstName + " " + rows.Key.LastName,
|
||||
rows.Count(i => i.Status == IssueStatus.Assigned || i.Status == IssueStatus.InProgress ||
|
||||
i.Status == IssueStatus.PendingVerification),
|
||||
rows.Count(i => i.Status == IssueStatus.Resolved),
|
||||
rows.Count(i => i.Status == IssueStatus.Rejected))).ToListAsync(ct);
|
||||
|
||||
public async Task<IReadOnlyList<IssueTrendPoint>> GetTrendAsync(StatisticsPeriod period, CancellationToken ct)
|
||||
{
|
||||
var (from, to) = period.UtcBounds();
|
||||
var created = await CountByMonthAsync(db.Issues.Select(i => i.CreatedAt), from, to, ct);
|
||||
var closed = await CountByMonthAsync(
|
||||
db.IssueEvents.Where(e => e.EventType == IssueEventType.StatusChanged &&
|
||||
(e.ToStatus == IssueStatus.Resolved || e.ToStatus == IssueStatus.Rejected)).Select(e => e.OccurredAt),
|
||||
from, to, ct);
|
||||
|
||||
var observed = created.Keys.Concat(closed.Keys).ToArray();
|
||||
if (observed.Length == 0 && (from is null || to is null))
|
||||
return [];
|
||||
|
||||
var first = from is DateTime start ? MonthIndex(start) : observed.Min();
|
||||
var last = to is DateTime end ? MonthIndex(end.AddTicks(-1)) : observed.Max();
|
||||
var result = new List<IssueTrendPoint>();
|
||||
for (var month = first; month <= last; month++)
|
||||
{
|
||||
var date = new DateOnly(month / 12 + 1, month % 12 + 1, 1);
|
||||
result.Add(new IssueTrendPoint(date, created.GetValueOrDefault(month), closed.GetValueOrDefault(month)));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<TopProposal>> GetTopProposalsAsync(StatisticsPeriod period, int limit, CancellationToken ct)
|
||||
{
|
||||
var (start, end) = period.UtcBounds();
|
||||
var top = await (
|
||||
from proposal in db.Proposals
|
||||
where (start == null || proposal.CreatedAt >= start) && (end == null || proposal.CreatedAt < end)
|
||||
join score in db.ProposalScores on proposal.Id equals score.ProposalId
|
||||
orderby score.Score descending, score.VotesFor descending, proposal.CreatedAt, proposal.Id
|
||||
select new { proposal.Id, proposal.Title, proposal.Status, score.VotesFor, score.VotesAgainst, score.Score })
|
||||
.Take(limit).ToListAsync(ct);
|
||||
|
||||
return top.Select(row => new TopProposal(row.Id, row.Title, row.Status.ToCode(),
|
||||
(long)row.VotesFor, (long)row.VotesAgainst, (long)row.Score)).ToArray();
|
||||
}
|
||||
|
||||
private IQueryable<Issue> IssuesInPeriod(StatisticsPeriod period)
|
||||
{
|
||||
var (from, to) = period.UtcBounds();
|
||||
return db.Issues.Where(i => (from == null || i.CreatedAt >= from) && (to == null || i.CreatedAt < to));
|
||||
}
|
||||
|
||||
private static Task<Dictionary<int, int>> CountByMonthAsync(
|
||||
IQueryable<DateTime> dates, DateTime? from, DateTime? to, CancellationToken ct) =>
|
||||
dates.Where(date => (from == null || date >= from) && (to == null || date < to))
|
||||
.GroupBy(date => (date.Year - 1) * 12 + date.Month - 1)
|
||||
.Select(rows => new { Month = rows.Key, Count = rows.Count() })
|
||||
.ToDictionaryAsync(row => row.Month, row => row.Count, ct);
|
||||
|
||||
private static int MonthIndex(DateTime date) => (date.Year - 1) * 12 + date.Month - 1;
|
||||
|
||||
private static decimal? AverageHours(decimal? microseconds, int count) =>
|
||||
count == 0 ? null : microseconds / count / MicrosecondsPerHour;
|
||||
}
|
||||
@@ -31,10 +31,20 @@ public sealed class IssueCategory
|
||||
{
|
||||
private IssueCategory() { } // EF Core
|
||||
|
||||
public IssueCategory(string name, string? description) => Update(name, description);
|
||||
|
||||
public int Id { get; private set; }
|
||||
public string Name { get; private set; } = null!;
|
||||
public string? Description { get; private set; }
|
||||
public bool IsActive { get; private set; } = true;
|
||||
|
||||
public void Update(string name, string? description)
|
||||
{
|
||||
Name = name.Trim();
|
||||
Description = string.IsNullOrWhiteSpace(description) ? null : description.Trim();
|
||||
}
|
||||
|
||||
public void Deactivate() => IsActive = false;
|
||||
}
|
||||
|
||||
/// <summary>Oblast návrhu na zlepšení (tabulka <c>proposal_category</c>).</summary>
|
||||
@@ -42,8 +52,18 @@ public sealed class ProposalCategory
|
||||
{
|
||||
private ProposalCategory() { } // EF Core
|
||||
|
||||
public ProposalCategory(string name, string? description) => Update(name, description);
|
||||
|
||||
public int Id { get; private set; }
|
||||
public string Name { get; private set; } = null!;
|
||||
public string? Description { get; private set; }
|
||||
public bool IsActive { get; private set; } = true;
|
||||
|
||||
public void Update(string name, string? description)
|
||||
{
|
||||
Name = name.Trim();
|
||||
Description = string.IsNullOrWhiteSpace(description) ? null : description.Trim();
|
||||
}
|
||||
|
||||
public void Deactivate() => IsActive = false;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ namespace Helpdesk.Domain.Notifications;
|
||||
|
||||
public enum NotificationType { IssueCreated, IssueAssigned, IssueStatusChanged, IssueCommentAdded, IssueReopened, ProposalStatusChanged }
|
||||
public enum DeliveryChannel { Email, Push }
|
||||
public enum DeliveryStatus { Pending, Skipped }
|
||||
public enum DeliveryStatus { Pending, Sent, Failed, Skipped }
|
||||
|
||||
public sealed class Notification : IHasCreatedAt
|
||||
{
|
||||
@@ -46,6 +46,9 @@ public sealed class Notification : IHasCreatedAt
|
||||
public sealed class NotificationDelivery(
|
||||
Notification notification, DeliveryChannel channel, bool enabled, DateTime now)
|
||||
{
|
||||
private static readonly TimeSpan[] RetryDelays =
|
||||
[TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(30), TimeSpan.FromHours(2)];
|
||||
|
||||
private NotificationDelivery() : this(null!, default, false, default) { }
|
||||
|
||||
public int Id { get; private set; }
|
||||
@@ -53,11 +56,45 @@ public sealed class NotificationDelivery(
|
||||
public Notification Notification { get; private set; } = notification;
|
||||
public DeliveryChannel Channel { get; private set; } = channel;
|
||||
public DeliveryStatus Status { get; private set; } = enabled ? DeliveryStatus.Pending : DeliveryStatus.Skipped;
|
||||
public int AttemptCount { get; private set; }
|
||||
public DateTime? NextAttemptAt { get; private set; } = enabled ? now : null;
|
||||
public string? LastError { get; private set; }
|
||||
public DateTime? SentAt { get; private set; }
|
||||
|
||||
public void RecordSent(DateTime now)
|
||||
{
|
||||
AttemptCount++;
|
||||
Status = DeliveryStatus.Sent;
|
||||
SentAt = now;
|
||||
NextAttemptAt = null;
|
||||
LastError = null;
|
||||
}
|
||||
|
||||
public void RecordFailure(DateTime now, string reason, bool retryable)
|
||||
{
|
||||
AttemptCount++;
|
||||
LastError = reason;
|
||||
if (retryable && AttemptCount <= RetryDelays.Length)
|
||||
{
|
||||
NextAttemptAt = now + RetryDelays[AttemptCount - 1];
|
||||
return;
|
||||
}
|
||||
|
||||
Status = DeliveryStatus.Failed;
|
||||
NextAttemptAt = null;
|
||||
}
|
||||
|
||||
public void Skip()
|
||||
{
|
||||
Status = DeliveryStatus.Skipped;
|
||||
NextAttemptAt = null;
|
||||
LastError = null;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PushDevice
|
||||
{
|
||||
public int Id { get; private set; }
|
||||
public int UserId { get; private set; }
|
||||
public string FcmToken { get; private set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using System.Data;
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Domain.Notifications;
|
||||
using Helpdesk.Infrastructure.Email;
|
||||
using Helpdesk.Infrastructure.Notifications;
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Background;
|
||||
|
||||
internal sealed partial class NotificationDispatcher(
|
||||
IServiceScopeFactory scopes, IEmailSender email, TimeProvider clock, ILogger<NotificationDispatcher> logger,
|
||||
FirebasePushSender? push = null) : BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(2);
|
||||
private readonly bool emailEnabled = email is not LoggingEmailSender;
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (!emailEnabled && push is null)
|
||||
return;
|
||||
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (await DeliverNextAsync(stoppingToken))
|
||||
continue;
|
||||
}
|
||||
catch (Exception failure) when (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
LogDispatchFailure(failure.GetType().Name);
|
||||
}
|
||||
|
||||
await Task.Delay(PollInterval, clock, stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> DeliverNextAsync(CancellationToken ct)
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||
await using var transaction = await db.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
var rows = await db.NotificationDeliveries.FromSql($"""
|
||||
SELECT * FROM notification_delivery
|
||||
WHERE status = 'PENDING' AND next_attempt_at <= {now}
|
||||
AND (({emailEnabled} AND channel = 'EMAIL') OR ({push is not null} AND channel = 'PUSH'))
|
||||
ORDER BY next_attempt_at, id LIMIT 1 FOR UPDATE SKIP LOCKED
|
||||
""").ToListAsync(ct);
|
||||
if (rows.SingleOrDefault() is not { } delivery)
|
||||
return false;
|
||||
|
||||
var recipient = await (
|
||||
from notification in db.Notifications.AsNoTracking()
|
||||
join user in db.Users on notification.UserId equals user.Id
|
||||
where notification.Id == delivery.NotificationId
|
||||
select new { Notification = notification, user.Id, user.Email, user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled }
|
||||
).SingleAsync(ct);
|
||||
|
||||
if (!recipient.IsActive)
|
||||
delivery.Skip();
|
||||
else if (delivery.Channel == DeliveryChannel.Email)
|
||||
{
|
||||
if (recipient.EmailConfirmed && recipient.EmailNotificationsEnabled)
|
||||
await SendEmailAsync(delivery, recipient.Notification, recipient.Email, ct);
|
||||
else
|
||||
delivery.Skip();
|
||||
}
|
||||
else
|
||||
{
|
||||
await SendPushAsync(db, delivery, recipient.Notification, recipient.Id, ct);
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task SendEmailAsync(NotificationDelivery delivery, Notification notification, string address, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
await email.SendAsync(address, notification.Title, notification.Message, ct);
|
||||
delivery.RecordSent(clock.GetUtcNow().UtcDateTime);
|
||||
}
|
||||
catch (EmailDeliveryException failure)
|
||||
{
|
||||
delivery.RecordFailure(clock.GetUtcNow().UtcDateTime, failure.Reason, failure.Retryable);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendPushAsync(
|
||||
HelpdeskDbContext db, NotificationDelivery delivery, Notification notification, int userId, CancellationToken ct)
|
||||
{
|
||||
var devices = db.PushDevices.Where(d => d.UserId == userId);
|
||||
var tokens = await devices.Select(d => d.FcmToken).ToArrayAsync(ct);
|
||||
if (tokens.Length == 0)
|
||||
{
|
||||
delivery.Skip();
|
||||
return;
|
||||
}
|
||||
|
||||
var result = await push!.SendAsync(notification, tokens, ct);
|
||||
foreach (var invalidToken in result.InvalidTokens)
|
||||
await devices.Where(d => d.FcmToken == invalidToken).ExecuteDeleteAsync(ct);
|
||||
|
||||
var now = clock.GetUtcNow().UtcDateTime;
|
||||
if (result.Sent)
|
||||
delivery.RecordSent(now);
|
||||
else
|
||||
delivery.RecordFailure(now, result.FailureReason, result.Retryable);
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Zpracování notifikační fronty selhalo ({FailureType}).")]
|
||||
private partial void LogDispatchFailure(string failureType);
|
||||
}
|
||||
@@ -3,17 +3,21 @@ using Helpdesk.Application.Issues;
|
||||
using Helpdesk.Infrastructure.Background;
|
||||
using Helpdesk.Infrastructure.Email;
|
||||
using Helpdesk.Infrastructure.Files;
|
||||
using Helpdesk.Infrastructure.Notifications;
|
||||
using Helpdesk.Infrastructure.Persistence;
|
||||
using Helpdesk.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using MimeKit;
|
||||
|
||||
namespace Helpdesk.Infrastructure;
|
||||
|
||||
public static class DependencyInjection
|
||||
{
|
||||
public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
|
||||
public static IServiceCollection AddInfrastructure(
|
||||
this IServiceCollection services, IConfiguration configuration, IHostEnvironment environment)
|
||||
{
|
||||
var connectionString = configuration.GetConnectionString("Helpdesk")
|
||||
?? throw new InvalidOperationException("Chybí připojovací řetězec ConnectionStrings:Helpdesk.");
|
||||
@@ -33,12 +37,37 @@ public static class DependencyInjection
|
||||
services.AddSingleton<IPasswordHasher, BCryptPasswordHasher>();
|
||||
services.AddSingleton<ITokenService, JwtTokenService>();
|
||||
services.AddSingleton<IRevokedTokenStore, RevokedTokenStore>();
|
||||
services.AddSingleton<IEmailSender, LoggingEmailSender>();
|
||||
AddEmailSender(services, configuration.GetSection("Smtp"), environment);
|
||||
var firebaseCredentials = configuration["Firebase:ServiceAccountJson"];
|
||||
if (!string.IsNullOrWhiteSpace(firebaseCredentials))
|
||||
services.AddSingleton(_ => FirebasePushSender.Create(firebaseCredentials));
|
||||
services.AddSingleton<IAttachmentStore, FileAttachmentStore>();
|
||||
|
||||
services.AddHostedService<RevokedTokenStoreLoader>();
|
||||
services.AddHostedService<AdminSeeder>();
|
||||
services.AddHostedService<AuthTokenCleanupService>();
|
||||
services.AddHostedService<NotificationDispatcher>();
|
||||
return services;
|
||||
}
|
||||
|
||||
private static void AddEmailSender(IServiceCollection services, IConfigurationSection configuration, IHostEnvironment environment)
|
||||
{
|
||||
if (environment.IsDevelopment() && string.IsNullOrWhiteSpace(configuration["Mailbox"]) &&
|
||||
string.IsNullOrWhiteSpace(configuration["Password"]))
|
||||
{
|
||||
services.AddSingleton<IEmailSender, LoggingEmailSender>();
|
||||
return;
|
||||
}
|
||||
|
||||
services.AddOptions<SmtpOptions>()
|
||||
.Bind(configuration)
|
||||
.Validate(options => !string.IsNullOrWhiteSpace(options.Host) && options.Port is >= 1 and <= 65535,
|
||||
"Nastavte platný SMTP server a port.")
|
||||
.Validate(options => MailboxAddress.TryParse(options.Mailbox, out var mailbox) &&
|
||||
mailbox.Address == options.Mailbox && mailbox.Address.Contains('@'),
|
||||
"Nastavte celou e-mailovou adresu SMTP schránky.")
|
||||
.Validate(options => !string.IsNullOrWhiteSpace(options.Password), "Nastavte heslo SMTP schránky.")
|
||||
.ValidateOnStart();
|
||||
services.AddSingleton<IEmailSender, SmtpEmailSender>();
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,19 @@
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Email;
|
||||
|
||||
/// <summary>
|
||||
/// Vývojová náhrada odesílání e-mailů – obsah zapíše do logu (odkaz pro ověření e-mailu je tak vidět
|
||||
/// v <c>docker compose logs api</c>). Odesílání přes SMTP (MailKit + Mailpit) přijde s notifikacemi.
|
||||
/// Vývojová náhrada odesílání e-mailů, pokud schránka SMTP není nakonfigurována.
|
||||
/// </summary>
|
||||
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger, IHostEnvironment environment) : IEmailSender
|
||||
internal sealed partial class LoggingEmailSender(ILogger<LoggingEmailSender> logger) : IEmailSender
|
||||
{
|
||||
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (environment.IsDevelopment())
|
||||
LogEmail(to, subject, body);
|
||||
else
|
||||
LogMissingTransport();
|
||||
LogEmail(to, subject, body);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "E-mail pro {To} – {Subject}:\n{Body}")]
|
||||
private partial void LogEmail(string to, string subject, string body);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "E-mail nebyl odeslán. Pro toto prostředí není nakonfigurován poštovní transport.")]
|
||||
private partial void LogMissingTransport();
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Net.Sockets;
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using MailKit;
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MimeKit;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Email;
|
||||
|
||||
internal sealed class SmtpOptions
|
||||
{
|
||||
public string Host { get; set; } = "smtp.seznam.cz";
|
||||
public int Port { get; set; } = 465;
|
||||
public string Mailbox { get; set; } = "";
|
||||
public string Password { get; set; } = "";
|
||||
}
|
||||
|
||||
internal sealed partial class SmtpEmailSender(IOptions<SmtpOptions> options, ILogger<SmtpEmailSender> logger) : IEmailSender
|
||||
{
|
||||
public async Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!MailboxAddress.TryParse(to, out var recipient))
|
||||
{
|
||||
LogDeliveryFailure("InvalidRecipient");
|
||||
throw new EmailDeliveryException("SMTP_INVALID_RECIPIENT", retryable: false);
|
||||
}
|
||||
|
||||
var settings = options.Value;
|
||||
using var message = new MimeMessage { Subject = subject, Body = new TextPart("plain") { Text = body } };
|
||||
message.From.Add(MailboxAddress.Parse(settings.Mailbox));
|
||||
message.To.Add(recipient);
|
||||
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
using var client = new SmtpClient();
|
||||
try
|
||||
{
|
||||
await client.ConnectAsync(settings.Host, settings.Port, SecureSocketOptions.SslOnConnect, timeout.Token);
|
||||
await client.AuthenticateAsync(settings.Mailbox, settings.Password, timeout.Token);
|
||||
await client.SendAsync(message, timeout.Token);
|
||||
}
|
||||
catch (Exception exception) when (!cancellationToken.IsCancellationRequested &&
|
||||
exception is (IOException or SocketException or CommandException or ProtocolException or
|
||||
AuthenticationException or SslHandshakeException or NotSupportedException or TimeoutException or
|
||||
OperationCanceledException))
|
||||
{
|
||||
LogDeliveryFailure(exception.GetType().Name);
|
||||
if (exception is SmtpCommandException command)
|
||||
{
|
||||
var status = (int)command.StatusCode;
|
||||
throw new EmailDeliveryException($"SMTP_{status}", retryable: status is < 500 or >= 600);
|
||||
}
|
||||
|
||||
throw new EmailDeliveryException($"SMTP_{exception.GetType().Name}", retryable: true);
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Doručení e-mailu přes SMTP selhalo ({FailureType}).")]
|
||||
private partial void LogDeliveryFailure(string failureType);
|
||||
}
|
||||
@@ -10,6 +10,8 @@
|
||||
<PackageReference Include="MySqlConnector" />
|
||||
<PackageReference Include="EFCore.NamingConventions" />
|
||||
<PackageReference Include="BCrypt.Net-Next" />
|
||||
<PackageReference Include="MailKit" />
|
||||
<PackageReference Include="FirebaseAdmin" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using FirebaseAdmin;
|
||||
using FirebaseAdmin.Messaging;
|
||||
using Google.Apis.Auth.OAuth2;
|
||||
using Google.Apis.Auth.OAuth2.Responses;
|
||||
using Helpdesk.Domain;
|
||||
using Notification = Helpdesk.Domain.Notifications.Notification;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Notifications;
|
||||
|
||||
internal sealed record PushDeliveryResult(bool Sent, bool Retryable, string FailureReason, IReadOnlyList<string> InvalidTokens);
|
||||
|
||||
internal sealed class FirebasePushSender(FirebaseApp app) : IDisposable
|
||||
{
|
||||
public static FirebasePushSender Create(string serviceAccountJson)
|
||||
{
|
||||
ServiceAccountCredential credential;
|
||||
try
|
||||
{
|
||||
credential = CredentialFactory.FromJson<ServiceAccountCredential>(serviceAccountJson);
|
||||
}
|
||||
catch (Exception exception) when (
|
||||
exception is ArgumentException or InvalidOperationException or CryptographicException or Newtonsoft.Json.JsonException)
|
||||
{
|
||||
throw new InvalidOperationException("Nastavte platný JSON klíče servisního účtu Firebase.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(credential.ProjectId))
|
||||
throw new InvalidOperationException("Klíč servisního účtu Firebase musí obsahovat project_id.");
|
||||
|
||||
var app = FirebaseApp.Create(new AppOptions
|
||||
{
|
||||
Credential = credential.ToGoogleCredential(),
|
||||
ProjectId = credential.ProjectId,
|
||||
});
|
||||
return new FirebasePushSender(app);
|
||||
}
|
||||
|
||||
public async Task<PushDeliveryResult> SendAsync(Notification notification, string[] tokens, CancellationToken ct)
|
||||
{
|
||||
var data = new Dictionary<string, string>
|
||||
{
|
||||
["notificationId"] = notification.Id.ToString(CultureInfo.InvariantCulture),
|
||||
};
|
||||
if (notification.IssueId is int issueId)
|
||||
data["issueId"] = issueId.ToString(CultureInfo.InvariantCulture);
|
||||
if (notification.ProposalId is int proposalId)
|
||||
data["proposalId"] = proposalId.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
var messaging = FirebaseMessaging.GetMessaging(app);
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
var invalidTokens = new List<string>();
|
||||
var sent = false;
|
||||
var retryable = false;
|
||||
var reason = "FCM_NO_ACCEPTED_DEVICE";
|
||||
|
||||
foreach (var batch in tokens.Chunk(500))
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await messaging.SendEachForMulticastAsync(new MulticastMessage
|
||||
{
|
||||
#pragma warning disable CS0618 // API zařízení podle návrhu přijímá registrační tokeny FCM.
|
||||
Tokens = batch,
|
||||
#pragma warning restore CS0618
|
||||
Notification = new FirebaseAdmin.Messaging.Notification
|
||||
{
|
||||
Title = notification.Title,
|
||||
Body = notification.Message,
|
||||
},
|
||||
Data = data,
|
||||
}, timeout.Token);
|
||||
|
||||
sent |= result.SuccessCount > 0;
|
||||
for (var i = 0; i < result.Responses.Count; i++)
|
||||
{
|
||||
if (result.Responses[i].Exception is not { } failure)
|
||||
continue;
|
||||
if (IsInvalidToken(failure))
|
||||
invalidTokens.Add(batch[i]);
|
||||
|
||||
if (!retryable)
|
||||
reason = FailureReason(failure);
|
||||
retryable |= IsRetryable(failure);
|
||||
}
|
||||
}
|
||||
catch (FirebaseMessagingException failure)
|
||||
{
|
||||
if (!retryable)
|
||||
reason = FailureReason(failure);
|
||||
retryable |= IsRetryable(failure);
|
||||
}
|
||||
catch (TokenResponseException)
|
||||
{
|
||||
return new PushDeliveryResult(sent, true, "FCM_AUTHENTICATION_FAILED", invalidTokens);
|
||||
}
|
||||
catch (Exception failure) when (!ct.IsCancellationRequested &&
|
||||
failure is HttpRequestException or IOException or OperationCanceledException)
|
||||
{
|
||||
return new PushDeliveryResult(sent, true, $"FCM_{failure.GetType().Name}", invalidTokens);
|
||||
}
|
||||
}
|
||||
|
||||
return new PushDeliveryResult(sent, retryable, reason, invalidTokens);
|
||||
}
|
||||
|
||||
private static bool IsInvalidToken(FirebaseMessagingException failure) =>
|
||||
failure.MessagingErrorCode == MessagingErrorCode.Unregistered ||
|
||||
(failure.MessagingErrorCode == MessagingErrorCode.InvalidArgument &&
|
||||
failure.Message.Contains("registration token", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static bool IsRetryable(FirebaseMessagingException failure) =>
|
||||
failure.MessagingErrorCode is MessagingErrorCode.Unavailable or MessagingErrorCode.Internal or MessagingErrorCode.QuotaExceeded ||
|
||||
failure.ErrorCode is ErrorCode.Unavailable or ErrorCode.Internal or ErrorCode.ResourceExhausted or ErrorCode.DeadlineExceeded;
|
||||
|
||||
private static string FailureReason(FirebaseMessagingException failure) =>
|
||||
$"FCM_{failure.MessagingErrorCode?.ToCode() ?? failure.ErrorCode.ToCode()}";
|
||||
|
||||
public void Dispose() => app.Delete();
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Data;
|
||||
using Helpdesk.Application.Abstractions;
|
||||
using Helpdesk.Application.Common;
|
||||
using Helpdesk.Application.Statistics;
|
||||
using Helpdesk.Domain.Auth;
|
||||
using Helpdesk.Domain.Catalogs;
|
||||
using Helpdesk.Domain.Issues;
|
||||
@@ -10,6 +12,7 @@ using Helpdesk.Infrastructure.Security;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using MySqlConnector;
|
||||
|
||||
namespace Helpdesk.Infrastructure.Persistence;
|
||||
|
||||
@@ -27,6 +30,7 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
||||
public DbSet<ProposalCategory> ProposalCategories => Set<ProposalCategory>();
|
||||
public DbSet<Issue> Issues => Set<Issue>();
|
||||
public DbSet<IssueEvent> IssueEvents => Set<IssueEvent>();
|
||||
public IQueryable<IssueTiming> IssueTimings => Set<IssueTiming>();
|
||||
public DbSet<Attachment> Attachments => Set<Attachment>();
|
||||
public DbSet<Proposal> Proposals => Set<Proposal>();
|
||||
public DbSet<ProposalEvent> ProposalEvents => Set<ProposalEvent>();
|
||||
@@ -36,6 +40,20 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
||||
public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>();
|
||||
public DbSet<PushDevice> PushDevices => Set<PushDevice>();
|
||||
|
||||
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await base.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (DbUpdateException exception) when (
|
||||
exception.InnerException is MySqlException { ErrorCode: MySqlErrorCode.DuplicateKeyEntry } &&
|
||||
exception.Entries is [var entry] && entry.Entity is (IssueCategory or ProposalCategory))
|
||||
{
|
||||
throw new ConflictException("Kategorie se stejným názvem již existuje.");
|
||||
}
|
||||
}
|
||||
|
||||
public Task<IDbContextTransaction> BeginProposalWriteAsync(CancellationToken ct) =>
|
||||
Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
|
||||
|
||||
@@ -55,6 +73,12 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
||||
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new IssueConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new IssueEventConfiguration());
|
||||
modelBuilder.Entity<IssueTiming>().HasNoKey().ToSqlQuery("""
|
||||
SELECT issue_id,
|
||||
TIMESTAMPDIFF(MICROSECOND, created_at, first_assigned_at) AS microseconds_to_assignment,
|
||||
TIMESTAMPDIFF(MICROSECOND, created_at, closed_at) AS microseconds_to_closure
|
||||
FROM v_issue_lifecycle
|
||||
""");
|
||||
modelBuilder.ApplyConfiguration(new AttachmentConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new ProposalConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new ProposalEventConfiguration());
|
||||
@@ -62,9 +86,18 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
|
||||
modelBuilder.Entity<ProposalScore>().HasNoKey().ToView("v_proposal_score");
|
||||
modelBuilder.ApplyConfiguration(new NotificationConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new NotificationDeliveryConfiguration());
|
||||
modelBuilder.Entity<PushDevice>().ToTable("push_device");
|
||||
var pushDevice = modelBuilder.Entity<PushDevice>();
|
||||
pushDevice.ToTable("push_device");
|
||||
pushDevice.Property(x => x.FcmToken).HasMaxLength(512);
|
||||
pushDevice.HasIndex(x => x.FcmToken).IsUnique();
|
||||
}
|
||||
|
||||
public Task RegisterPushDeviceAsync(int userId, string token, CancellationToken ct) =>
|
||||
Database.ExecuteSqlInterpolatedAsync($"""
|
||||
INSERT INTO push_device (user_id, fcm_token) VALUES ({userId}, {token})
|
||||
ON DUPLICATE KEY UPDATE user_id = VALUES(user_id)
|
||||
""", ct);
|
||||
|
||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
|
||||
{
|
||||
// Všechny časy jsou v DB v UTC; při čtení jim nastavíme Kind = Utc, aby se v JSON serializovaly se "Z".
|
||||
|
||||
@@ -73,6 +73,7 @@ internal sealed class NotificationDeliveryConfiguration : IEntityTypeConfigurati
|
||||
b.ToTable("notification_delivery");
|
||||
b.Property(x => x.Channel).HasConversion<EnumCodeConverter<DeliveryChannel>>().HasMaxLength(10);
|
||||
b.Property(x => x.Status).HasConversion<EnumCodeConverter<DeliveryStatus>>().HasMaxLength(10);
|
||||
b.Property(x => x.LastError).HasMaxLength(1000);
|
||||
b.HasOne(x => x.Notification).WithMany().HasForeignKey(x => x.NotificationId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Registrační token FCM rozlišuje velikost písmen.
|
||||
ALTER TABLE push_device
|
||||
MODIFY fcm_token VARCHAR(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL;
|
||||
+26
-2
@@ -11,10 +11,34 @@ APP_DB_PASSWORD=change-me-app
|
||||
JWT_SIGNING_KEY=change-me-to-a-random-string-of-at-least-32-bytes
|
||||
ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||
|
||||
# Účet administrátora – vytvoří se při prvním startu API, pokud neexistuje.
|
||||
ADMIN_EMAIL=admin@univerzita.cz
|
||||
# Volitelný účet administrátora vytvořený při prvním startu API.
|
||||
ADMIN_EMAIL=admin@domain.local
|
||||
ADMIN_PASSWORD=change-me-admin
|
||||
|
||||
# HTTP adresa a port API na hostiteli, kam se reverse proxy připojuje.
|
||||
# Loopback použijte pro reverse proxy běžící přímo na stejném hostiteli.
|
||||
PROXY_UPSTREAM_BIND_ADDRESS=127.0.0.1
|
||||
API_HTTP_PORT=8080
|
||||
# Adresa reverse proxy tak, jak ji API vidí jako bezprostředního klienta.
|
||||
TRUSTED_REVERSE_PROXY_IP=
|
||||
|
||||
# Veřejná HTTPS adresa webu pro odkazy v e-mailech a povolené univerzitní domény.
|
||||
PUBLIC_BASE_URL= #https://helpdesk.domain.local
|
||||
STUDENT_EMAIL_DOMAIN= #student.domain.local
|
||||
TEACHER_EMAIL_DOMAIN= #domain.local
|
||||
|
||||
# Email Profi. V Production vyplňte celou adresu schránky a její heslo.
|
||||
SMTP_HOST=smtp.seznam.cz
|
||||
SMTP_PORT=465
|
||||
SMTP_MAILBOX=
|
||||
# Jednoduché uvozovky zachovají ve skutečném hesle např. znak $.
|
||||
SMTP_PASSWORD=''
|
||||
|
||||
# Jednořádkový JSON klíče servisního účtu Firebase v jednoduchých uvozovkách.
|
||||
FIREBASE_SERVICE_ACCOUNT_JSON=''
|
||||
|
||||
# Development = bez proxy
|
||||
# Production = s reverse proxy
|
||||
ASPNETCORE_ENVIRONMENT=Development
|
||||
|
||||
API_PORT=8080
|
||||
@@ -0,0 +1,2 @@
|
||||
FROM mariadb:11.4
|
||||
COPY --chmod=0644 01-accounts.sh /docker-entrypoint-initdb.d/01-accounts.sh
|
||||
@@ -1,11 +1,11 @@
|
||||
# Vývojové spuštění backendu: docker compose -f deploy/docker-compose.yml --env-file deploy/.env up --build
|
||||
# Topologie odpovídá kap. 15 návrhu; proxy (nginx + HTTPS), web a mailpit přibudou v dalších fázích.
|
||||
# Reverse proxy ukončuje HTTPS a připojuje se k API přes HTTP.
|
||||
|
||||
name: helpdesk
|
||||
|
||||
services:
|
||||
db:
|
||||
image: mariadb:11.4
|
||||
build: ./db-init
|
||||
environment:
|
||||
MARIADB_ROOT_PASSWORD: ${DB_ROOT_PASSWORD:?}
|
||||
MARIADB_DATABASE: helpdesk
|
||||
@@ -14,7 +14,6 @@ services:
|
||||
APP_DB_PASSWORD: ${APP_DB_PASSWORD:?}
|
||||
volumes:
|
||||
- db-data:/var/lib/mysql
|
||||
- ./db-init:/docker-entrypoint-initdb.d:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
|
||||
interval: 5s
|
||||
@@ -44,6 +43,15 @@ services:
|
||||
ConnectionStrings__Helpdesk: "Server=db;Database=helpdesk;User=helpdesk_app;Password=${APP_DB_PASSWORD}"
|
||||
Jwt__SigningKey: ${JWT_SIGNING_KEY:?}
|
||||
Encryption__Key: ${ENCRYPTION_KEY:?}
|
||||
Registration__WebBaseUrl: ${PUBLIC_BASE_URL:-https://helpdesk.localhost}
|
||||
Registration__StudentEmailDomains__0: ${STUDENT_EMAIL_DOMAIN:-student.univerzita.cz}
|
||||
Registration__TeacherEmailDomains__0: ${TEACHER_EMAIL_DOMAIN:-univerzita.cz}
|
||||
Smtp__Host: ${SMTP_HOST:-smtp.seznam.cz}
|
||||
Smtp__Port: ${SMTP_PORT:-465}
|
||||
Smtp__Mailbox: ${SMTP_MAILBOX:-}
|
||||
Smtp__Password: ${SMTP_PASSWORD:-}
|
||||
Firebase__ServiceAccountJson: ${FIREBASE_SERVICE_ACCOUNT_JSON:-}
|
||||
ReverseProxy__TrustedIp: ${TRUSTED_REVERSE_PROXY_IP:-}
|
||||
ADMIN_EMAIL: ${ADMIN_EMAIL:-}
|
||||
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
||||
volumes:
|
||||
@@ -51,9 +59,8 @@ services:
|
||||
depends_on:
|
||||
migrator:
|
||||
condition: service_completed_successfully
|
||||
# Dočasně publikováno přímo; po přidání nginx proxy bude API dostupné jen přes ni.
|
||||
ports:
|
||||
- "8080:8080"
|
||||
- "${PROXY_UPSTREAM_BIND_ADDRESS:-127.0.0.1}:${API_HTTP_PORT:-8080}:8080"
|
||||
networks: [frontend, backend]
|
||||
|
||||
networks:
|
||||
|
||||
Reference in new issue
Block a user