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
7 changes: 7 additions & 0 deletions src/Orbit.Api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -17360,6 +17360,13 @@
"isOneTime": {
"type": "boolean",
"default": false
},
"habitId": {
"type": [
"null",
"string"
],
"format": "uuid"
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ public record RetrospectiveHabitStat(
int CompletionRate,
int CompletedCount,
int ScheduledCount,
bool IsOneTime = false);
bool IsOneTime = false,
Guid? HabitId = null);

/// <summary>Structured habit metrics for a retrospective or recap.</summary>
/// <param name="WeeklyConsistency">Seven weekday percentages ordered Monday through Sunday.</param>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,8 @@ private static RetrospectiveHabitStat BuildHabitStat(
Percent(metCount, scheduledCount),
completedCount,
scheduledCount,
habit.FrequencyUnit is null);
habit.FrequencyUnit is null,
habit.Id);

private static int[] BuildWeeklyConsistency(int[] weekdayScheduled, int[] weekdayCompleted)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ public async Task LoadAsync_WithHabits_MapsEveryCountToItsMetric()
var user = CreateUser(streak: 9);
var habit = CreateHabitWithStreak(5);
var oldLog = habit.Log(Today.AddDays(-65), advanceDueDate: false).Value;
typeof(HabitLog).GetProperty(nameof(HabitLog.CreatedAtUtc))!
.SetValue(oldLog, oldLog.Date.ToDateTime(new TimeOnly(12, 0), DateTimeKind.Utc));
StubHabits(habit);
StubCounts();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
using Orbit.Domain.Interfaces;
using Orbit.Domain.Models;
using System.Linq.Expressions;
using System.Text.Json;
using Orbit.Application.Common;
using Orbit.Application.Chat;
using Orbit.Application.Habits.Services;

namespace Orbit.Application.Tests.Queries.Habits;

Expand Down Expand Up @@ -173,6 +176,12 @@ public async Task Handle_TopHabits_OrderedByHighestRateFirst()
top[0].CompletionRate.Should().Be(100);
top[0].Emoji.Should().BeNull();
top[1].Name.Should().Be("Weak");

var response = JsonSerializer.SerializeToElement(result.Value, new JsonSerializerOptions(JsonSerializerDefaults.Web));
var serializedTop = response.GetProperty("metrics").GetProperty("topHabits");
serializedTop[0].TryGetProperty("habitId", out var strongId).Should().BeTrue();
strongId.GetGuid().Should().Be(strong.Id);
serializedTop[1].GetProperty("habitId").GetGuid().Should().Be(weak.Id);
}

[Fact]
Expand All @@ -196,6 +205,12 @@ public async Task Handle_NeedsAttention_OrderedByLowestRate_ExcludesPerfectHabit
needs.Should().NotContain(s => s.Name == "Perfect");
needs[0].Name.Should().Be("Weak");
needs[1].Name.Should().Be("Middling");

var response = JsonSerializer.SerializeToElement(result.Value, new JsonSerializerOptions(JsonSerializerDefaults.Web));
var serializedNeeds = response.GetProperty("metrics").GetProperty("needsAttention");
serializedNeeds[0].TryGetProperty("habitId", out var weakId).Should().BeTrue();
weakId.GetGuid().Should().Be(weak.Id);
serializedNeeds[1].GetProperty("habitId").GetGuid().Should().Be(middling.Id);
}

[Fact]
Expand Down Expand Up @@ -242,6 +257,35 @@ public async Task Handle_ReturnsCachedResult_WhenCached()
result.Value.Narrative.Should().Be(SampleNarrative);
}

[Fact]
public async Task Handle_CachedStatWithoutHabitId_RemainsReadableByInsightCard()
{
var legacyStat = JsonSerializer.Deserialize<RetrospectiveHabitStat>(
"""{"name":"Read","emoji":null,"completionRate":14,"completedCount":1,"scheduledCount":7,"isOneTime":false}""",
new JsonSerializerOptions(JsonSerializerDefaults.Web));
legacyStat.Should().NotBeNull();
legacyStat!.HabitId.Should().BeNull();
new RetrospectiveHabitStat("Read", null, 14, 1, 7).HabitId.Should().BeNull();
var metrics = RetrospectiveMetricsCalculator.Compute([CreateLoggedHabit()], DateFrom, DateTo, 4, 9)
with
{ TopHabits = [legacyStat], NeedsAttention = [legacyStat] };
_cache.Set(RetrospectiveCacheKey.Build(UserId, "week", DateFrom, "en"),
new RetrospectiveResponse("week", metrics, SampleNarrative, false, DateFrom, DateTo));

var result = await HandleWeek();

result.IsSuccess.Should().BeTrue();
result.Value.FromCache.Should().BeTrue();
var card = PeriodInsightCardBuilder.Build(result.Value);
card.Should().NotBeNull();
card!.TopHabits.Should().ContainSingle().Which.HabitId.Should().BeNull();
card.NeedsAttention.Should().ContainSingle().Which.HabitId.Should().BeNull();
await _habitRepo.DidNotReceive().FindAsync(
Arg.Any<Expression<Func<Habit, bool>>>(),
Arg.Any<Func<IQueryable<Habit>, IQueryable<Habit>>?>(),
Arg.Any<CancellationToken>());
}

[Fact]
public async Task Handle_CacheHit_DoesNotRegenerateNarrative()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using FluentAssertions;
using Orbit.Application.Chat;
using Orbit.Application.Habits.Queries;
using Orbit.Application.Habits.Services;
using Orbit.Domain.Entities;
using Orbit.Domain.Enums;
using Orbit.Domain.Models;

namespace Orbit.Application.Tests.Services;

public class RetrospectiveHabitStatTests
{
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Compute_HabitRankingsAndInsightCard_PreserveIdsForDuplicateTitles(bool historical)
{
var from = new DateOnly(2026, 3, 2);
var to = from.AddDays(6);
var userId = Guid.NewGuid();
var strong = Habit.Create(new HabitCreateParams(userId, "Read", FrequencyUnit.Day, 1, from)).Value;
var weak = Habit.Create(new HabitCreateParams(userId, "Read", FrequencyUnit.Day, 1, from)).Value;
foreach (var habit in new[] { strong, weak })
typeof(Habit).GetProperty(nameof(Habit.CreatedAtUtc))!.SetValue(
habit, from.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc));
for (var i = 0; i < 7; i++)
strong.Log(from.AddDays(i), advanceDueDate: false).IsSuccess.Should().BeTrue();
weak.Log(from, advanceDueDate: false).IsSuccess.Should().BeTrue();

var metrics = historical
? RetrospectiveMetricsCalculator.ComputeHistorical([strong, weak], from, to, 0, 0, TimeZoneInfo.Utc)
: RetrospectiveMetricsCalculator.Compute([strong, weak], from, to, 0, 0);

metrics.TopHabits.Select(stat => stat.HabitId).Should().Equal(strong.Id, weak.Id);
metrics.NeedsAttention.Should().ContainSingle().Which.HabitId.Should().Be(weak.Id);
var card = PeriodInsightCardBuilder.Build(new RetrospectiveResponse(
"week", metrics, new RetrospectiveNarrative("Highlights", "Missed", "Trends", "Suggestion"),
false, from, to));
card.Should().NotBeNull();
card!.TopHabits.Select(stat => stat.HabitId).Should().Equal(strong.Id, weak.Id);
card.NeedsAttention.Should().ContainSingle().Which.HabitId.Should().Be(weak.Id);
}
}
Loading