89 lines
2.7 KiB
C#
89 lines
2.7 KiB
C#
using Fitness_core_BE.Models;
|
|
using Fitness_core_BE.Interfaces;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Fitness_core_BE.Repos
|
|
{
|
|
public class ActivityLogRepository : IActivityLogRepository
|
|
{
|
|
private readonly CentralDbContext _dbContext;
|
|
|
|
public ActivityLogRepository(CentralDbContext dbContext)
|
|
{
|
|
_dbContext = dbContext;
|
|
}
|
|
|
|
public async Task AddActivityLogAsync(ActivityLog log, CancellationToken ct = default)
|
|
{
|
|
try
|
|
{
|
|
_dbContext.ActivityLogs.Add(log);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Failed to add activity log: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
public async Task<List<ActivityLog>> GetActivityLogsAsync(
|
|
string searchTerm = null,
|
|
DateTime? startDate = null,
|
|
DateTime? endDate = null,
|
|
CancellationToken ct = default)
|
|
{
|
|
try
|
|
{
|
|
var query = _dbContext.ActivityLogs
|
|
.AsNoTracking()
|
|
.Include(a => a.User)
|
|
.AsQueryable();
|
|
|
|
// Apply search filter
|
|
if (!string.IsNullOrEmpty(searchTerm))
|
|
{
|
|
query = query.Where(a =>
|
|
a.Description.Contains(searchTerm) ||
|
|
a.UserName.Contains(searchTerm));
|
|
}
|
|
|
|
// Apply date range filters
|
|
if (startDate.HasValue)
|
|
{
|
|
query = query.Where(a => a.Timestamp >= startDate.Value);
|
|
}
|
|
|
|
if (endDate.HasValue)
|
|
{
|
|
query = query.Where(a => a.Timestamp <= endDate.Value);
|
|
}
|
|
|
|
return await query
|
|
.OrderByDescending(a => a.Timestamp)
|
|
.ToListAsync(ct);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Failed to fetch activity logs: {ex.Message}");
|
|
return new List<ActivityLog>();
|
|
}
|
|
}
|
|
|
|
public async Task<string> GetUserNameAsync(Guid userId, CancellationToken ct = default)
|
|
{
|
|
try
|
|
{
|
|
var user = await _dbContext.Users
|
|
.AsNoTracking()
|
|
.FirstOrDefaultAsync(u => u.UserId == userId, ct);
|
|
|
|
return user?.UserName ?? "Unknown User";
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Failed to fetch username: {ex.Message}");
|
|
return "Unknown User";
|
|
}
|
|
}
|
|
}
|
|
}
|