diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3aa36b1 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,35 @@ +name: Valora CI + +on: + push: + branches: + - main + - dev + pull_request: + branches: + - main + - dev + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 9.0.x + + - name: Restore dependencies + run: dotnet restore + + - name: Build solution + run: dotnet build --no-restore --configuration Release + + - name: Run tests + run: dotnet test --no-build --configuration Release \ No newline at end of file diff --git a/src/Valora.Api/Controllers/AdminController.cs b/src/Valora.Api/Controllers/AdminController.cs new file mode 100644 index 0000000..3e6a3c0 --- /dev/null +++ b/src/Valora.Api/Controllers/AdminController.cs @@ -0,0 +1,321 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using Valora.Application.Contracts.Admin; +using Valora.Domain.Constants; +using Valora.Infrastructure.Persistence; +using Valora.Infrastructure.Persistence.Identity; + +namespace Valora.Api.Controllers; + +/// +/// Administrative endpoints for platform insights. +/// +[ApiController] +[Authorize(Roles = ApplicationRoles.Admin)] +[Route("api/admin")] +public sealed class AdminController : ControllerBase +{ + private readonly ValoraDbContext _dbContext; + private readonly UserManager _userManager; + + /// + /// Initializes a new instance of the class. + /// + public AdminController( + ValoraDbContext dbContext, + UserManager userManager) + { + _dbContext = dbContext; + _userManager = userManager; + } + + /// + /// Gets a combined admin dashboard overview. + /// + [HttpGet("dashboard")] + [ProducesResponseType(typeof(AdminDashboardResponse), StatusCodes.Status200OK)] + public async Task GetDashboard(CancellationToken cancellationToken) + { + DateTime sinceUtc = DateTime.UtcNow.AddHours(-24); + + int totalUsers = await _dbContext.Users.CountAsync(cancellationToken); + int totalListings = await _dbContext.Listings.CountAsync(cancellationToken); + int publishedListings = await _dbContext.Listings.CountAsync(x => x.Status == ListingStatuses.Published, cancellationToken); + int soldListings = await _dbContext.Listings.CountAsync(x => x.Status == ListingStatuses.Sold, cancellationToken); + int totalPredictions = await _dbContext.PredictionRecords.CountAsync(cancellationToken); + int totalTrainingRuns = await _dbContext.TrainingRuns.CountAsync(cancellationToken); + int totalAuditLogs = await _dbContext.AuditLogs.CountAsync(cancellationToken); + int listingsLast24Hours = await _dbContext.Listings.CountAsync(x => x.CreatedAtUtc >= sinceUtc, cancellationToken); + int predictionsLast24Hours = await _dbContext.PredictionRecords.CountAsync(x => x.CreatedAtUtc >= sinceUtc, cancellationToken); + + AdminMetricItemResponse[] listingsByCategory = await _dbContext.Listings + .AsNoTracking() + .GroupBy(x => x.CategoryKey) + .Select(g => new AdminMetricItemResponse + { + Name = g.Key, + Value = g.Count() + }) + .OrderByDescending(x => x.Value) + .ToArrayAsync(cancellationToken); + + AdminMetricItemResponse[] predictionsByCategory = await _dbContext.PredictionRecords + .AsNoTracking() + .GroupBy(x => x.CategoryKey) + .Select(g => new AdminMetricItemResponse + { + Name = g.Key, + Value = g.Count() + }) + .OrderByDescending(x => x.Value) + .ToArrayAsync(cancellationToken); + + AdminMetricItemResponse[] trainingRunsByCategory = await _dbContext.TrainingRuns + .AsNoTracking() + .GroupBy(x => x.CategoryKey) + .Select(g => new AdminMetricItemResponse + { + Name = g.Key, + Value = g.Count() + }) + .OrderByDescending(x => x.Value) + .ToArrayAsync(cancellationToken); + + AdminRecentAuditLogResponse[] recentAuditLogs = await _dbContext.AuditLogs + .AsNoTracking() + .OrderByDescending(x => x.CreatedAtUtc) + .Take(20) + .Select(x => new AdminRecentAuditLogResponse + { + Id = x.Id, + UserId = x.UserId, + Action = x.Action, + EntityType = x.EntityType, + EntityId = x.EntityId, + Details = x.Details, + CreatedAtUtc = x.CreatedAtUtc + }) + .ToArrayAsync(cancellationToken); + + AdminDashboardResponse response = new() + { + TotalUsers = totalUsers, + TotalListings = totalListings, + PublishedListings = publishedListings, + SoldListings = soldListings, + TotalPredictions = totalPredictions, + TotalTrainingRuns = totalTrainingRuns, + TotalAuditLogs = totalAuditLogs, + ListingsLast24Hours = listingsLast24Hours, + PredictionsLast24Hours = predictionsLast24Hours, + ListingsByCategory = listingsByCategory, + PredictionsByCategory = predictionsByCategory, + TrainingRunsByCategory = trainingRunsByCategory, + RecentAuditLogs = recentAuditLogs + }; + + return Ok(response); + } + + /// + /// Gets simple user statistics. + /// + [HttpGet("users/stats")] + [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] + public async Task GetUserStats(CancellationToken cancellationToken) + { + ApplicationUser[] users = await _dbContext.Users + .AsNoTracking() + .ToArrayAsync(cancellationToken); + + int totalUsers = users.Length; + int activeUsers = users.Count(x => x.IsActive); + int admins = 0; + int sellers = 0; + int buyers = 0; + + foreach (ApplicationUser user in users) + { + IList roles = await _userManager.GetRolesAsync(user); + + if (roles.Contains(ApplicationRoles.Admin)) + { + admins++; + } + + if (roles.Contains(ApplicationRoles.Seller)) + { + sellers++; + } + + if (roles.Contains(ApplicationRoles.Buyer)) + { + buyers++; + } + } + + return Ok(new + { + totalUsers, + activeUsers, + admins, + sellers, + buyers + }); + } + + /// + /// Gets listing statistics. + /// + [HttpGet("listings/stats")] + [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] + public async Task GetListingStats(CancellationToken cancellationToken) + { + int total = await _dbContext.Listings.CountAsync(cancellationToken); + int draft = await _dbContext.Listings.CountAsync(x => x.Status == ListingStatuses.Draft, cancellationToken); + int predicted = await _dbContext.Listings.CountAsync(x => x.Status == ListingStatuses.Predicted, cancellationToken); + int published = await _dbContext.Listings.CountAsync(x => x.Status == ListingStatuses.Published, cancellationToken); + int sold = await _dbContext.Listings.CountAsync(x => x.Status == ListingStatuses.Sold, cancellationToken); + int archived = await _dbContext.Listings.CountAsync(x => x.Status == ListingStatuses.Archived, cancellationToken); + + var byCategory = await _dbContext.Listings + .AsNoTracking() + .GroupBy(x => x.CategoryKey) + .Select(g => new + { + category = g.Key, + count = g.Count() + }) + .OrderByDescending(x => x.count) + .ToArrayAsync(cancellationToken); + + return Ok(new + { + total, + draft, + predicted, + published, + sold, + archived, + byCategory + }); + } + + /// + /// Gets prediction statistics. + /// + [HttpGet("predictions/stats")] + [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] + public async Task GetPredictionStats(CancellationToken cancellationToken) + { + int total = await _dbContext.PredictionRecords.CountAsync(cancellationToken); + + var byCategory = await _dbContext.PredictionRecords + .AsNoTracking() + .GroupBy(x => x.CategoryKey) + .Select(g => new + { + category = g.Key, + count = g.Count() + }) + .OrderByDescending(x => x.count) + .ToArrayAsync(cancellationToken); + + var byModelVersion = await _dbContext.PredictionRecords + .AsNoTracking() + .GroupBy(x => new { x.CategoryKey, x.ModelVersion }) + .Select(g => new + { + category = g.Key.CategoryKey, + modelVersion = g.Key.ModelVersion, + count = g.Count() + }) + .OrderByDescending(x => x.count) + .ToArrayAsync(cancellationToken); + + return Ok(new + { + total, + byCategory, + byModelVersion + }); + } + + /// + /// Gets model training statistics. + /// + [HttpGet("models/stats")] + [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] + public async Task GetModelStats(CancellationToken cancellationToken) + { + int totalTrainingRuns = await _dbContext.TrainingRuns.CountAsync(cancellationToken); + + var latestRuns = await _dbContext.TrainingRuns + .AsNoTracking() + .OrderByDescending(x => x.CreatedAtUtc) + .Take(20) + .Select(x => new + { + x.Id, + x.CategoryKey, + x.Version, + x.RSquared, + x.RootMeanSquaredError, + x.MeanAbsoluteError, + x.MeanSquaredError, + x.CreatedAtUtc + }) + .ToArrayAsync(cancellationToken); + + var byCategory = await _dbContext.TrainingRuns + .AsNoTracking() + .GroupBy(x => x.CategoryKey) + .Select(g => new + { + category = g.Key, + count = g.Count(), + latestVersion = g.Max(x => x.Version) + }) + .OrderByDescending(x => x.count) + .ToArrayAsync(cancellationToken); + + return Ok(new + { + totalTrainingRuns, + byCategory, + latestRuns + }); + } + + /// + /// Gets recent audit logs. + /// + [HttpGet("audit-logs")] + [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] + public async Task GetAuditLogs(CancellationToken cancellationToken) + { + var logs = await _dbContext.AuditLogs + .AsNoTracking() + .OrderByDescending(x => x.CreatedAtUtc) + .Take(100) + .Select(x => new + { + x.Id, + x.UserId, + x.Action, + x.EntityType, + x.EntityId, + x.Details, + x.CreatedAtUtc + }) + .ToArrayAsync(cancellationToken); + + return Ok(new + { + count = logs.Length, + logs + }); + } +} \ No newline at end of file diff --git a/src/Valora.Api/Extensions/ApplicationBuilderExtensions.cs b/src/Valora.Api/Extensions/ApplicationBuilderExtensions.cs new file mode 100644 index 0000000..4ea7f3a --- /dev/null +++ b/src/Valora.Api/Extensions/ApplicationBuilderExtensions.cs @@ -0,0 +1,22 @@ +using Valora.Api.Middleware; + +namespace Valora.Api.Extensions; + +/// +/// Application builder extensions for Valora middleware. +/// +public static class ApplicationBuilderExtensions +{ + /// + /// Adds the Valora middleware pipeline. + /// + /// The web application. + /// The web application. + public static WebApplication UseValoraMiddleware(this WebApplication app) + { + app.UseMiddleware(); + app.UseMiddleware(); + + return app; + } +} \ No newline at end of file diff --git a/src/Valora.Api/Extensions/ServiceCollectionExtensions.cs b/src/Valora.Api/Extensions/ServiceCollectionExtensions.cs index 3b991ee..e6111e7 100644 --- a/src/Valora.Api/Extensions/ServiceCollectionExtensions.cs +++ b/src/Valora.Api/Extensions/ServiceCollectionExtensions.cs @@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Valora.Application.Abstractions.Listings; +using Valora.Application.Abstractions.Logging; using Valora.Application.Abstractions.PricePrediction; using Valora.Infrastructure.ML.Definitions; using Valora.Infrastructure.ML.Registry; @@ -11,12 +12,12 @@ using Valora.Infrastructure.Persistence; using Valora.Infrastructure.Persistence.Identity; using Valora.Infrastructure.Services.Listings; +using Valora.Infrastructure.Services.Logging; namespace Valora.Api.Extensions; /// -/// Extension methods for registering Valora services. -/// Keeps Program.cs clean and organizes DI by layer. +/// Extension methods for registering infrastructure persistence services. /// public static class ServiceCollectionExtensions { @@ -99,6 +100,7 @@ public static IServiceCollection AddValoraPersistence( services.AddAuthorization(); services.AddScoped(); + services.AddScoped(); return services; } diff --git a/src/Valora.Api/Middleware/ExceptionHandlingMiddleware.cs b/src/Valora.Api/Middleware/ExceptionHandlingMiddleware.cs new file mode 100644 index 0000000..e5e8551 --- /dev/null +++ b/src/Valora.Api/Middleware/ExceptionHandlingMiddleware.cs @@ -0,0 +1,96 @@ +using System.Security.Claims; +using System.Text.Json; +using Valora.Application.Abstractions.Logging; + +namespace Valora.Api.Middleware; + +/// +/// Middleware for centralized exception handling and exception audit logging. +/// +public sealed class ExceptionHandlingMiddleware +{ + private readonly RequestDelegate _next; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + public ExceptionHandlingMiddleware( + RequestDelegate next, + ILogger logger) + { + _next = next; + _logger = logger; + } + + /// + /// Invokes the middleware. + /// + public async Task InvokeAsync( + HttpContext context, + IAuditLogService auditLogService) + { + try + { + await _next(context); + } + catch (Exception ex) + { + Guid? userId = TryGetUserId(context.User); + + _logger.LogError( + ex, + "Unhandled exception for {Method} {Path}", + context.Request.Method, + context.Request.Path); + + string details = JsonSerializer.Serialize(new + { + method = context.Request.Method, + path = context.Request.Path.Value, + queryString = context.Request.QueryString.Value, + exceptionType = ex.GetType().Name, + ex.Message + }); + + try + { + await auditLogService.WriteAsync( + userId, + action: "UnhandledException", + entityType: "Request", + entityId: context.TraceIdentifier, + details: details, + cancellationToken: context.RequestAborted); + } + catch + { + // Intentionally swallow secondary logging failures. + } + + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + context.Response.ContentType = "application/json"; + + var response = new + { + title = "An unexpected error occurred", + status = StatusCodes.Status500InternalServerError, + detail = ex.Message + }; + + await context.Response.WriteAsJsonAsync(response); + } + } + + private static Guid? TryGetUserId(ClaimsPrincipal user) + { + string? userId = user.FindFirstValue(ClaimTypes.NameIdentifier); + + if (string.IsNullOrWhiteSpace(userId) || !Guid.TryParse(userId, out Guid parsed)) + { + return null; + } + + return parsed; + } +} \ No newline at end of file diff --git a/src/Valora.Api/Middleware/RequestLoggingMiddleware.cs b/src/Valora.Api/Middleware/RequestLoggingMiddleware.cs new file mode 100644 index 0000000..d75c1e5 --- /dev/null +++ b/src/Valora.Api/Middleware/RequestLoggingMiddleware.cs @@ -0,0 +1,88 @@ +using System.Diagnostics; +using System.Security.Claims; +using System.Text.Json; +using Valora.Application.Abstractions.Logging; + +namespace Valora.Api.Middleware; + +/// +/// Middleware for request/response audit logging. +/// +public sealed class RequestLoggingMiddleware +{ + private readonly RequestDelegate _next; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + public RequestLoggingMiddleware( + RequestDelegate next, + ILogger logger) + { + _next = next; + _logger = logger; + } + + /// + /// Invokes the middleware. + /// + public async Task InvokeAsync( + HttpContext context, + IAuditLogService auditLogService) + { + Stopwatch stopwatch = Stopwatch.StartNew(); + + await _next(context); + + stopwatch.Stop(); + + Guid? userId = TryGetUserId(context.User); + + string[] roles = context.User.Claims + .Where(x => x.Type == ClaimTypes.Role) + .Select(x => x.Value) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + + string details = JsonSerializer.Serialize(new + { + method = context.Request.Method, + path = context.Request.Path.Value, + queryString = context.Request.QueryString.Value, + statusCode = context.Response.StatusCode, + elapsedMs = stopwatch.ElapsedMilliseconds, + traceIdentifier = context.TraceIdentifier, + roles, + remoteIp = context.Connection.RemoteIpAddress?.ToString(), + userAgent = context.Request.Headers.UserAgent.ToString() + }); + + _logger.LogInformation( + "HTTP {Method} {Path} responded {StatusCode} in {ElapsedMs} ms", + context.Request.Method, + context.Request.Path, + context.Response.StatusCode, + stopwatch.ElapsedMilliseconds); + + await auditLogService.WriteAsync( + userId, + action: "HttpRequest", + entityType: "Request", + entityId: context.TraceIdentifier, + details: details, + cancellationToken: context.RequestAborted); + } + + private static Guid? TryGetUserId(ClaimsPrincipal user) + { + string? userId = user.FindFirstValue(ClaimTypes.NameIdentifier); + + if (string.IsNullOrWhiteSpace(userId) || !Guid.TryParse(userId, out Guid parsed)) + { + return null; + } + + return parsed; + } +} \ No newline at end of file diff --git a/src/Valora.Api/Program.cs b/src/Valora.Api/Program.cs index 474f6ac..49f4441 100644 --- a/src/Valora.Api/Program.cs +++ b/src/Valora.Api/Program.cs @@ -1,6 +1,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.OpenApi.Models; using Valora.Api.Extensions; +using Valora.Api.Middleware; using Valora.Infrastructure.Persistence; using Valora.Infrastructure.Persistence.Seed; @@ -53,11 +54,15 @@ app.UseSwaggerUI(); } +app.UseMiddleware(); + app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); +app.UseMiddleware(); + app.MapControllers(); await ApplyDatabaseMigrationsAsync(app); diff --git a/src/Valora.Application/Abstractions/Logging/IAuditLogService.cs b/src/Valora.Application/Abstractions/Logging/IAuditLogService.cs new file mode 100644 index 0000000..ce8d1a8 --- /dev/null +++ b/src/Valora.Application/Abstractions/Logging/IAuditLogService.cs @@ -0,0 +1,24 @@ +namespace Valora.Application.Abstractions.Logging; + +/// +/// Service for writing audit logs. +/// +public interface IAuditLogService +{ + /// + /// Writes an audit log entry. + /// + /// The optional user id. + /// The action name. + /// The entity type. + /// The optional entity id. + /// Additional details. + /// The cancellation token. + Task WriteAsync( + Guid? userId, + string action, + string entityType, + string? entityId, + string? details, + CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/src/Valora.Application/Contracts/Admin/AdminDashboardResponse.cs b/src/Valora.Application/Contracts/Admin/AdminDashboardResponse.cs new file mode 100644 index 0000000..a8727b9 --- /dev/null +++ b/src/Valora.Application/Contracts/Admin/AdminDashboardResponse.cs @@ -0,0 +1,72 @@ +namespace Valora.Application.Contracts.Admin; + +/// +/// Represents the main admin dashboard response. +/// +public sealed class AdminDashboardResponse +{ + /// + /// Gets or sets the total user count. + /// + public int TotalUsers { get; init; } + + /// + /// Gets or sets the total listing count. + /// + public int TotalListings { get; init; } + + /// + /// Gets or sets the published listing count. + /// + public int PublishedListings { get; init; } + + /// + /// Gets or sets the sold listing count. + /// + public int SoldListings { get; init; } + + /// + /// Gets or sets the total prediction count. + /// + public int TotalPredictions { get; init; } + + /// + /// Gets or sets the total training run count. + /// + public int TotalTrainingRuns { get; init; } + + /// + /// Gets or sets the total audit log count. + /// + public int TotalAuditLogs { get; init; } + + /// + /// Gets or sets the latest listing count in the last 24 hours. + /// + public int ListingsLast24Hours { get; init; } + + /// + /// Gets or sets the latest prediction count in the last 24 hours. + /// + public int PredictionsLast24Hours { get; init; } + + /// + /// Gets or sets the training runs by category. + /// + public required IReadOnlyCollection TrainingRunsByCategory { get; init; } + + /// + /// Gets or sets the predictions by category. + /// + public required IReadOnlyCollection PredictionsByCategory { get; init; } + + /// + /// Gets or sets the listings by category. + /// + public required IReadOnlyCollection ListingsByCategory { get; init; } + + /// + /// Gets or sets the most recent audit logs. + /// + public required IReadOnlyCollection RecentAuditLogs { get; init; } +} \ No newline at end of file diff --git a/src/Valora.Application/Contracts/Admin/AdminMetricItemResponse.cs b/src/Valora.Application/Contracts/Admin/AdminMetricItemResponse.cs new file mode 100644 index 0000000..5116010 --- /dev/null +++ b/src/Valora.Application/Contracts/Admin/AdminMetricItemResponse.cs @@ -0,0 +1,17 @@ +namespace Valora.Application.Contracts.Admin; + +/// +/// Represents a named metric item. +/// +public sealed class AdminMetricItemResponse +{ + /// + /// Gets or sets the metric name. + /// + public required string Name { get; set; } + + /// + /// Gets or sets the metric value. + /// + public int Value { get; set; } +} \ No newline at end of file diff --git a/src/Valora.Application/Contracts/Admin/AdminRecentAuditLogResponse.cs b/src/Valora.Application/Contracts/Admin/AdminRecentAuditLogResponse.cs new file mode 100644 index 0000000..c3f8be8 --- /dev/null +++ b/src/Valora.Application/Contracts/Admin/AdminRecentAuditLogResponse.cs @@ -0,0 +1,42 @@ +namespace Valora.Application.Contracts.Admin; + +/// +/// Represents a recent audit log entry for the admin dashboard. +/// +public sealed class AdminRecentAuditLogResponse +{ + /// + /// Gets or sets the audit log id. + /// + public Guid Id { get; init; } + + /// + /// Gets or sets the optional user id. + /// + public Guid? UserId { get; init; } + + /// + /// Gets or sets the action. + /// + public required string Action { get; init; } + + /// + /// Gets or sets the entity type. + /// + public required string EntityType { get; init; } + + /// + /// Gets or sets the entity id. + /// + public required string EntityId { get; init; } + + /// + /// Gets or sets the details. + /// + public required string Details { get; init; } + + /// + /// Gets or sets the creation timestamp. + /// + public DateTime CreatedAtUtc { get; init; } +} \ No newline at end of file diff --git a/src/Valora.Infrastructure/Services/Logging/AuditLogService.cs b/src/Valora.Infrastructure/Services/Logging/AuditLogService.cs new file mode 100644 index 0000000..d41b610 --- /dev/null +++ b/src/Valora.Infrastructure/Services/Logging/AuditLogService.cs @@ -0,0 +1,68 @@ +using Valora.Application.Abstractions.Logging; +using Valora.Domain.Entities; +using Valora.Infrastructure.Persistence; + +namespace Valora.Infrastructure.Services.Logging; + +/// +/// Default database-backed audit log service. +/// +public sealed class AuditLogService : IAuditLogService +{ + private readonly ValoraDbContext _dbContext; + + /// + /// Initializes a new instance of the class. + /// + /// The database context. + public AuditLogService(ValoraDbContext dbContext) + { + _dbContext = dbContext; + } + + /// + public async Task WriteAsync( + Guid? userId, + string action, + string entityType, + string? entityId, + string? details, + CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(action)) + { + throw new ArgumentException("Action is required.", nameof(action)); + } + + if (string.IsNullOrWhiteSpace(entityType)) + { + throw new ArgumentException("EntityType is required.", nameof(entityType)); + } + + AuditLog log = new AuditLog + { + Id = Guid.NewGuid(), + UserId = userId, + Action = Trim(action, 200), + EntityType = Trim(entityType, 200), + EntityId = Trim(entityId ?? string.Empty, 200), + Details = Trim(details ?? string.Empty, 8000), + CreatedAtUtc = DateTime.UtcNow + }; + + _dbContext.AuditLogs.Add(log); + await _dbContext.SaveChangesAsync(cancellationToken); + } + + private static string Trim(string value, int maxLength) + { + if (string.IsNullOrEmpty(value)) + { + return string.Empty; + } + + return value.Length <= maxLength + ? value + : value[..maxLength]; + } +} \ No newline at end of file