diff --git a/FEATURES.md b/FEATURES.md index 8f45df5b..32abf055 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -340,7 +340,7 @@ Location: `src/Trale/HostedServices/`. | Hangfire server (`JobQueueSetup.AddJobQueue`, registered in Infrastructure, not a class in this folder) | Continuous | The durable job queue's workers (4 per instance) over the `hangfire` schema of the application database, which Hangfire creates itself on first start. Runs `TranslationQueueJob` → `TranslationJobs.ResumeAsync`. A job whose worker died is delivered again after `JobQueueSetup.InvisibilityTimeout` (1 min, sliding). | | `ReturnPushWorker` | Daily at 10:00 UTC | Dispatch D1+ return push to users who started a lesson but didn't return (#940). | | `CampaignSendWorker` | Every 5s (1s between batches while sending) | Sends the campaigns the owner asked to send to everyone (`send-all`), 25 at a time per campaign, 10 messages per second, waiting out Telegram's 429; touches no other campaign. When one has no one left waiting, its request is cleared atomically (`TryFinishCampaignSendAllAsync`, so with two replicas the owner hears once) and the owner gets a bot message with how many got it. Carries on after a restart. | -| `HourlyNotificationWorker` | Every top-of-hour UTC | Fan-out tick for contextual pushes — calls `IHolidayNotificationService` / `ICoinsNotificationService` / `IStreakNotificationService` / `IFirstOpenReminderService` with fault-isolation. Holiday push uses `TbilisiMorningWindow` to fire only at 09:xx Tbilisi (#997, epic #894). | +| `HourlyNotificationWorker` | Every top-of-hour UTC | Fan-out tick for contextual pushes — calls `IHolidayNotificationService` / `ICoinsNotificationService` / `IStreakNotificationService` / `IFirstOpenReminderService` / `IFirstWeekNudgeService` with fault-isolation. Holiday push uses `TbilisiMorningWindow` to fire only at 09:xx Tbilisi (#997, epic #894). | --- @@ -521,7 +521,8 @@ Validation: loader logs a warning and skips any sentence-builder question whose - `ProcessPendingReferralsService` — batch runner for the worker; after an activation tells the referrer in the bot what they got and until when (a Telegram failure does not undo the bonus) - `FeedTreatService` — buy & feed a treat - `AchievementsService` / `GetAchievementsQuery` — achievements -- `DailyReturnNotificationService` — D1+ return push, picks least-progressed module, claim-before-send (#940) +- `DailyReturnNotificationService` — D1+ return push, picks least-progressed module, claim-before-send (#940); leaves people in their first 8 days to `FirstWeekNudgeService` (once that is switched on) +- `FirstWeekNudgeService` — days 1, 3 and 7 after registration, at about the hour of joining: a message with the next lesson (title and goal from `IMiniAppContentProvider.LessonOrder` — the mini-app's order, Georgian with Cyrillic reading) of the module gone furthest in (the alphabet's first lesson if none is finished) and a button straight into it (`src=push_first_week_d`). Only to those who opened the mini-app and have not studied in the last 20 h; skips blocked users and those with notifications off; a day missed by more than a day is skipped. Only people registered after it was switched on (marker `first_week_switched_on`). Once per day and person: triggers `first_week_d1` / `_d3` / `_d7` never expire - `StreakNotificationService` — streak-milestone push at exact 7 / 30 / 100 days; per-milestone `streak_{n}` trigger (epic #894, §82, #995) - `FirstOpenReminderService` — one reminder from Bombora to a newcomer who started the bot and has not opened the mini-app (no `MiniAppUserProgress` row) 24–72h after registration; same single button as the first message. Skips blocked users and those with notifications off. Only people registered after the reminder was first switched on (marker row `first_open_reminder_switched_on` in `NotificationTriggers`) — never the older base. Once per person: the `first_open_reminder` trigger never expires - `CoinsNotificationService` — coins-stale push when ≥50 spendable XP + no feeding in 7d; 7-day cooldown via `coins` trigger (epic #894, §82, #994) diff --git a/src/Application/Common/Interfaces/IFirstWeekNudgeService.cs b/src/Application/Common/Interfaces/IFirstWeekNudgeService.cs new file mode 100644 index 00000000..743faee6 --- /dev/null +++ b/src/Application/Common/Interfaces/IFirstWeekNudgeService.cs @@ -0,0 +1,11 @@ +namespace Application.Common.Interfaces; + +/// +/// The first week of a newcomer who opened the mini-app: a short message on days 1, 3 and 7 with the +/// next lesson to take. HourlyNotificationWorker calls every hour; +/// the implementation decides who is due and sends each day's message at most once per person. +/// +public interface IFirstWeekNudgeService +{ + Task DispatchAsync(CancellationToken ct); +} diff --git a/src/Application/Common/Interfaces/IUserNotificationService.cs b/src/Application/Common/Interfaces/IUserNotificationService.cs index 12cde1c8..50a95f22 100644 --- a/src/Application/Common/Interfaces/IUserNotificationService.cs +++ b/src/Application/Common/Interfaces/IUserNotificationService.cs @@ -67,4 +67,10 @@ Task SendReferralBonusGrantedAsync( /// first message. 403 → user flagged inactive; 429 → single retry after the suggested delay. /// Task SendFirstOpenReminderAsync(User user, CancellationToken ct); + + /// + /// A first-week message (see FirstWeekNudgeService): the text and one web-app button straight into + /// the lesson, tagged src=push_first_week_d<day>. 403 → user flagged inactive; 429 → single retry. + /// + Task SendFirstWeekNudgeAsync(User user, Application.Notifications.FirstWeekNudge nudge, CancellationToken ct); } diff --git a/src/Application/Common/Interfaces/MiniApp/IMiniAppContentProvider.cs b/src/Application/Common/Interfaces/MiniApp/IMiniAppContentProvider.cs index 254d80f3..a4bf50d1 100644 --- a/src/Application/Common/Interfaces/MiniApp/IMiniAppContentProvider.cs +++ b/src/Application/Common/Interfaces/MiniApp/IMiniAppContentProvider.cs @@ -5,8 +5,19 @@ namespace Application.Common.Interfaces.MiniApp; public interface IMiniAppContentProvider { List GetStarterVocabulary(); + + /// Lessons of a module in the order the mini-app shows them — in the alphabet the words lessons + /// (ids 12+) sit between the letters lessons, so ids are not the order. Empty — no such module. + IReadOnlyList LessonOrder(string moduleId); + + /// The module's title as the mini-app shows it; null — no such module. + string? ModuleTitle(string moduleId); } +/// A lesson for a message to a learner: its title and what it gives. Georgian words in both already +/// carry their Cyrillic reading in brackets — «და (да)». +public record LessonOutline(int Id, string Title, string Goal); + public class StarterWordDto { public string Word { get; set; } diff --git a/src/Application/DependencyInjection.cs b/src/Application/DependencyInjection.cs index 878187b2..53eca454 100644 --- a/src/Application/DependencyInjection.cs +++ b/src/Application/DependencyInjection.cs @@ -49,6 +49,11 @@ public static IServiceCollection AddApplication(this IServiceCollection services services.AddScoped( sp => sp.GetRequiredService()); + // Days 1, 3 and 7 of a newcomer who opened the mini-app: the next lesson to take. + services.AddScoped(); + services.AddScoped( + sp => sp.GetRequiredService()); + // Holiday catalog (#894 / #992). Pure stateless lookup — singleton. services.AddSingleton(); diff --git a/src/Application/Notifications/DailyReturnNotificationService.cs b/src/Application/Notifications/DailyReturnNotificationService.cs index b858ceed..f14c1ccc 100644 --- a/src/Application/Notifications/DailyReturnNotificationService.cs +++ b/src/Application/Notifications/DailyReturnNotificationService.cs @@ -40,9 +40,13 @@ public async Task DispatchAsync(CancellationToken ct) if (progressList.Count == 0) return; + // The first week belongs to FirstWeekNudgeService (days 1, 3, 7 with the next lesson) — once it is on. + var firstWeekSince = await FirstWeekNudgeService.SwitchedOnAtAsync(db, now, ct); + var firstWeekFrom = now - FirstWeekNudgeService.FirstWeek; var userIds = progressList.Select(p => p.UserId).ToList(); var users = await db.Users - .Where(u => userIds.Contains(u.Id) && u.IsActive && u.NotificationsEnabled) + .Where(u => userIds.Contains(u.Id) && u.IsActive && u.NotificationsEnabled + && !(u.RegisteredAtUtc >= firstWeekSince && u.RegisteredAtUtc > firstWeekFrom)) .ToListAsync(ct); if (users.Count == 0) return; diff --git a/src/Application/Notifications/FirstWeekNudgeService.cs b/src/Application/Notifications/FirstWeekNudgeService.cs new file mode 100644 index 00000000..e3233b24 --- /dev/null +++ b/src/Application/Notifications/FirstWeekNudgeService.cs @@ -0,0 +1,145 @@ +using System.Text.Json; +using Application.Common; +using Application.Common.Interfaces; +using Application.Common.Interfaces.MiniApp; +using Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Application.Notifications; + +/// +/// The first week of a newcomer: on days 1, 3 and 7 after registration — at about the hour they joined — +/// one short message with the next lesson of the module they are taking (its title and what it gives) and a +/// button straight into it. Whoever studied in the last 20 hours is left alone that day. +/// +/// Who: opened the mini-app (has a MiniAppUserProgress; those who never opened it get +/// ), has not blocked the bot and has not switched notifications off. +/// Only people registered after the first run of this release (marker ), so +/// the existing base gets nothing. While someone is in their first week, +/// leaves them to these messages. +/// +/// Once per day and person: the trigger first_week_d1 / _d3 / _d7 is claimed before +/// sending and never expires, so neither a second run nor a second instance sends it again. A day that was +/// missed by more than a day (the worker was down) is skipped. +/// +public class FirstWeekNudgeService( + ITraleDbContext db, + IMiniAppContentProvider content, + IUserNotificationService notificationService, + ILoggerFactory loggerFactory) : IFirstWeekNudgeService +{ + private readonly ILogger _logger = loggerFactory.CreateLogger(); + + public static readonly int[] Days = [1, 3, 7]; + public static string SourceFor(int day) => $"first_week_d{day}"; + + /// Marker row: LastSentAt is when the first-week messages were switched on. Not a real user. + public const string SwitchedOnSource = "first_week_switched_on"; + public const long SwitchedOnUserId = 0; + + /// Studied this recently — no need to remind today. + public static readonly TimeSpan RecentlyPlayed = TimeSpan.FromHours(20); + + /// The length of the first week: until then stays away. + public static readonly TimeSpan FirstWeek = TimeSpan.FromDays(8); + + private static readonly DateTime Never = DateTime.UnixEpoch; + + public Task DispatchAsync(CancellationToken ct) => DispatchAsync(DateTime.UtcNow, ct); + + public async Task DispatchAsync(DateTime nowUtc, CancellationToken ct) + { + var switchedOnAt = await SwitchedOnAtAsync(db, nowUtc, ct); + + foreach (var day in Days) + { + var registeredBefore = nowUtc - TimeSpan.FromDays(day); + var registeredAfter = registeredBefore - TimeSpan.FromDays(1); + if (switchedOnAt > registeredBefore) continue; + var source = SourceFor(day); + var playedBefore = nowUtc - RecentlyPlayed; + + var due = await db.Users + .Where(u => u.IsActive && u.NotificationsEnabled + && u.RegisteredAtUtc >= switchedOnAt + && u.RegisteredAtUtc <= registeredBefore + && u.RegisteredAtUtc > registeredAfter + && !db.NotificationTriggers.Any(t => t.UserId == u.TelegramId && t.Source == source)) + .Join(db.MiniAppUserProgresses, u => u.Id, p => p.UserId, (u, p) => new { User = u, Progress = p }) + .Where(x => x.Progress.LastPlayedAtUtc == null || x.Progress.LastPlayedAtUtc < playedBefore) + .ToListAsync(ct); + + foreach (var x in due) + { + var nudge = Build(day, x.Progress.CompletedLessonsJson); + if (nudge == null) continue; // every lesson already taken — nothing to point at + + if (!await db.TryClaimNotificationTriggerAsync(x.User.TelegramId, source, null, nowUtc, Never, ct)) + { + _logger.LogInformation("User {TelegramId} skipped — {Source} already claimed", x.User.TelegramId, source); + continue; + } + + await notificationService.SendFirstWeekNudgeAsync(x.User, nudge, ct); + } + } + + // The sender flags people who have blocked the bot as inactive — keep that. + await db.SaveChangesAsync(ct); + } + + /// The day's message: the next lesson of the module the person has gone furthest in + /// (the alphabet for someone who has not finished a lesson yet). Null — nothing left to take. + public FirstWeekNudge? Build(int day, string completedLessonsJson) + { + var completed = ParseCompletedLessons(completedLessonsJson); + var started = completed + .Select(kv => (Module: kv.Key, Done: kv.Value.ToHashSet(), Order: content.LessonOrder(kv.Key))) + .Where(m => m.Order.Count > 0 && m.Done.Count > 0) + .OrderByDescending(m => m.Done.Count) + .ToList(); + var (module, done, order) = started.Count > 0 + ? started[0] + : (LearningConstants.Modules.Alphabet, new HashSet(), content.LessonOrder(LearningConstants.Modules.Alphabet)); + + var next = order.FirstOrDefault(l => !done.Contains(l.Id)); + if (next == null) return null; + + var lessonsDone = completed.Values.Sum(v => v.Count); + return new FirstWeekNudge(day, Text(day, lessonsDone, content.ModuleTitle(module) ?? "", next), module, next.Id); + } + + internal static string Text(int day, int lessonsDone, string moduleTitle, LessonOutline next) + { + var lesson = $"«{next.Title}» — {moduleTitle}\n{next.Goal}"; + return (day, lessonsDone > 0) switch + { + (1, false) => $"Бомбора ждёт тебя на первом уроке 🐶\n\n{lesson}\n\nОткрой урок — это 2–3 минуты.", + (1, true) => $"Хорошее начало 👏 Следующий урок:\n\n{lesson}\n\nОткрой его — это 2–3 минуты.", + (3, false) => $"Первый урок всё ещё ждёт 🐶\n\n{lesson}\n\nОткрой его сейчас — 2–3 минуты, и первые слова по-грузински твои.", + (3, true) => $"Уроков пройдено: {lessonsDone} 💪 Следующий:\n\n{lesson}\n\nОткрой его — пара минут в день, и буквы начинают читаться сами.", + (_, false) => $"Прошла неделя, а первый урок всё ещё ждёт 🐶\n\n{lesson}\n\nОткрой его — всего 2–3 минуты.", + _ => $"Неделя с грузинским 🇬🇪 Уроков пройдено: {lessonsDone}. Следующий:\n\n{lesson}\n\nОткрой его и держи темп — 2–3 минуты в день.", + }; + } + + /// When the messages were switched on — the first run stores now. Shared with the daily return push. + internal static async Task SwitchedOnAtAsync(ITraleDbContext db, DateTime nowUtc, CancellationToken ct) + { + await db.TryClaimNotificationTriggerAsync(SwitchedOnUserId, SwitchedOnSource, null, nowUtc, Never, ct); + return await db.NotificationTriggers + .Where(t => t.UserId == SwitchedOnUserId && t.Source == SwitchedOnSource) + .Select(t => t.LastSentAt) + .SingleAsync(ct); + } + + private static Dictionary> ParseCompletedLessons(string? json) + { + try { return JsonSerializer.Deserialize>>(json ?? "") ?? []; } + catch { return []; } + } +} + +/// One first-week message: the text and the lesson its button opens. +public record FirstWeekNudge(int Day, string Text, string ModuleId, int LessonId); diff --git a/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs b/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs index ebb25b26..f6e9d2b8 100644 --- a/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs +++ b/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs @@ -435,6 +435,39 @@ await _client.SendTextMessageAsync( await Task.Delay(BulkSendDelay, ct); } + public async Task SendFirstWeekNudgeAsync(Domain.Entities.User user, Application.Notifications.FirstWeekNudge nudge, CancellationToken ct) + { + if (!_botConfig.MiniAppEnabled || string.IsNullOrEmpty(_botConfig.HostAddress)) return; + + var url = $"{_botConfig.NormalizedHost()}/?screen=practice&moduleId={Uri.EscapeDataString(nudge.ModuleId)}&lessonId={nudge.LessonId}&src=push_first_week_d{nudge.Day}"; + var keyboard = new InlineKeyboardMarkup(new[] + { + new[] { InlineKeyboardButton.WithWebApp("Открыть урок", new WebAppInfo { Url = url }) } + }); + + try + { + await _client.SendTextMessageAsync(chatId: user.TelegramId, text: nudge.Text, replyMarkup: keyboard, cancellationToken: ct); + } + catch (ApiRequestException ex) when (ex.ErrorCode == 429) + { + var retryAfterSeconds = ex.Parameters?.RetryAfter ?? 1; + _logger.LogInformation( + "First-week message for {TelegramId} hit rate limit; retrying after {RetryAfter}s", + user.TelegramId, retryAfterSeconds); + await Task.Delay(TimeSpan.FromSeconds(retryAfterSeconds), ct); + await _client.SendTextMessageAsync(chatId: user.TelegramId, text: nudge.Text, replyMarkup: keyboard, cancellationToken: ct); + } + catch (ApiRequestException ex) when (ex.ErrorCode == 403) + { + _logger.LogInformation("First-week message for {TelegramId} blocked (403); marking user inactive", user.TelegramId); + user.IsActive = false; + return; + } + + await Task.Delay(BulkSendDelay, ct); + } + private InlineKeyboardMarkup? BuildReferralBonusKeyboard() { if (!_botConfig.MiniAppEnabled || string.IsNullOrEmpty(_botConfig.HostAddress)) return null; diff --git a/src/Trale/HostedServices/HourlyNotificationWorker.cs b/src/Trale/HostedServices/HourlyNotificationWorker.cs index 16543c5f..6885e0de 100644 --- a/src/Trale/HostedServices/HourlyNotificationWorker.cs +++ b/src/Trale/HostedServices/HourlyNotificationWorker.cs @@ -84,6 +84,7 @@ public async Task RunOnceAsync(DateTime nowUtc, CancellationToken ct) await DispatchSafelyAsync(sp, "Coins", ct); await DispatchSafelyAsync(sp, "Streak", ct); await DispatchSafelyAsync(sp, "FirstOpenReminder", ct); + await DispatchSafelyAsync(sp, "FirstWeekNudge", ct); } private async Task DispatchSafelyAsync(IServiceProvider sp, string contextName, CancellationToken ct) @@ -124,6 +125,7 @@ private static Task InvokeDispatchAsync(TService service, Cancellation ICoinsNotificationService c => c.DispatchAsync(ct), IStreakNotificationService s => s.DispatchAsync(ct), IFirstOpenReminderService f => f.DispatchAsync(ct), + IFirstWeekNudgeService w => w.DispatchAsync(ct), _ => throw new InvalidOperationException( $"Unsupported dispatcher type {typeof(TService).FullName}"), }; diff --git a/src/Trale/MiniApp/MiniAppContentProvider.cs b/src/Trale/MiniApp/MiniAppContentProvider.cs index 0fe733e7..394a4992 100644 --- a/src/Trale/MiniApp/MiniAppContentProvider.cs +++ b/src/Trale/MiniApp/MiniAppContentProvider.cs @@ -24,6 +24,17 @@ public MiniAppContentProvider() public CatalogDto GetCatalog() => _catalog; + public IReadOnlyList LessonOrder(string moduleId) => + _catalog.Modules.FirstOrDefault(m => m.Id == moduleId)?.Lessons + .Select(l => new LessonOutline(l.Id, WithReading(l.Title), WithReading(l.Theory.Goal))).ToList() + ?? (IReadOnlyList)[]; + + public string? ModuleTitle(string moduleId) => _catalog.Modules.FirstOrDefault(m => m.Id == moduleId)?.Title; + + /// Every Georgian word gets its Cyrillic reading in brackets: «Слова: და (да), არა (ара)». + public static string WithReading(string text) => + System.Text.RegularExpressions.Regex.Replace(text, "[\u10D0-\u10FF]+", m => $"{m.Value} ({CyrOf(m.Value)})"); + public List GetAlphabetLessonQuestions(int lessonId) { if (!_alphabetLessonLetters.TryGetValue(lessonId, out var letters)) diff --git a/tests/Application.UnitTests/Notifications/DailyReturnNotificationServiceTests.cs b/tests/Application.UnitTests/Notifications/DailyReturnNotificationServiceTests.cs index f21cb3c0..52e2901e 100644 --- a/tests/Application.UnitTests/Notifications/DailyReturnNotificationServiceTests.cs +++ b/tests/Application.UnitTests/Notifications/DailyReturnNotificationServiceTests.cs @@ -155,4 +155,33 @@ public async Task DispatchAsync_NoXp_PicksEarnVariant() capturedVariant.ShouldBe("earn"); } + + [Test] + public async Task DispatchAsync_NewcomerInTheFirstWeek_IsLeftToTheFirstWeekMessages() + { + // The first-week messages were switched on long ago; this person registered three days ago. + await new FirstWeekNudgeService(Context, Mock.Of(), + _notificationServiceMock.Object, NullLoggerFactory.Instance).DispatchAsync(DateTime.UtcNow.AddDays(-30), CancellationToken.None); + var user = await SeedEligibleUser(); + user.RegisteredAtUtc = DateTime.UtcNow.AddDays(-3); + await Context.SaveChangesAsync(); + + await _sut.DispatchAsync(CancellationToken.None); + + VerifyPushSent(Times.Never()); + } + + [Test] + public async Task DispatchAsync_PersonPastTheFirstWeek_StillGetsTheReturnPush() + { + await new FirstWeekNudgeService(Context, Mock.Of(), + _notificationServiceMock.Object, NullLoggerFactory.Instance).DispatchAsync(DateTime.UtcNow.AddDays(-30), CancellationToken.None); + var user = await SeedEligibleUser(); + user.RegisteredAtUtc = DateTime.UtcNow.AddDays(-9); + await Context.SaveChangesAsync(); + + await _sut.DispatchAsync(CancellationToken.None); + + VerifyPushSent(Times.Once()); + } } diff --git a/tests/Application.UnitTests/Notifications/FirstWeekNudgeServiceTests.cs b/tests/Application.UnitTests/Notifications/FirstWeekNudgeServiceTests.cs new file mode 100644 index 00000000..4906459d --- /dev/null +++ b/tests/Application.UnitTests/Notifications/FirstWeekNudgeServiceTests.cs @@ -0,0 +1,180 @@ +using Application.Common.Interfaces; +using Application.Common.Interfaces.MiniApp; +using Application.Notifications; +using Application.UnitTests.Common; +using Application.UnitTests.DSL; +using Domain.Entities; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Shouldly; + +namespace Application.UnitTests.Notifications; + +public class FirstWeekNudgeServiceTests : CommandTestsBase +{ + private static readonly DateTime Now = new(2026, 11, 20, 12, 0, 0, DateTimeKind.Utc); + private Mock _sender = null!; + private FirstWeekNudgeService _sut = null!; + private readonly List<(long TelegramId, FirstWeekNudge Nudge)> _sent = []; + private long _nextTelegramId = 92000; + + [SetUp] + public void SetUp() + { + _sent.Clear(); + _sender = new Mock(); + _sender.Setup(s => s.SendFirstWeekNudgeAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((u, n, _) => _sent.Add((u.TelegramId, n))) + .Returns(Task.CompletedTask); + var content = new Mock(); + // In the alphabet the words lesson 12 comes right after letters lesson 1. + content.Setup(c => c.LessonOrder("alphabet-progressive")).Returns( + [ + new LessonOutline(1, "Первые буквы", "Три буквы — и первые слова."), + new LessonOutline(12, "Слова: და (да)", "Прочитаешь слова целиком."), + new LessonOutline(2, "Ещё буквы", "Ещё три буквы.") + ]); + content.Setup(c => c.LessonOrder("numbers")).Returns([new LessonOutline(1, "До десяти", "Считаешь до десяти.")]); + content.Setup(c => c.LessonOrder(It.IsNotIn("alphabet-progressive", "numbers"))).Returns([]); + content.Setup(c => c.ModuleTitle("alphabet-progressive")).Returns("Алфавит"); + content.Setup(c => c.ModuleTitle("numbers")).Returns("Числа"); + _sut = new FirstWeekNudgeService(Context, content.Object, _sender.Object, NullLoggerFactory.Instance); + } + + private async Task SwitchedOnLongAgo() => await _sut.DispatchAsync(Now.AddDays(-30), CancellationToken.None); + + private async Task Newcomer(DateTime registeredAt, string? completed = """{"alphabet-progressive":[1]}""", DateTime? lastPlayed = null) + { + var user = Create.User().Build(); + user.TelegramId = _nextTelegramId++; + user.RegisteredAtUtc = registeredAt; + user.IsActive = true; + user.NotificationsEnabled = true; + Context.Users.Add(user); + if (completed != null) + Context.MiniAppUserProgresses.Add(new MiniAppUserProgress + { + Id = Guid.NewGuid(), UserId = user.Id, CompletedLessonsJson = completed, + LastPlayedAtUtc = lastPlayed ?? registeredAt.AddMinutes(10), + CreatedAtUtc = registeredAt, UpdatedAtUtc = registeredAt + }); + await Context.SaveChangesAsync(); + return user; + } + + private IEnumerable SentTo(User user) => _sent.Where(s => s.TelegramId == user.TelegramId).Select(s => s.Nudge); + + [Test] + public async Task First_run_after_the_release_messages_nobody_from_the_existing_base() + { + var old = await Newcomer(Now.AddHours(-24)); + + await _sut.DispatchAsync(Now, CancellationToken.None); + + SentTo(old).ShouldBeEmpty(); + } + + [Test] + public async Task Day_one_points_at_the_next_lesson_in_the_module_order_once() + { + await SwitchedOnLongAgo(); + var user = await Newcomer(Now.AddHours(-24)); + + await _sut.DispatchAsync(Now, CancellationToken.None); + await _sut.DispatchAsync(Now.AddHours(1), CancellationToken.None); + + var nudge = SentTo(user).ShouldHaveSingleItem(); + nudge.Day.ShouldBe(1); + nudge.ModuleId.ShouldBe("alphabet-progressive"); + nudge.LessonId.ShouldBe(12, "after letters lesson 1 come its words, not letters lesson 2"); + nudge.Text.ShouldContain("«Слова: და (да)» — Алфавит"); + nudge.Text.ShouldContain("Хорошее начало"); + } + + [Test] + public async Task Days_three_and_seven_come_at_the_hour_of_registration() + { + await SwitchedOnLongAgo(); + var user = await Newcomer(Now.AddDays(-7), """{"alphabet-progressive":[1,12]}"""); + + await _sut.DispatchAsync(Now.AddDays(-6), CancellationToken.None); + await _sut.DispatchAsync(Now.AddDays(-4), CancellationToken.None); + await _sut.DispatchAsync(Now, CancellationToken.None); + + SentTo(user).Select(n => n.Day).ShouldBe([1, 3, 7]); + SentTo(user).Last().Text.ShouldContain("Уроков пройдено: 2"); + SentTo(user).Last().LessonId.ShouldBe(2); + } + + [Test] + public async Task Whoever_studied_in_the_last_twenty_hours_is_left_alone_that_day() + { + await SwitchedOnLongAgo(); + var user = await Newcomer(Now.AddHours(-24), lastPlayed: Now.AddHours(-3)); + + await _sut.DispatchAsync(Now, CancellationToken.None); + + SentTo(user).ShouldBeEmpty(); + } + + [Test] + public async Task Someone_who_never_opened_the_mini_app_is_left_to_the_first_open_reminder() + { + await SwitchedOnLongAgo(); + var user = await Newcomer(Now.AddHours(-24), completed: null); + + await _sut.DispatchAsync(Now, CancellationToken.None); + + SentTo(user).ShouldBeEmpty(); + } + + [Test] + public async Task Without_a_finished_lesson_the_first_alphabet_lesson_is_offered() + { + await SwitchedOnLongAgo(); + var user = await Newcomer(Now.AddHours(-24), "{}"); + + await _sut.DispatchAsync(Now, CancellationToken.None); + + var nudge = SentTo(user).ShouldHaveSingleItem(); + nudge.LessonId.ShouldBe(1); + nudge.Text.ShouldContain("на первом уроке"); + } + + [Test] + public async Task The_module_gone_furthest_in_is_continued() + { + await SwitchedOnLongAgo(); + var user = await Newcomer(Now.AddHours(-24), """{"alphabet-progressive":[1,12],"numbers":[]}"""); + + await _sut.DispatchAsync(Now, CancellationToken.None); + + SentTo(user).ShouldHaveSingleItem().ModuleId.ShouldBe("alphabet-progressive"); + } + + [Test] + public async Task A_day_missed_by_more_than_a_day_is_skipped() + { + await SwitchedOnLongAgo(); + var user = await Newcomer(Now.AddHours(-49)); + + await _sut.DispatchAsync(Now, CancellationToken.None); + + SentTo(user).ShouldBeEmpty(); + } + + [Test] + public async Task Bot_blocked_or_notifications_off_get_nothing() + { + await SwitchedOnLongAgo(); + var blocked = await Newcomer(Now.AddHours(-24)); + blocked.IsActive = false; + var quiet = await Newcomer(Now.AddHours(-24)); + quiet.NotificationsEnabled = false; + await Context.SaveChangesAsync(); + + await _sut.DispatchAsync(Now, CancellationToken.None); + + _sent.ShouldBeEmpty(); + } +} diff --git a/tests/Infrastructure.UnitTests/LessonOrderForMessagesTests.cs b/tests/Infrastructure.UnitTests/LessonOrderForMessagesTests.cs new file mode 100644 index 00000000..a6635f48 --- /dev/null +++ b/tests/Infrastructure.UnitTests/LessonOrderForMessagesTests.cs @@ -0,0 +1,47 @@ +using System.Text.RegularExpressions; +using Shouldly; +using Trale.MiniApp; + +namespace Infrastructure.UnitTests; + +// Messages to learners (first-week reminders) name the next lesson by its title and goal: the order must be +// the one the mini-app shows, and every Georgian word must come with its Cyrillic reading. +public class LessonOrderForMessagesTests +{ + private static readonly MiniAppContentProvider Content = new(); + + [Test] + public void Alphabet_words_lesson_comes_right_after_its_letters_lesson() + { + var order = Content.LessonOrder("alphabet-progressive").Select(l => l.Id).ToList(); + + order[0].ShouldBe(1); + order[1].ShouldBe(12, "after the first letters lesson come its words, not letters lesson 2"); + order.ShouldContain(2); + Content.ModuleTitle("alphabet-progressive").ShouldBe("Алфавит"); + } + + [Test] + public void Unknown_module_has_no_lessons() => + Content.LessonOrder("no-such-module").ShouldBeEmpty(); + + [Test] + public void Georgian_words_carry_their_reading() + { + MiniAppContentProvider.WithReading("Слова: და, არა").ShouldBe("Слова: და (да), არა (ара)"); + } + + [Test] + public void Every_lesson_title_and_goal_reads_as_whole_words_with_readings() + { + var glued = new Regex("[\\u0400-\\u04FF][\\u10D0-\\u10FF]|[\\u10D0-\\u10FF][\\u0400-\\u04FF]"); + var bare = new Regex("[\\u10D0-\\u10FF]+(?![\\u10D0-\\u10FF]| \\()"); + foreach (var module in Content.GetCatalog().Modules) + foreach (var l in Content.LessonOrder(module.Id)) + foreach (var text in new[] { l.Title, l.Goal }) + { + glued.IsMatch(text).ShouldBeFalse($"{module.Id}/{l.Id}: a Georgian letter glued to Russian — «{text}»"); + bare.IsMatch(text).ShouldBeFalse($"{module.Id}/{l.Id}: Georgian without its reading — «{text}»"); + } + } +}