From d76d6844f620e8d9ff53963770a518aa9ce79932 Mon Sep 17 00:00:00 2001 From: Dmitry Afonchenko Date: Tue, 10 Nov 2026 08:23:09 +0400 Subject: [PATCH 1/2] =?UTF-8?q?=D0=9F=D0=BE=D1=81=D0=BB=D0=B5=20=D0=BF?= =?UTF-8?q?=D0=B5=D1=80=D0=B2=D0=BE=D0=B3=D0=BE=20=D1=83=D1=80=D0=BE=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=B1=D0=BE=D1=82=20=D0=BE=D0=B4=D0=B8=D0=BD=20=D1=80?= =?UTF-8?q?=D0=B0=D0=B7=20=D0=BF=D1=80=D0=BE=D1=81=D0=B8=D1=82=20=D0=B7?= =?UTF-8?q?=D0=B0=D0=BA=D1=80=D0=B5=D0=BF=D0=B8=D1=82=D1=8C=20=D1=87=D0=B0?= =?UTF-8?q?=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01TAcLBj2Fn8nAKE4qWyn5es --- FEATURES.md | 1 + .../Interfaces/IUserNotificationService.cs | 14 ++- .../Commands/CompleteLessonProgress.cs | 29 ++++- src/Application/MiniApp/PinChatTip.cs | 33 +++++ .../Services/TelegramNotificationService.cs | 13 ++ .../MiniApp/PinChatTipTests.cs | 114 ++++++++++++++++++ 6 files changed, 199 insertions(+), 5 deletions(-) create mode 100644 src/Application/MiniApp/PinChatTip.cs create mode 100644 tests/IntegrationTests/MiniApp/PinChatTipTests.cs diff --git a/FEATURES.md b/FEATURES.md index 70ccac01..99e80840 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -521,6 +521,7 @@ 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 +- `PinChatTip` — right after a person's first finished lesson (`CompleteLessonProgress`, onboarding not counted) the bot sends, once, how to pin the chat on iPhone / Android / desktop; plain text, no button; trigger `pin_chat` never expires; skips blocked users and those with notifications off; a failure to send never fails the lesson - `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. On day 7 whoever studies in earnest (`EngagedOffer`: ≥5 finished lessons, onboarding not counted, on ≥2 different days; no payment, no running Pro) gets the offer of the old prices instead of the day-7 message, however recently they studied: trigger `engaged_offer`; after the rise the old prices hold for this person for 72 h (`PriceSchedule.OfferEndsAtAsync` — `/plans` returns `offerEndsAtUtc`, `/purchase` charges the old price, the paywall says until when; message and button say «сниженная цена»); before the rise the message says that buying before it keeps the old prices for good. Button opens the paywall (`?paywall=1&src=push_engaged_offer`) - `StreakNotificationService` — streak-milestone push at exact 7 / 30 / 100 days; per-milestone `streak_{n}` trigger (epic #894, §82, #995) diff --git a/src/Application/Common/Interfaces/IUserNotificationService.cs b/src/Application/Common/Interfaces/IUserNotificationService.cs index 57a20607..cb236f53 100644 --- a/src/Application/Common/Interfaces/IUserNotificationService.cs +++ b/src/Application/Common/Interfaces/IUserNotificationService.cs @@ -68,15 +68,21 @@ Task SendReferralBonusGrantedAsync( /// 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. - /// /// /// The day-7 offer of the old prices (see EngagedOffer): the text and one web-app button that opens the /// paywall, tagged src=push_engaged_offer. 403 → user flagged inactive; 429 → single retry. /// Task SendEngagedOfferAsync(User user, string text, string button, 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); + + /// + /// The tip to pin the chat with the bot (see PinChatTip): plain text, no button. Sent from the + /// lesson-complete request, so no bulk delay and no retry. 403 → user flagged inactive. + /// + Task SendPinChatTipAsync(User user, CancellationToken ct); } diff --git a/src/Application/MiniApp/Commands/CompleteLessonProgress.cs b/src/Application/MiniApp/Commands/CompleteLessonProgress.cs index de77bd79..ec55b043 100644 --- a/src/Application/MiniApp/Commands/CompleteLessonProgress.cs +++ b/src/Application/MiniApp/Commands/CompleteLessonProgress.cs @@ -2,8 +2,11 @@ using System.Threading; using System.Threading.Tasks; using Application.Common; +using Application.Common.Interfaces; using Application.Common.Interfaces.MiniApp; using MediatR; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; namespace Application.MiniApp.Commands; @@ -17,7 +20,9 @@ public class CompleteLessonProgress : IRequest public class Handler( ITraleDbContext dbContext, - IProgressCalculator progressCalculator) + IProgressCalculator progressCalculator, + IUserNotificationService notificationService, + ILoggerFactory loggerFactory) : IRequestHandler { public async Task Handle(CompleteLessonProgress request, CancellationToken ct) @@ -32,10 +37,32 @@ public async Task Handle(CompleteLessonProgress re progress, request.ModuleId, request.LessonId, request.Correct, request.Total); await dbContext.SaveChangesAsync(ct); + if (update.LessonCompleted && PinChatTip.IsFirstLesson(progress.CompletedLessonsJson)) + await SendPinChatTipAsync(request.UserId, ct); + return new CompleteLessonProgressResult.Success( update.XpEarned, progressCalculator.SerializeProgress(progress)); } + + /// Once per person; a failure to send never fails the lesson. + private async Task SendPinChatTipAsync(Guid userId, CancellationToken ct) + { + try + { + var user = await dbContext.Users.FirstOrDefaultAsync(u => u.Id == userId, ct); + if (user is not { IsActive: true, NotificationsEnabled: true }) return; + if (!await dbContext.TryClaimNotificationTriggerAsync(user.TelegramId, PinChatTip.Source, null, DateTime.UtcNow, DateTime.UnixEpoch, ct)) + return; + + await notificationService.SendPinChatTipAsync(user, ct); + await dbContext.SaveChangesAsync(ct); + } + catch (Exception ex) + { + loggerFactory.CreateLogger().LogWarning(ex, "Pin-chat tip for user {UserId} was not sent", userId); + } + } } } diff --git a/src/Application/MiniApp/PinChatTip.cs b/src/Application/MiniApp/PinChatTip.cs new file mode 100644 index 00000000..16a0a53a --- /dev/null +++ b/src/Application/MiniApp/PinChatTip.cs @@ -0,0 +1,33 @@ +using System.Text.Json; + +namespace Application.MiniApp; + +/// +/// The tip sent once, right after a person's first finished lesson: pin the chat with the bot so it does not +/// sink among the others. Trigger never expires. +/// +public static class PinChatTip +{ + public const string Source = "pin_chat"; + + public const string Text = """ + Первый урок пройден 👏 Закрепи этот чат, чтобы не потерять его среди других 📌 + + • iPhone: в списке чатов смахни этот чат вправо и нажми «Закрепить» + • Android: в списке чатов зажми этот чат и нажми на булавку сверху + • Компьютер: нажми на чат правой кнопкой и выбери «Закрепить» + + Так следующий урок всегда будет под рукой. + """; + + /// True when exactly one lesson is finished (the welcome scene is not a lesson). + public static bool IsFirstLesson(string? completedLessonsJson) + { + try + { + var completed = JsonSerializer.Deserialize>>(completedLessonsJson ?? "") ?? []; + return completed.Where(kv => kv.Key != "onboarding").Sum(kv => kv.Value.Count) == 1; + } + catch { return false; } + } +} diff --git a/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs b/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs index 16805fed..cdce3d3c 100644 --- a/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs +++ b/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs @@ -435,6 +435,19 @@ await _client.SendTextMessageAsync( await Task.Delay(BulkSendDelay, ct); } + public async Task SendPinChatTipAsync(Domain.Entities.User user, CancellationToken ct) + { + try + { + await _client.SendTextMessageAsync(chatId: user.TelegramId, text: Application.MiniApp.PinChatTip.Text, cancellationToken: ct); + } + catch (ApiRequestException ex) when (ex.ErrorCode == 403) + { + _logger.LogInformation("Pin-chat tip for {TelegramId} blocked (403); marking user inactive", user.TelegramId); + user.IsActive = false; + } + } + public async Task SendEngagedOfferAsync(Domain.Entities.User user, string text, string button, CancellationToken ct) { if (!_botConfig.MiniAppEnabled || string.IsNullOrEmpty(_botConfig.HostAddress)) return; diff --git a/tests/IntegrationTests/MiniApp/PinChatTipTests.cs b/tests/IntegrationTests/MiniApp/PinChatTipTests.cs new file mode 100644 index 00000000..f7d3af0a --- /dev/null +++ b/tests/IntegrationTests/MiniApp/PinChatTipTests.cs @@ -0,0 +1,114 @@ +using System.Net.Http.Json; +using Application.Common; +using Application.MiniApp; +using Domain.Entities; +using FluentAssertions; +using IntegrationTests.DSL; +using IntegrationTests.Fakes; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Telegram.Bot; +using Telegram.Bot.Requests; + +namespace IntegrationTests.MiniApp; + +/// +/// Right after the first finished lesson the bot asks, once, to pin the chat — so people do not lose it. +/// +public class PinChatTipTests : TestBase +{ + private const long Owner = 4_000_000_201; + private static long _nextTelegramId = 6_200_000_000; + + private TraleTestApplication _app = null!; + private TelegramClientFake _telegram = null!; + + [OneTimeSetUp] + public void StartSignedApp() + { + _app = _testServer.WithSignedLogin(Owner); + _telegram = (TelegramClientFake)_app.Services.GetRequiredService(); + } + + [OneTimeTearDown] + public async Task StopSignedApp() => await _app.DisposeAsync(); + + private async Task NewUser(Action? configure = null) + { + await using var scope = _app.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var user = Create.User(Interlocked.Increment(ref _nextTelegramId), "Newcomer"); + configure?.Invoke(user); + db.Users.Add(user); + await db.SaveChangesAsync(CancellationToken.None); + return user; + } + + private async Task Finish(User user, int lessonId, int correct = 4, string moduleId = "alphabet-progressive") + { + using var client = _app.ClientFor(user.TelegramId); + (await client.PostAsJsonAsync("/api/miniapp/progress/lesson-complete", new { moduleId, lessonId, correct, total = 4 })) + .EnsureSuccessStatusCode(); + } + + private List SentTo(User user) => + _telegram.Requests.OfType().Where(m => m.ChatId.Identifier == user.TelegramId).ToList(); + + [Test] + public async Task The_first_finished_lesson_brings_the_tip_to_pin_the_chat_and_later_lessons_do_not() + { + var user = await NewUser(); + + await Finish(user, 1); + + var tip = SentTo(user).Should().ContainSingle().Subject; + tip.Text.Should().Be(PinChatTip.Text); + tip.Text.Should().StartWith("Первый урок пройден 👏 Закрепи этот чат"); + tip.Text.Should().Contain("iPhone").And.Contain("Android").And.Contain("Компьютер"); + tip.ReplyMarkup.Should().BeNull(); + + await Finish(user, 12); + await Finish(user, 1); + + SentTo(user).Should().ContainSingle("the tip comes once"); + } + + [Test] + public async Task A_lesson_that_did_not_count_brings_nothing_and_the_tip_comes_with_the_one_that_did() + { + var user = await NewUser(); + + await Finish(user, 1, correct: 1); + SentTo(user).Should().BeEmpty(); + + await Finish(user, 1); + SentTo(user).Should().ContainSingle(); + } + + [Test] + public async Task Whoever_already_has_lessons_or_switched_notifications_off_gets_nothing() + { + var old = await NewUser(); + await using (var scope = _app.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.MiniAppUserProgresses.Add(new MiniAppUserProgress + { + Id = Guid.NewGuid(), UserId = old.Id, CompletedLessonsJson = """{"alphabet-progressive":[1,12]}""", + CreatedAtUtc = DateTime.UtcNow, UpdatedAtUtc = DateTime.UtcNow + }); + await db.SaveChangesAsync(CancellationToken.None); + } + var silent = await NewUser(u => u.NotificationsEnabled = false); + + await Finish(old, 2); + await Finish(silent, 1); + + SentTo(old).Should().BeEmpty(); + SentTo(silent).Should().BeEmpty(); + await using var check = _app.Services.CreateAsyncScope(); + (await check.ServiceProvider.GetRequiredService().NotificationTriggers + .AnyAsync(t => t.Source == PinChatTip.Source && (t.UserId == old.TelegramId || t.UserId == silent.TelegramId))) + .Should().BeFalse(); + } +} From aec82650277f7da0d884d308cb2abc52ce9f1824 Mon Sep 17 00:00:00 2001 From: Dmitry Afonchenko Date: Tue, 10 Nov 2026 13:25:44 +0400 Subject: [PATCH 2/2] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D1=81=D1=8C=D0=B1=D0=B0?= =?UTF-8?q?=20=D0=B7=D0=B0=D0=BA=D1=80=D0=B5=D0=BF=D0=B8=D1=82=D1=8C=20?= =?UTF-8?q?=D1=87=D0=B0=D1=82=20=D0=BF=D1=80=D0=B8=D1=85=D0=BE=D0=B4=D0=B8?= =?UTF-8?q?=D1=82=20=D0=BF=D0=BE=D1=81=D0=BB=D0=B5=20=D1=82=D1=80=D0=B5?= =?UTF-8?q?=D1=82=D1=8C=D0=B5=D0=B3=D0=BE=20=D1=83=D1=80=D0=BE=D0=BA=D0=B0?= =?UTF-8?q?,=20=D1=81=D0=BE=20=D1=81=D0=BF=D0=BE=D1=81=D0=BE=D0=B1=D0=BE?= =?UTF-8?q?=D0=BC=20=D0=B4=D0=BB=D1=8F=20=D1=82=D0=B5=D0=BB=D0=B5=D0=B3?= =?UTF-8?q?=D1=80=D0=B0=D0=BC=D0=B0=20=D1=87=D0=B5=D0=BB=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01TAcLBj2Fn8nAKE4qWyn5es --- FEATURES.md | 2 +- .../Interfaces/IUserNotificationService.cs | 2 +- .../Commands/CompleteLessonProgress.cs | 14 +++- src/Application/MiniApp/PinChatTip.cs | 42 +++++++--- .../Services/TelegramNotificationService.cs | 4 +- .../MiniApp/PinChatTipTests.cs | 81 +++++++++++++------ 6 files changed, 100 insertions(+), 45 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index 99e80840..3de19752 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -521,7 +521,7 @@ 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 -- `PinChatTip` — right after a person's first finished lesson (`CompleteLessonProgress`, onboarding not counted) the bot sends, once, how to pin the chat on iPhone / Android / desktop; plain text, no button; trigger `pin_chat` never expires; skips blocked users and those with notifications off; a failure to send never fails the lesson +- `PinChatTip` — once a person has got into it — right after a newly finished lesson that makes 3 or more (`CompleteLessonProgress`, onboarding not counted; so people who already have lessons get it with their next new one) — the bot sends, once, why and how to pin the chat: the way for the Telegram client of their last mini-app visit (`AppEvents.Platform`: iPhone / Android / computer), all three if unknown; plain text, no button; trigger `pin_chat` never expires; skips blocked users and those with notifications off; a failure to send never fails the lesson - `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. On day 7 whoever studies in earnest (`EngagedOffer`: ≥5 finished lessons, onboarding not counted, on ≥2 different days; no payment, no running Pro) gets the offer of the old prices instead of the day-7 message, however recently they studied: trigger `engaged_offer`; after the rise the old prices hold for this person for 72 h (`PriceSchedule.OfferEndsAtAsync` — `/plans` returns `offerEndsAtUtc`, `/purchase` charges the old price, the paywall says until when; message and button say «сниженная цена»); before the rise the message says that buying before it keeps the old prices for good. Button opens the paywall (`?paywall=1&src=push_engaged_offer`) - `StreakNotificationService` — streak-milestone push at exact 7 / 30 / 100 days; per-milestone `streak_{n}` trigger (epic #894, §82, #995) diff --git a/src/Application/Common/Interfaces/IUserNotificationService.cs b/src/Application/Common/Interfaces/IUserNotificationService.cs index cb236f53..5d21571f 100644 --- a/src/Application/Common/Interfaces/IUserNotificationService.cs +++ b/src/Application/Common/Interfaces/IUserNotificationService.cs @@ -84,5 +84,5 @@ Task SendReferralBonusGrantedAsync( /// The tip to pin the chat with the bot (see PinChatTip): plain text, no button. Sent from the /// lesson-complete request, so no bulk delay and no retry. 403 → user flagged inactive. /// - Task SendPinChatTipAsync(User user, CancellationToken ct); + Task SendPinChatTipAsync(User user, string text, CancellationToken ct); } diff --git a/src/Application/MiniApp/Commands/CompleteLessonProgress.cs b/src/Application/MiniApp/Commands/CompleteLessonProgress.cs index ec55b043..813c3505 100644 --- a/src/Application/MiniApp/Commands/CompleteLessonProgress.cs +++ b/src/Application/MiniApp/Commands/CompleteLessonProgress.cs @@ -37,8 +37,9 @@ public async Task Handle(CompleteLessonProgress re progress, request.ModuleId, request.LessonId, request.Correct, request.Total); await dbContext.SaveChangesAsync(ct); - if (update.LessonCompleted && PinChatTip.IsFirstLesson(progress.CompletedLessonsJson)) - await SendPinChatTipAsync(request.UserId, ct); + var lessonsDone = PinChatTip.LessonsDone(progress.CompletedLessonsJson); + if (update.LessonCompleted && lessonsDone >= PinChatTip.MinLessons) + await SendPinChatTipAsync(request.UserId, lessonsDone, ct); return new CompleteLessonProgressResult.Success( update.XpEarned, @@ -46,7 +47,7 @@ public async Task Handle(CompleteLessonProgress re } /// Once per person; a failure to send never fails the lesson. - private async Task SendPinChatTipAsync(Guid userId, CancellationToken ct) + private async Task SendPinChatTipAsync(Guid userId, int lessonsDone, CancellationToken ct) { try { @@ -55,7 +56,12 @@ private async Task SendPinChatTipAsync(Guid userId, CancellationToken ct) if (!await dbContext.TryClaimNotificationTriggerAsync(user.TelegramId, PinChatTip.Source, null, DateTime.UtcNow, DateTime.UnixEpoch, ct)) return; - await notificationService.SendPinChatTipAsync(user, ct); + var platform = await dbContext.AppEvents + .Where(e => e.UserId == userId && e.Platform != null) + .OrderByDescending(e => e.CreatedAtUtc) + .Select(e => e.Platform) + .FirstOrDefaultAsync(ct); + await notificationService.SendPinChatTipAsync(user, PinChatTip.Text(lessonsDone, platform), ct); await dbContext.SaveChangesAsync(ct); } catch (Exception ex) diff --git a/src/Application/MiniApp/PinChatTip.cs b/src/Application/MiniApp/PinChatTip.cs index 16a0a53a..772ae30a 100644 --- a/src/Application/MiniApp/PinChatTip.cs +++ b/src/Application/MiniApp/PinChatTip.cs @@ -3,31 +3,47 @@ namespace Application.MiniApp; /// -/// The tip sent once, right after a person's first finished lesson: pin the chat with the bot so it does not -/// sink among the others. Trigger never expires. +/// The tip sent once, when a person has got into it — right after a newly finished lesson that makes +/// or more: pin the chat with the bot so it does not sink among the others. The way +/// to pin is given for the Telegram client the person last opened the mini-app from. Trigger +/// never expires. /// public static class PinChatTip { public const string Source = "pin_chat"; + public const int MinLessons = 3; - public const string Text = """ - Первый урок пройден 👏 Закрепи этот чат, чтобы не потерять его среди других 📌 + private const string OnIphone = "в списке чатов смахни этот чат вправо и нажми «Закрепить»"; + private const string OnAndroid = "в списке чатов зажми этот чат и нажми на булавку сверху"; + private const string OnComputer = "нажми на этот чат правой кнопкой и выбери «Закрепить»"; - • iPhone: в списке чатов смахни этот чат вправо и нажми «Закрепить» - • Android: в списке чатов зажми этот чат и нажми на булавку сверху - • Компьютер: нажми на чат правой кнопкой и выбери «Закрепить» + /// Telegram.WebApp.platform of the person's last visit; null — unknown, all three ways are listed. + public static string Text(int lessonsDone, string? platform) + { + var how = platform switch + { + "ios" => $"Как закрепить на iPhone: {OnIphone}.", + "android" or "android_x" => $"Как закрепить на Android: {OnAndroid}.", + "tdesktop" or "macos" or "unigram" or "web" or "weba" or "webk" => $"Как закрепить: {OnComputer}.", + _ => $"Как закрепить:\n• iPhone: {OnIphone}\n• Android: {OnAndroid}\n• Компьютер: {OnComputer}", + }; + return $""" + Уроков пройдено: {lessonsDone} 👏 Чтобы не искать Бомбору среди других чатов, закрепи этот чат 📌 - Так следующий урок всегда будет под рукой. - """; + Он всегда будет наверху списка, и следующий урок откроется в одно касание. + + {how} + """; + } - /// True when exactly one lesson is finished (the welcome scene is not a lesson). - public static bool IsFirstLesson(string? completedLessonsJson) + /// Finished lessons in all modules (the welcome scene is not a lesson). + public static int LessonsDone(string? completedLessonsJson) { try { var completed = JsonSerializer.Deserialize>>(completedLessonsJson ?? "") ?? []; - return completed.Where(kv => kv.Key != "onboarding").Sum(kv => kv.Value.Count) == 1; + return completed.Where(kv => kv.Key != "onboarding").Sum(kv => kv.Value.Count); } - catch { return false; } + catch { return 0; } } } diff --git a/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs b/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs index cdce3d3c..19159dd1 100644 --- a/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs +++ b/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs @@ -435,11 +435,11 @@ await _client.SendTextMessageAsync( await Task.Delay(BulkSendDelay, ct); } - public async Task SendPinChatTipAsync(Domain.Entities.User user, CancellationToken ct) + public async Task SendPinChatTipAsync(Domain.Entities.User user, string text, CancellationToken ct) { try { - await _client.SendTextMessageAsync(chatId: user.TelegramId, text: Application.MiniApp.PinChatTip.Text, cancellationToken: ct); + await _client.SendTextMessageAsync(chatId: user.TelegramId, text: text, cancellationToken: ct); } catch (ApiRequestException ex) when (ex.ErrorCode == 403) { diff --git a/tests/IntegrationTests/MiniApp/PinChatTipTests.cs b/tests/IntegrationTests/MiniApp/PinChatTipTests.cs index f7d3af0a..f20adac5 100644 --- a/tests/IntegrationTests/MiniApp/PinChatTipTests.cs +++ b/tests/IntegrationTests/MiniApp/PinChatTipTests.cs @@ -13,7 +13,8 @@ namespace IntegrationTests.MiniApp; /// -/// Right after the first finished lesson the bot asks, once, to pin the chat — so people do not lose it. +/// Once a person has got into it (the third finished lesson) the bot asks, once, to pin the chat — and says how +/// on the Telegram client they use. /// public class PinChatTipTests : TestBase { @@ -51,42 +52,49 @@ private async Task Finish(User user, int lessonId, int correct = 4, string modul .EnsureSuccessStatusCode(); } + private async Task Opened(User user, string platform) + { + await using var scope = _app.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.AppEvents.Add(new AppEvent { Id = Guid.NewGuid(), UserId = user.Id, Event = "app_open", Platform = platform, CreatedAtUtc = DateTime.UtcNow }); + await db.SaveChangesAsync(CancellationToken.None); + } + private List SentTo(User user) => _telegram.Requests.OfType().Where(m => m.ChatId.Identifier == user.TelegramId).ToList(); [Test] - public async Task The_first_finished_lesson_brings_the_tip_to_pin_the_chat_and_later_lessons_do_not() + public async Task The_third_finished_lesson_brings_the_tip_for_the_persons_telegram_and_later_lessons_do_not() { var user = await NewUser(); + await Opened(user, "ios"); await Finish(user, 1); + await Finish(user, 12); + await Finish(user, 12); + await Finish(user, 2, correct: 1); + SentTo(user).Should().BeEmpty("two lessons are finished so far"); - var tip = SentTo(user).Should().ContainSingle().Subject; - tip.Text.Should().Be(PinChatTip.Text); - tip.Text.Should().StartWith("Первый урок пройден 👏 Закрепи этот чат"); - tip.Text.Should().Contain("iPhone").And.Contain("Android").And.Contain("Компьютер"); - tip.ReplyMarkup.Should().BeNull(); + await Finish(user, 2); - await Finish(user, 12); - await Finish(user, 1); + var tip = SentTo(user).Should().ContainSingle().Subject; + tip.Text.Should().Be(""" + Уроков пройдено: 3 👏 Чтобы не искать Бомбору среди других чатов, закрепи этот чат 📌 - SentTo(user).Should().ContainSingle("the tip comes once"); - } + Он всегда будет наверху списка, и следующий урок откроется в одно касание. - [Test] - public async Task A_lesson_that_did_not_count_brings_nothing_and_the_tip_comes_with_the_one_that_did() - { - var user = await NewUser(); + Как закрепить на iPhone: в списке чатов смахни этот чат вправо и нажми «Закрепить». + """); + tip.ReplyMarkup.Should().BeNull(); - await Finish(user, 1, correct: 1); - SentTo(user).Should().BeEmpty(); + await Finish(user, 13); + await Finish(user, 1, moduleId: "numbers"); - await Finish(user, 1); - SentTo(user).Should().ContainSingle(); + SentTo(user).Should().ContainSingle("the tip comes once"); } [Test] - public async Task Whoever_already_has_lessons_or_switched_notifications_off_gets_nothing() + public async Task Whoever_already_has_lessons_gets_the_tip_with_the_next_new_one() { var old = await NewUser(); await using (var scope = _app.Services.CreateAsyncScope()) @@ -94,21 +102,46 @@ public async Task Whoever_already_has_lessons_or_switched_notifications_off_gets var db = scope.ServiceProvider.GetRequiredService(); db.MiniAppUserProgresses.Add(new MiniAppUserProgress { - Id = Guid.NewGuid(), UserId = old.Id, CompletedLessonsJson = """{"alphabet-progressive":[1,12]}""", + Id = Guid.NewGuid(), UserId = old.Id, CompletedLessonsJson = """{"alphabet-progressive":[1,12,2,13],"onboarding":[1]}""", CreatedAtUtc = DateTime.UtcNow, UpdatedAtUtc = DateTime.UtcNow }); await db.SaveChangesAsync(CancellationToken.None); } + await Opened(old, "ios"); + await Opened(old, "android"); + + await Finish(old, 1); + SentTo(old).Should().BeEmpty("a lesson taken again is not a new one"); + + await Finish(old, 3); + + var tip = SentTo(old).Should().ContainSingle().Subject; + tip.Text.Should().StartWith("Уроков пройдено: 5 👏"); + tip.Text.Should().EndWith("Как закрепить на Android: в списке чатов зажми этот чат и нажми на булавку сверху."); + } + + [Test] + public void The_way_to_pin_follows_the_telegram_client_and_all_three_are_listed_when_it_is_unknown() + { + PinChatTip.Text(3, "tdesktop").Should().EndWith("Как закрепить: нажми на этот чат правой кнопкой и выбери «Закрепить»."); + PinChatTip.Text(3, "macos").Should().Contain("правой кнопкой").And.NotContain("iPhone"); + PinChatTip.Text(3, null).Should().Contain("• iPhone:").And.Contain("• Android:").And.Contain("• Компьютер:"); + PinChatTip.Text(3, "something-new").Should().Contain("• iPhone:"); + } + + [Test] + public async Task Whoever_switched_notifications_off_gets_nothing() + { var silent = await NewUser(u => u.NotificationsEnabled = false); - await Finish(old, 2); await Finish(silent, 1); + await Finish(silent, 12); + await Finish(silent, 2); - SentTo(old).Should().BeEmpty(); SentTo(silent).Should().BeEmpty(); await using var check = _app.Services.CreateAsyncScope(); (await check.ServiceProvider.GetRequiredService().NotificationTriggers - .AnyAsync(t => t.Source == PinChatTip.Source && (t.UserId == old.TelegramId || t.UserId == silent.TelegramId))) + .AnyAsync(t => t.Source == PinChatTip.Source && t.UserId == silent.TelegramId)) .Should().BeFalse(); } }