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
25 changes: 18 additions & 7 deletions src/Orbit.Application/Gamification/Queries/GetStreakInfoQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
public class GetStreakInfoQueryHandler(
IGenericRepository<User> userRepository,
IGenericRepository<StreakFreeze> streakFreezeRepository,
IUserDateService userDateService) : IRequestHandler<GetStreakInfoQuery, Result<StreakInfoResponse>>
IUserDateService userDateService,
IUserStreakService userStreakService,
IUnitOfWork unitOfWork) : IRequestHandler<GetStreakInfoQuery, Result<StreakInfoResponse>>
{
public async Task<Result<StreakInfoResponse>> Handle(GetStreakInfoQuery request, CancellationToken cancellationToken)
{
Expand All @@ -37,6 +39,15 @@
if (!user.HasProAccess)
return Result.PayGateFailure<StreakInfoResponse>("Streak insights are a Pro feature. Upgrade to unlock!");

var recalculatedStreak = await userStreakService.RecalculateAsync(
request.UserId, cancellationToken, awardFreezeIfEligible: false);
if (recalculatedStreak is not null)
await unitOfWork.SaveChangesAsync(cancellationToken);

var currentStreak = recalculatedStreak?.CurrentStreak ?? user.CurrentStreak;
var longestStreak = recalculatedStreak?.LongestStreak ?? user.LongestStreak;
var lastActiveDate = recalculatedStreak?.LastActiveDate ?? user.LastActiveDate;

var today = await userDateService.GetUserTodayAsync(request.UserId, cancellationToken);

var monthStart = new DateOnly(today.Year, today.Month, 1);
Expand All @@ -56,11 +67,11 @@

var freezesAvailableToUse = Math.Min(user.StreakFreezesAccumulated, remainingMonthlyQuota);

var daysSinceLastAward = Math.Max(0, user.CurrentStreak - user.LastFreezeAwardStreak);
var daysUntilNextFreeze = user.CurrentStreak <= 0
var daysSinceLastAward = Math.Max(0, currentStreak - user.LastFreezeAwardStreak);
var daysUntilNextFreeze = currentStreak <= 0
? AppConstants.StreakDaysPerFreeze
: Math.Max(0, AppConstants.StreakDaysPerFreeze - (daysSinceLastAward % AppConstants.StreakDaysPerFreeze));
if (daysUntilNextFreeze == 0 && user.CurrentStreak > 0 && user.StreakFreezesAccumulated >= AppConstants.MaxStreakFreezesAccumulated)
if (daysUntilNextFreeze == 0 && currentStreak > 0 && user.StreakFreezesAccumulated >= AppConstants.MaxStreakFreezesAccumulated)

Check warning on line 74 in src/Orbit.Application/Gamification/Queries/GetStreakInfoQuery.cs

View workflow job for this annotation

GitHub Actions / SonarCloud Analysis

Change this condition so that it does not always evaluate to 'True'.

Check warning on line 74 in src/Orbit.Application/Gamification/Queries/GetStreakInfoQuery.cs

View workflow job for this annotation

GitHub Actions / SonarCloud Analysis

Change this condition so that it does not always evaluate to 'True'.

Check warning on line 74 in src/Orbit.Application/Gamification/Queries/GetStreakInfoQuery.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Change this condition so that it does not always evaluate to 'True'.

See more on https://sonarcloud.io/project/issues?id=thomasluizon_orbit-api&issues=AZ68k1uaA5hZo2luyIuK&open=AZ68k1uaA5hZo2luyIuK&pullRequest=203
{
daysUntilNextFreeze = AppConstants.StreakDaysPerFreeze;
}
Expand All @@ -73,9 +84,9 @@
.ToList();

return Result.Success(new StreakInfoResponse(
user.CurrentStreak,
user.LongestStreak,
user.LastActiveDate,
currentStreak,
longestStreak,
lastActiveDate,
freezesUsedThisMonth,
user.StreakFreezesAccumulated,
AppConstants.MaxStreakFreezesPerMonth,
Expand Down
6 changes: 3 additions & 3 deletions src/Orbit.Infrastructure/Services/AiSummaryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public sealed partial class AiSummaryService(
AiCompletionClient aiClient,
ILogger<AiSummaryService> logger) : ISummaryService
{
private const int MaxSummaryChars = 140;
private const int MaxSummaryChars = 300;

public async Task<Result<string>> GenerateSummaryAsync(
IEnumerable<Habit> allHabits,
Expand All @@ -37,7 +37,7 @@ public async Task<Result<string>> GenerateSummaryAsync(
prompt,
temperature: 0.7,
cancellationToken,
maxOutputTokens: 120);
maxOutputTokens: 180);

if (string.IsNullOrWhiteSpace(text))
return Result.Failure<string>("AI returned empty response");
Expand Down Expand Up @@ -121,7 +121,7 @@ Write a short message to this person about their day.
- Describe the ACTIVITY naturally, don't just parrot the exact habit title
- BAD: "You have Yoga, Morning Routine, and Guitar Playing left."
- GOOD: "Nice work getting your run in -- some guitar later could be a great way to unwind."
- Keep it to ONE short sentence -- two very short ones only when the day truly needs both -- under ~140 characters total, warm and close, like a friend who actually knows you -- never corporate or coach-like
- Keep it to TWO short sentences -- three only when the day truly needs them -- under ~300 characters total, warm and close, like a friend who actually knows you -- never corporate or coach-like
- This message is shown for the WHOLE current part of the day, so it must read correctly whether they see it at the start or the end of that window
- Treat the time of day as a broad window, not an exact moment; never imply a precise instant
- Do NOT use phrases like "right now", "just woke up", "now that the afternoon is here", "as the day begins", "earlier today", or "upcoming later today"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Orbit.Application.Gamification.Queries;
using Orbit.Domain.Entities;
using Orbit.Domain.Interfaces;
using Orbit.Domain.Models;
using System.Linq.Expressions;

namespace Orbit.Application.Tests.Queries.Gamification;
Expand All @@ -12,14 +13,17 @@ public class GetStreakInfoQueryHandlerTests
private readonly IGenericRepository<User> _userRepo = Substitute.For<IGenericRepository<User>>();
private readonly IGenericRepository<StreakFreeze> _streakFreezeRepo = Substitute.For<IGenericRepository<StreakFreeze>>();
private readonly IUserDateService _userDateService = Substitute.For<IUserDateService>();
private readonly IUserStreakService _userStreakService = Substitute.For<IUserStreakService>();
private readonly IUnitOfWork _unitOfWork = Substitute.For<IUnitOfWork>();
private readonly GetStreakInfoQueryHandler _handler;

private static readonly Guid UserId = Guid.NewGuid();
private static readonly DateOnly Today = new(2026, 4, 3);

public GetStreakInfoQueryHandlerTests()
{
_handler = new GetStreakInfoQueryHandler(_userRepo, _streakFreezeRepo, _userDateService);
_handler = new GetStreakInfoQueryHandler(
_userRepo, _streakFreezeRepo, _userDateService, _userStreakService, _unitOfWork);
_userDateService.GetUserTodayAsync(UserId, Arg.Any<CancellationToken>()).Returns(Today);
}

Expand Down Expand Up @@ -57,6 +61,31 @@ public async Task Handle_UserFound_ReturnsStreakInfo()
result.Value.RecentFreezeDates.Should().BeEmpty();
}

[Fact]
public async Task Handle_RecalculatesStreakOnRead_AndReturnsFreshValues()
{
var user = CreateTestUser();
_userRepo.GetByIdAsync(UserId, Arg.Any<CancellationToken>()).Returns(user);

_userStreakService.RecalculateAsync(UserId, Arg.Any<CancellationToken>(), awardFreezeIfEligible: false)
.Returns(new UserStreakState(11, 43, Today));

_streakFreezeRepo.FindAsync(
Arg.Any<Expression<Func<StreakFreeze, bool>>>(),
Arg.Any<CancellationToken>())
.Returns(new List<StreakFreeze>().AsReadOnly());

var query = new GetStreakInfoQuery(UserId);

var result = await _handler.Handle(query, CancellationToken.None);

result.IsSuccess.Should().BeTrue();
result.Value.CurrentStreak.Should().Be(11);
result.Value.LongestStreak.Should().Be(43);
result.Value.LastActiveDate.Should().Be(Today);
await _unitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
}

[Fact]
public async Task Handle_UserNotFound_ReturnsFailure()
{
Expand Down
Loading