diff --git a/FEATURES.md b/FEATURES.md index 70ccac01..3de19752 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` — 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 57a20607..5d21571f 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, string text, CancellationToken ct); } diff --git a/src/Application/MiniApp/Commands/CompleteLessonProgress.cs b/src/Application/MiniApp/Commands/CompleteLessonProgress.cs index de77bd79..813c3505 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,38 @@ public async Task Handle(CompleteLessonProgress re progress, request.ModuleId, request.LessonId, request.Correct, request.Total); await dbContext.SaveChangesAsync(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, progressCalculator.SerializeProgress(progress)); } + + /// Once per person; a failure to send never fails the lesson. + private async Task SendPinChatTipAsync(Guid userId, int lessonsDone, 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; + + 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) + { + 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..772ae30a --- /dev/null +++ b/src/Application/MiniApp/PinChatTip.cs @@ -0,0 +1,49 @@ +using System.Text.Json; + +namespace Application.MiniApp; + +/// +/// 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; + + private const string OnIphone = "в списке чатов смахни этот чат вправо и нажми «Закрепить»"; + private const string OnAndroid = "в списке чатов зажми этот чат и нажми на булавку сверху"; + private const string OnComputer = "нажми на этот чат правой кнопкой и выбери «Закрепить»"; + + /// 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} + """; + } + + /// 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); + } + catch { return 0; } + } +} diff --git a/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs b/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs index 16805fed..19159dd1 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, string text, CancellationToken ct) + { + try + { + await _client.SendTextMessageAsync(chatId: user.TelegramId, text: 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..f20adac5 --- /dev/null +++ b/tests/IntegrationTests/MiniApp/PinChatTipTests.cs @@ -0,0 +1,147 @@ +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; + +/// +/// 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 +{ + 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 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_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"); + + await Finish(user, 2); + + var tip = SentTo(user).Should().ContainSingle().Subject; + tip.Text.Should().Be(""" + Уроков пройдено: 3 👏 Чтобы не искать Бомбору среди других чатов, закрепи этот чат 📌 + + Он всегда будет наверху списка, и следующий урок откроется в одно касание. + + Как закрепить на iPhone: в списке чатов смахни этот чат вправо и нажми «Закрепить». + """); + tip.ReplyMarkup.Should().BeNull(); + + await Finish(user, 13); + await Finish(user, 1, moduleId: "numbers"); + + SentTo(user).Should().ContainSingle("the tip comes once"); + } + + [Test] + 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()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.MiniAppUserProgresses.Add(new MiniAppUserProgress + { + 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(silent, 1); + await Finish(silent, 12); + await Finish(silent, 2); + + SentTo(silent).Should().BeEmpty(); + await using var check = _app.Services.CreateAsyncScope(); + (await check.ServiceProvider.GetRequiredService().NotificationTriggers + .AnyAsync(t => t.Source == PinChatTip.Source && t.UserId == silent.TelegramId)) + .Should().BeFalse(); + } +}