Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
namespace Api.Controllers.Payload.Requests;
namespace Api.Controllers.Payload.Requests;

/// <summary>
/// get all logs paginated
Expand Down
46 changes: 46 additions & 0 deletions src/Api/Controllers/UsersController.cs
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
using Api.Controllers.Payload.Requests;
using Api.Controllers.Payload.Requests.Users;
using Application.Common.Interfaces;
using Application.Common.Models;
using Application.Common.Models.Dtos.Logging;
using Application.Identity;
using Application.Users.Commands;
using Application.Users.Queries;
Expand DownExpand Up@@ -160,4 +162,48 @@ public async Task<ActionResult<Result<UserDto>>> Update([FromRoute] Guid userId,
var result = await Mediator.Send(command);
return Ok(Result<UserDto>.Succeed(result));
}

/// <summary>
/// Get all user related logs paginated
/// </summary>
/// <param name="queryParameters">Get all users related logs query parameters</param>
/// <returns>A paginated list of UserLogDto</returns>
[RequiresRole(IdentityData.Roles.Admin)]
[HttpGet("logs")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult<Result<PaginatedList<UserLogDto>>>> GetAllUserLogs(
[FromQuery] GetAllLogsPaginatedQueryParameters queryParameters)
{
var query = new GetAllUserLogsPaginated.Query()
{
SearchTerm = queryParameters.SearchTerm,
Page = queryParameters.Page,
Size = queryParameters.Size,
SortBy = queryParameters.SortBy,
SortOrder = queryParameters.SortOrder,
};
var result = await Mediator.Send(query);
return Ok(Result<PaginatedList<UserLogDto>>.Succeed(result));
}

/// <summary>
/// Get user related log by Id
/// </summary>
/// <param name="logId">Id of the logged user</param>
/// <returns>UserLogDto of the logged user</returns>
[RequiresRole(IdentityData.Roles.Admin)]
[HttpGet("log/{logId:guid}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<ActionResult<Result<UserLogDto>>> GetUserLogById([FromRoute] Guid logId)
{
var query = new GetUserLogById.Query()
{
LogId = logId
};

var result = await Mediator.Send(query);
return Ok(Result<UserLogDto>.Succeed(result));
}
}
25 changes: 25 additions & 0 deletions src/Application/Common/Models/Dtos/Logging/UserLogDto.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
using Application.Common.Mappings;
using Application.Users.Queries;
using AutoMapper;
using Domain.Entities.Logging;

namespace Application.Common.Models.Dtos.Logging;

public class UserLogDto : IMapFrom<UserLog>
{
public Guid Id { get; set; }
public string Action { get; set; } = null!;
public UserDto? Object { get; set; }
public DateTime Time { get; set; }
public UserDto User { get; set; } = null!;

public void Mapping(Profile profile)
{
profile.CreateMap<UserLog, UserLogDto>()
.ForMember( dest => dest.Time,
opt => opt.MapFrom( src => src.Time.ToDateTimeUnspecified()))
.ForMember(dest => dest.Object,
opt => opt.MapFrom( src => src.Object));

}
}
66 changes: 66 additions & 0 deletions src/Application/Users/Queries/GetAllUserLogsPaginated.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
using Application.Common.Extensions;
using Application.Common.Interfaces;
using Application.Common.Models;
using Application.Common.Models.Dtos.Logging;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Application.Users.Queries;

public class GetAllUserLogsPaginated
{
public record Query : IRequest<PaginatedList<UserLogDto>>
{
public string? SearchTerm { get; init; }
public int? Page { get; init; }
public int? Size { get; init; }
public string? SortBy { get; init; }
public string? SortOrder { get; init; }
}

public class QueryHandler : IRequestHandler<Query, PaginatedList<UserLogDto>>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;

public QueryHandler(IApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}

public async Task<PaginatedList<UserLogDto>> Handle(Query request, CancellationToken cancellationToken)
{
var logs = _context.UserLogs
.Include(x => x.Object)
.AsQueryable();

if (!(request.SearchTerm is null || request.SearchTerm.Trim().Equals(string.Empty)))
{
logs = logs.Where(x =>
x.Action.Trim().ToLower().Contains(request.SearchTerm.Trim().ToLower()));
}

var sortBy = request.SortBy;
if (sortBy is null || !sortBy.MatchesPropertyName<UserLogDto>())
{
sortBy = nameof(UserLogDto.Time);
}

var sortOrder = request.SortOrder ?? "dsc";
var pageNumber = request.Page is null or <= 0 ? 1 : request.Page;
var sizeNumber = request.Size is null or <= 0 ? 5 : request.Size;

var count = await logs.CountAsync(cancellationToken);
var list = await logs
.Paginate(pageNumber.Value, sizeNumber.Value)
.OrderByCustom(sortBy, sortOrder)
.ToListAsync(cancellationToken);

var result = _mapper.Map<List<UserLogDto>>(list);

return new PaginatedList<UserLogDto>(result, count, pageNumber.Value, sizeNumber.Value);
}
}
}
43 changes: 43 additions & 0 deletions src/Application/Users/Queries/GetUserLogById.cs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
using Application.Common.Interfaces;
using Application.Common.Models.Dtos.Logging;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Application.Users.Queries;

public class GetUserLogById
{
public record Query : IRequest<UserLogDto>
{
public Guid LogId { get; init; }
}

public class QueryHandler : IRequestHandler<Query, UserLogDto>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;

public QueryHandler(IApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}

public async Task<UserLogDto> Handle(Query request, CancellationToken cancellationToken)
{
var log = await _context.UserLogs
.Include(x => x.Object)
.Include(x => x.User)
.ThenInclude(x => x.Department)
.FirstOrDefaultAsync(x => x.Id.Equals(request.LogId), cancellationToken);

if (log is null)
{
throw new KeyNotFoundException("Log does not exist.");
}

return _mapper.Map<UserLogDto>(log);
}
}
}