7 Commits

Author SHA1 Message Date
Renovate Bot a74f29b246 chore(deps): update dependency aspire.hosting.apphost to 13.3.5
Backend CI / build-and-test (pull_request) Successful in 49s
Frontend Playwright / e2e (pull_request) Successful in 10m17s
2026-05-30 05:00:16 +00:00
serega404 a8d51df3f1 feat: добавил эндпоинт для получения статистики админского дашборда
Backend CI / build-and-test (push) Successful in 40s
Frontend CI / build-and-check (push) Failing after 19s
🚀 Create and publish a Docker image / Detect changes in backend and frontend (push) Successful in 6s
🚀 Create and publish a Docker image / Build & publish backend image (push) Successful in 24s
🚀 Create and publish a Docker image / Build & publish frontend image (push) Successful in 27s
🚀 Create and publish a Docker image / Update stack on Portainer (push) Successful in 5s
2026-05-30 01:23:57 +03:00
serega404 e8f7a64d15 Merge pull request 'chore(deps): update dependency aspire.apphost.sdk to 13.3.5' (#26) from renovate/aspire.apphost.sdk-13.x into dev
Backend CI / build-and-test (push) Has been cancelled
🚀 Create and publish a Docker image / Detect changes in backend and frontend (push) Has been cancelled
🚀 Create and publish a Docker image / Build & publish backend image (push) Has been cancelled
🚀 Create and publish a Docker image / Build & publish frontend image (push) Has been cancelled
🚀 Create and publish a Docker image / Update stack on Portainer (push) Has been cancelled
Reviewed-on: #26
2026-05-30 01:18:26 +03:00
serega404 c1597a8649 Merge pull request 'chore(deps): update dependency xunit.runner.visualstudio to 3.1.5' (#25) from renovate/xunit.runner.visualstudio-3.x into dev
Backend CI / build-and-test (push) Has been cancelled
🚀 Create and publish a Docker image / Detect changes in backend and frontend (push) Has been cancelled
🚀 Create and publish a Docker image / Build & publish backend image (push) Has been cancelled
🚀 Create and publish a Docker image / Build & publish frontend image (push) Has been cancelled
🚀 Create and publish a Docker image / Update stack on Portainer (push) Has been cancelled
Reviewed-on: #25
2026-05-30 01:18:08 +03:00
serega404 f9d3f1ac56 feat: добавил prometheus экспортер
Backend CI / build-and-test (push) Successful in 43s
🚀 Create and publish a Docker image / Detect changes in backend and frontend (push) Successful in 7s
Backend CI / build-and-test (pull_request) Successful in 44s
Frontend Playwright / e2e (pull_request) Has been cancelled
🚀 Create and publish a Docker image / Build & publish backend image (push) Successful in 59s
🚀 Create and publish a Docker image / Build & publish frontend image (push) Has been skipped
🚀 Create and publish a Docker image / Update stack on Portainer (push) Successful in 4s
2026-05-30 01:16:58 +03:00
Renovate Bot 62dbeecd9f chore(deps): update dependency aspire.apphost.sdk to 13.3.5
Backend CI / build-and-test (pull_request) Successful in 41s
Frontend Playwright / e2e (pull_request) Successful in 10m13s
2026-05-29 05:00:15 +00:00
Renovate Bot edd276664c chore(deps): update dependency xunit.runner.visualstudio to 3.1.5
Backend CI / build-and-test (pull_request) Successful in 46s
Frontend Playwright / e2e (pull_request) Successful in 10m13s
2026-05-29 05:00:14 +00:00
13 changed files with 206 additions and 26 deletions
@@ -14,7 +14,7 @@
<PackageReference Include="NSubstitute" Version="5.3.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.13.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.0">
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
@@ -159,6 +159,19 @@ public class UsersController : ControllerBase
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<UserStatsDto>> Stats(int id) => Ok(await _users.GetStatsAsync(id));
/// <summary>Получить статистику для админского дашборда.</summary>
/// <remarks>Только Admin.</remarks>
/// <response code="200">Агрегированная статистика дашборда.</response>
/// <response code="401">Требуется аутентификация.</response>
/// <response code="403">Требуется роль Admin.</response>
[Authorize(Roles = "Admin")]
[HttpGet("admin/stats")]
[ProducesResponseType(typeof(AdminDashboardStatsDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult<AdminDashboardStatsDto>> AdminStats() =>
Ok(await _users.GetAdminDashboardStatsAsync());
/// <summary>Получить список записей пользователя на лекции.</summary>
/// <remarks>Только Admin. Для текущего пользователя используйте GET /api/v1/users/me/enrollments.</remarks>
/// <param name="id">ID пользователя.</param>
@@ -0,0 +1,71 @@
using System.Net;
using System.Net.Sockets;
namespace UniVerse.Api.Middleware;
public sealed class LocalNetworksOnlyMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<LocalNetworksOnlyMiddleware> _logger;
public LocalNetworksOnlyMiddleware(RequestDelegate next, ILogger<LocalNetworksOnlyMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var remoteIpAddress = context.Connection.RemoteIpAddress;
if (remoteIpAddress is null || !IsLocalNetwork(remoteIpAddress))
{
_logger.LogWarning("Blocked metrics request from non-local address {RemoteIpAddress}", remoteIpAddress);
context.Response.StatusCode = StatusCodes.Status403Forbidden;
await context.Response.WriteAsync("Metrics endpoint is available only from local networks.");
return;
}
await _next(context);
}
private static bool IsLocalNetwork(IPAddress ipAddress)
{
if (IPAddress.IsLoopback(ipAddress))
{
return true;
}
if (ipAddress.IsIPv4MappedToIPv6)
{
ipAddress = ipAddress.MapToIPv4();
}
return ipAddress.AddressFamily switch
{
AddressFamily.InterNetwork => IsPrivateOrLinkLocalIPv4(ipAddress),
AddressFamily.InterNetworkV6 => IsPrivateOrLinkLocalIPv6(ipAddress),
_ => false
};
}
private static bool IsPrivateOrLinkLocalIPv4(IPAddress ipAddress)
{
var bytes = ipAddress.GetAddressBytes();
return bytes[0] == 10
|| bytes[0] == 127
|| (bytes[0] == 192 && bytes[1] == 168)
|| (bytes[0] == 172 && bytes[1] is >= 16 and <= 31)
|| (bytes[0] == 169 && bytes[1] == 254);
}
private static bool IsPrivateOrLinkLocalIPv6(IPAddress ipAddress)
{
var bytes = ipAddress.GetAddressBytes();
return ipAddress.IsIPv6LinkLocal
|| ipAddress.IsIPv6SiteLocal
|| (bytes[0] & 0xfe) == 0xfc;
}
}
+8
View File
@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi;
using Prometheus;
using Quartz;
using Serilog;
using UniVerse.Api.BackgroundServices;
@@ -221,6 +222,7 @@ if (app.Environment.IsDevelopment())
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpMetrics();
if (app.Environment.IsDevelopment())
{
app.UseAntiforgery();
@@ -228,4 +230,10 @@ if (app.Environment.IsDevelopment())
}
app.MapControllers();
// Restrict Prometheus scrape endpoint to local and private networks.
app.UseWhen(
context => context.Request.Path.StartsWithSegments("/metrics", StringComparison.OrdinalIgnoreCase),
branch => branch.UseMiddleware<LocalNetworksOnlyMiddleware>());
app.MapMetrics();
app.Run();
+1
View File
@@ -30,6 +30,7 @@
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.1" />
<PackageReference Include="Quartz.Extensions.Hosting" Version="3.18.1" />
<PackageReference Include="prometheus-net.AspNetCore" Version="8.2.1" />
</ItemGroup>
<ItemGroup>
+68
View File
@@ -4158,6 +4158,52 @@
]
}
},
"/api/v1/users/admin/stats": {
"get": {
"tags": [
"Users"
],
"summary": "Получить статистику для админского дашборда.",
"description": "Только Admin.\n\n**Required roles:** Admin",
"responses": {
"200": {
"description": "Агрегированная статистика дашборда.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/AdminDashboardStatsDto"
}
}
}
},
"401": {
"description": "Требуется аутентификация.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"403": {
"description": "Требуется роль Admin.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
}
},
"security": [
{
"Bearer": [ ]
}
]
}
},
"/api/v1/users/{id}/enrollments": {
"get": {
"tags": [
@@ -4758,6 +4804,28 @@
},
"additionalProperties": false
},
"AdminDashboardStatsDto": {
"type": "object",
"properties": {
"usersCount": {
"type": "integer",
"format": "int32"
},
"lecturesCount": {
"type": "integer",
"format": "int32"
},
"enrollmentsCount": {
"type": "integer",
"format": "int32"
},
"pendingReviewsCount": {
"type": "integer",
"format": "int32"
}
},
"additionalProperties": false
},
"AuthResponse": {
"type": "object",
"properties": {
@@ -1,4 +1,4 @@
<Project Sdk="Aspire.AppHost.Sdk/13.2.2">
<Project Sdk="Aspire.AppHost.Sdk/13.3.5">
<PropertyGroup>
<OutputType>Exe</OutputType>
@@ -13,7 +13,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="13.2.2" />
<PackageReference Include="Aspire.Hosting.AppHost" Version="13.3.5" />
</ItemGroup>
</Project>
@@ -42,6 +42,13 @@ public record UserStatsDto(
IReadOnlyList<EnrollmentSlotRuleDto> EnrollmentSlotRules
);
public record AdminDashboardStatsDto(
int UsersCount,
int LecturesCount,
int EnrollmentsCount,
int PendingReviewsCount
);
public record EnrollmentSlotRuleDto(int Level, int Slots);
public record UpdateUserRequest(
@@ -10,6 +10,7 @@ public interface IUserService
Task<UserDto> GetByIdAsync(int id);
Task<UserDto> UpdateProfileAsync(int id, UpdateUserRequest request);
Task<UserStatsDto> GetStatsAsync(int id);
Task<AdminDashboardStatsDto> GetAdminDashboardStatsAsync();
Task<PagedResult<LectureDto>> GetEnrollmentsAsync(int id, PaginationRequest pagination);
Task<PagedResult<UserDto>> GetAllAsync(UserFilterRequest filter);
Task SetRolesAsync(int id, IReadOnlyCollection<UserRole> roles);
@@ -74,6 +74,17 @@ public class UserService : IUserService
);
}
public async Task<AdminDashboardStatsDto> GetAdminDashboardStatsAsync()
{
var usersCount = await _db.Users
.CountAsync(user => !user.Roles.Any(role => role.Role == UserRole.Teacher));
var lecturesCount = await _db.Lectures.CountAsync();
var enrollmentsCount = await _db.LectureEnrollments.CountAsync();
var pendingReviewsCount = await _db.Reviews.CountAsync(review => review.LlmStatus == ReviewLlmStatus.Pending);
return new AdminDashboardStatsDto(usersCount, lecturesCount, enrollmentsCount, pendingReviewsCount);
}
public async Task<PagedResult<LectureDto>> GetEnrollmentsAsync(int id, PaginationRequest pagination)
{
if (!await _db.Users.AnyAsync(u => u.Id == id))
+2
View File
@@ -18,6 +18,7 @@ import type {
TagDto,
UpdateReviewPromptRequest,
UserAchievementDto,
AdminDashboardStatsDto,
CurrentUserDto,
UserDto,
UserQuery,
@@ -68,6 +69,7 @@ export const usersApi = {
body: JSON.stringify(payload),
}),
myStats: () => apiRequest<UserStatsDto>('/users/me/stats'),
adminStats: () => apiRequest<AdminDashboardStatsDto>('/users/admin/stats'),
async myEnrollments() {
const payload = await apiRequest<PagedResult<LectureDto> | LectureDto[] | undefined>(
'/users/me/enrollments',
+7
View File
@@ -76,6 +76,13 @@ export interface UserStatsDto {
enrollmentSlotRules: EnrollmentSlotRuleDto[]
}
export interface AdminDashboardStatsDto {
usersCount: number
lecturesCount: number
enrollmentsCount: number
pendingReviewsCount: number
}
export interface EnrollmentSlotRuleDto {
level: number
slots: number
+14 -23
View File
@@ -3,17 +3,11 @@ import { computed, onMounted, ref } from 'vue'
import GlassCard from '@/components/ui/GlassCard.vue'
import StatsWidget from '@/components/ui/StatsWidget.vue'
import StatusBadge from '@/components/ui/StatusBadge.vue'
import { lecturesApi, reviewsApi, syncApi, usersApi } from '@/api'
import type { LectureDto, SyncStatusDto, UserDto } from '@/api/types'
import { syncApi, usersApi } from '@/api'
import type { AdminDashboardStatsDto, SyncStatusDto } from '@/api/types'
const users = ref<UserDto[]>([])
const lectures = ref<LectureDto[]>([])
const pendingReviewsCount = ref(0)
const stats = ref<AdminDashboardStatsDto | null>(null)
const syncStatus = ref<SyncStatusDto | null>(null)
const enrollmentCount = computed(() =>
lectures.value.reduce((sum, lecture) => sum + lecture.enrollmentsCount, 0),
)
const syncMeta = computed(() =>
syncStatus.value?.lastSyncAt
? `Последняя синхронизация: ${new Date(syncStatus.value.lastSyncAt).toLocaleString('ru-RU')}`
@@ -21,16 +15,8 @@ const syncMeta = computed(() =>
)
onMounted(async () => {
const [usersResult, lecturesResult, reviewsResult, syncResult] = await Promise.allSettled([
usersApi.list({ PageSize: 100 }),
lecturesApi.list({ PageSize: 100 }),
reviewsApi.listPage({ Page: 1, PageSize: 1, LlmStatus: 'Pending' }),
syncApi.status(),
])
if (usersResult.status === 'fulfilled') users.value = usersResult.value
if (lecturesResult.status === 'fulfilled') lectures.value = lecturesResult.value
if (reviewsResult.status === 'fulfilled')
pendingReviewsCount.value = reviewsResult.value.totalCount
const [statsResult, syncResult] = await Promise.allSettled([usersApi.adminStats(), syncApi.status()])
if (statsResult.status === 'fulfilled') stats.value = statsResult.value
if (syncResult.status === 'fulfilled') syncStatus.value = syncResult.value
})
</script>
@@ -40,12 +26,17 @@ onMounted(async () => {
<h1 class="page-title">Дашборд администратора</h1>
<div class="stats-row">
<StatsWidget label="Пользователей" :value="users.length" icon="users" color="green" />
<StatsWidget label="Лекций" :value="lectures.length" icon="books" color="aqua" />
<StatsWidget label="Записей" :value="enrollmentCount" icon="calendar-event" color="orange" />
<StatsWidget label="Пользователей" :value="stats?.usersCount ?? 0" icon="users" color="green" />
<StatsWidget label="Лекций" :value="stats?.lecturesCount ?? 0" icon="books" color="aqua" />
<StatsWidget
label="Записей"
:value="stats?.enrollmentsCount ?? 0"
icon="calendar-event"
color="orange"
/>
<StatsWidget
label="Отзывы на проверке"
:value="pendingReviewsCount"
:value="stats?.pendingReviewsCount ?? 0"
icon="message-circle"
color="purple"
/>