backend: Add management statistics endpoints
This commit is contained in:
1 parent
1ff4a0a814
commit
b1e0638979
6 files changed
+240
No files matched your search
@@ -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,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; }
|
||||
|
||||
@@ -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<NotificationService>();
|
||||
services.AddScoped<NotificationWriter>();
|
||||
services.AddScoped<ProposalService>();
|
||||
services.AddScoped<StatisticsService>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<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>();
|
||||
@@ -55,6 +57,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());
|
||||
|
||||
Reference in new issue
Block a user