99 lines
3.4 KiB
C#
99 lines
3.4 KiB
C#
using Fitness_core_BE.Models;
|
|
using Fitness_core_BE.Helpers;
|
|
using Fitness_core_BE.Infra.UoW;
|
|
using Fitness_core_BE.Interfaces;
|
|
using Fitness_core_BE.Interfaces.Services;
|
|
|
|
namespace Fitness_core_BE.Services.ActivityLog
|
|
{
|
|
public class ActivityLogService : IActivityLogService
|
|
{
|
|
private readonly IActivityLogRepository _activityLogRepository;
|
|
private readonly UserRoleHelper _userRoleHelper;
|
|
private readonly IUnitOfWork _uow;
|
|
|
|
public ActivityLogService(
|
|
IActivityLogRepository activityLogRepository,
|
|
UserRoleHelper userRoleHelper,
|
|
IUnitOfWork uow)
|
|
{
|
|
_activityLogRepository = activityLogRepository;
|
|
_userRoleHelper = userRoleHelper;
|
|
_uow = uow;
|
|
}
|
|
|
|
// To do: add services used, IP addresses, category as Error/ Action
|
|
|
|
public async Task<object> LogActivity(object payload, HttpContext httpContext)
|
|
{
|
|
await _uow.BeginAsync();
|
|
try
|
|
{
|
|
var data = DeserializePayload.Deserialize(payload);
|
|
string description = data["description"].GetString()!;
|
|
|
|
// Get userId from HttpContext ( for testing purposes - hardcoded)
|
|
Guid userId = Guid.Parse("08de9f89-4681-4a2f-8f37-6c1ce830ee6f");
|
|
// Guid userId = Guid.Parse(httpContext.Items["UserId"]?.ToString()!);
|
|
|
|
Guid? adminId = await _userRoleHelper.GetAdminId(userId);
|
|
bool isAdmin = adminId.HasValue;
|
|
|
|
// Get user details (you might need to add a method to get user by Id)
|
|
var userName = await _activityLogRepository.GetUserNameAsync(userId);
|
|
|
|
var log = new Fitness_core_BE.Models.ActivityLog
|
|
{
|
|
FKUserId = userId,
|
|
UserName = userName,
|
|
IsAdmin = isAdmin,
|
|
Description = description,
|
|
Timestamp = DateTime.UtcNow
|
|
};
|
|
|
|
await _activityLogRepository.AddActivityLogAsync(log);
|
|
await _uow.CommitAsync();
|
|
|
|
return log;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await _uow.RollbackAsync();
|
|
Console.WriteLine($"Activity log failed: {ex.Message}");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public async Task<object> GetActivityLogs(object payload, HttpContext httpContext)
|
|
{
|
|
try
|
|
{
|
|
var data = DeserializePayload.Deserialize(payload);
|
|
|
|
string searchTerm = data.ContainsKey("searchTerm") && !string.IsNullOrEmpty(data["searchTerm"].GetString())
|
|
? data["searchTerm"].GetString()
|
|
: null;
|
|
|
|
DateTime? startDate = data.ContainsKey("startDate") && !string.IsNullOrEmpty(data["startDate"].GetString())
|
|
? DateTime.Parse(data["startDate"].GetString()!)
|
|
: null;
|
|
|
|
DateTime? endDate = data.ContainsKey("endDate") && !string.IsNullOrEmpty(data["endDate"].GetString())
|
|
? DateTime.Parse(data["endDate"].GetString()!)
|
|
: null;
|
|
|
|
var logs = await _activityLogRepository.GetActivityLogsAsync(
|
|
searchTerm,
|
|
startDate,
|
|
endDate);
|
|
|
|
return logs;
|
|
}
|
|
catch
|
|
{
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
}
|