FlowAPI / FlowAPI.Application /Services /HabitService.cs
danylokhodus's picture
init
b9c7f0e
Raw History Blame
2.71 kB
using FlowAPI.Application.DTOs.Habit;
using FlowAPI.Application.Interfaces;
using FlowAPI.Domain.Entities;
namespace FlowAPI.Application.Services
{
public class HabitService : IHabitService
{
private readonly IHabitRecordRepository _repo;
private readonly IAchievementService _achievementService;
public HabitService(IHabitRecordRepository repo, IAchievementService achievementService)
{
_repo = repo;
_achievementService = achievementService;
}
public async Task<IEnumerable<HabitRecordResponseDto>> GetAllByUserIdAsync(Guid userId)
{
var records = await _repo.GetAllByUserIdAsync(userId);
return records.Select(MapToDto);
}
public async Task<HabitRecordResponseDto> RecordHabitAsync(CreateHabitRecordDto dto)
{
var existing = await _repo.GetTodayRecordAsync(dto.UserId, dto.HabitName);
if (existing is not null) return MapToDto(existing);
var record = new HabitRecord
{
Id = Guid.NewGuid(),
UserId = dto.UserId,
HabitName = dto.HabitName,
CheckedDate = DateTime.UtcNow
};
var created = await _repo.CreateAsync(record);
await _achievementService.ProcessEventAsync(dto.UserId, "HabitTracked");
return MapToDto(created);
}
public async Task<int> GetStreakAsync(Guid userId, string habitName)
{
var records = await _repo.GetAllByUserIdAsync(userId);
var habitRecords = records
.Where(r => r.HabitName == habitName)
.OrderByDescending(r => r.CheckedDate)
.ToList();
if (!habitRecords.Any()) return 0;
int streak = 0;
DateTime expectedDate = DateTime.UtcNow.Date;
foreach (var record in habitRecords)
{
if (record.CheckedDate.Date == expectedDate)
{
streak++;
expectedDate = expectedDate.AddDays(-1);
}
else if (record.CheckedDate.Date > expectedDate)
{
continue;
}
else
{
break;
}
}
return streak;
}
private static HabitRecordResponseDto MapToDto(HabitRecord record) => new()
{
Id = record.Id,
UserId = record.UserId,
HabitName = record.HabitName,
CheckedDate = record.CheckedDate
};
}
}