diff --git a/backend/src/Helpdesk.Api/Controllers/StatisticsController.cs b/backend/src/Helpdesk.Api/Controllers/StatisticsController.cs
new file mode 100644
index 0000000..dbc8e4d
--- /dev/null
+++ b/backend/src/Helpdesk.Api/Controllers/StatisticsController.cs
@@ -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;
+
+/// Statistiky pro vedení školy. Období v UTC zahrnuje začátek a vylučuje konec.
+[ApiController]
+[Authorize(Roles = Roles.Management)]
+[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
+[Route("api/statistics")]
+[ProducesResponseType(StatusCodes.Status400BadRequest)]
+[ProducesResponseType(StatusCodes.Status401Unauthorized)]
+[ProducesResponseType(StatusCodes.Status403Forbidden)]
+public sealed class StatisticsController(StatisticsService statistics) : ControllerBase
+{
+ /// Počty podle aktuálního stavu a průměrné časy pro závady nahlášené v období.
+ [HttpGet("overview")]
+ public Task GetOverview([FromQuery] StatisticsQuery query, CancellationToken ct) =>
+ statistics.GetOverviewAsync(query.ToPeriod(), ct);
+
+ /// Počty nahlášených závad a průměrná doba vyřešení podle kategorie.
+ [HttpGet("issues/by-category")]
+ public Task> GetByCategory([FromQuery] StatisticsQuery query, CancellationToken ct) =>
+ statistics.GetByCategoryAsync(query.ToPeriod(), ct);
+
+ /// Počty nahlášených závad podle budovy včetně závad bez budovy.
+ [HttpGet("issues/by-building")]
+ public Task> GetByBuilding([FromQuery] StatisticsQuery query, CancellationToken ct) =>
+ statistics.GetByBuildingAsync(query.ToPeriod(), ct);
+
+ /// Otevřené, vyřešené a zamítnuté závady podle aktuálního řešitele.
+ [HttpGet("issues/by-assignee")]
+ public Task> GetByAssignee([FromQuery] StatisticsQuery query, CancellationToken ct) =>
+ statistics.GetByAssigneeAsync(query.ToPeriod(), ct);
+
+ /// Počty vytvoření a uzavření závad po měsících podle data události.
+ [HttpGet("issues/trend")]
+ public Task> GetTrend([FromQuery] StatisticsQuery query, CancellationToken ct,
+ [FromQuery, AllowedValues("month")] string granularity = "month") =>
+ statistics.GetTrendAsync(query.ToPeriod(), ct);
+
+ /// Návrhy podané v období podle aktuálního skóre, počtu hlasů pro a data podání.
+ [HttpGet("proposals/top")]
+ public Task> 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);
+}
diff --git a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs
index 81f767d..abcdb58 100644
--- a/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs
+++ b/backend/src/Helpdesk.Application/Abstractions/Abstractions.cs
@@ -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 ProposalCategories { get; }
DbSet Issues { get; }
DbSet IssueEvents { get; }
+ IQueryable IssueTimings { get; }
DbSet Attachments { get; }
DbSet Proposals { get; }
DbSet ProposalEvents { get; }
diff --git a/backend/src/Helpdesk.Application/DependencyInjection.cs b/backend/src/Helpdesk.Application/DependencyInjection.cs
index 462c29b..290ea91 100644
--- a/backend/src/Helpdesk.Application/DependencyInjection.cs
+++ b/backend/src/Helpdesk.Application/DependencyInjection.cs
@@ -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;
@@ -25,6 +26,7 @@ public static class DependencyInjection
services.AddScoped();
services.AddScoped();
services.AddScoped();
+ services.AddScoped();
return services;
}
}
diff --git a/backend/src/Helpdesk.Application/Statistics/StatisticsDtos.cs b/backend/src/Helpdesk.Application/Statistics/StatisticsDtos.cs
new file mode 100644
index 0000000..1fcf6c0
--- /dev/null
+++ b/backend/src/Helpdesk.Application/Statistics/StatisticsDtos.cs
@@ -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 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);
diff --git a/backend/src/Helpdesk.Application/Statistics/StatisticsService.cs b/backend/src/Helpdesk.Application/Statistics/StatisticsService.cs
new file mode 100644
index 0000000..ad8f4be
--- /dev/null
+++ b/backend/src/Helpdesk.Application/Statistics/StatisticsService.cs
@@ -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 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()
+ .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> 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> 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> 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> 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();
+ 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> 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 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> CountByMonthAsync(
+ IQueryable 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;
+}
diff --git a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs
index 2645811..5bd2548 100644
--- a/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs
+++ b/backend/src/Helpdesk.Infrastructure/Persistence/HelpdeskDbContext.cs
@@ -1,5 +1,6 @@
using System.Data;
using Helpdesk.Application.Abstractions;
+using Helpdesk.Application.Statistics;
using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Catalogs;
using Helpdesk.Domain.Issues;
@@ -27,6 +28,7 @@ public sealed class HelpdeskDbContext(DbContextOptions option
public DbSet ProposalCategories => Set();
public DbSet Issues => Set();
public DbSet IssueEvents => Set();
+ public IQueryable IssueTimings => Set();
public DbSet Attachments => Set();
public DbSet Proposals => Set();
public DbSet ProposalEvents => Set();
@@ -55,6 +57,12 @@ public sealed class HelpdeskDbContext(DbContextOptions option
modelBuilder.ApplyConfiguration(new ProposalCategoryConfiguration());
modelBuilder.ApplyConfiguration(new IssueConfiguration());
modelBuilder.ApplyConfiguration(new IssueEventConfiguration());
+ modelBuilder.Entity().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());