Spaces:
Running
Running
Download FlowAPI.Application/Services/HabitService.cs from DanilDrotik/FlowAPI: direct link, hf CLI and curl.
- Browser
- Download file 2.71 kB
-
https://huggingface.co/spaces/DanilDrotik/FlowAPI/resolve/ecea7e2cf65ddcb1a751ceab68c14ecad830aa29/FlowAPI.Application/Services/HabitService.cs
- Command line
-
hf download hf://spaces/DanilDrotik/FlowAPI@ecea7e2cf65ddcb1a751ceab68c14ecad830aa29/FlowAPI.Application/Services/HabitService.cs
-
curl -L -o HabitService.cs https://huggingface.co/spaces/DanilDrotik/FlowAPI/resolve/ecea7e2cf65ddcb1a751ceab68c14ecad830aa29/FlowAPI.Application/Services/HabitService.cs
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 | |
| }; | |
| } | |
| } | |