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
1 change: 1 addition & 0 deletions FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<n>`). 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)
Expand Down
14 changes: 10 additions & 4 deletions src/Application/Common/Interfaces/IUserNotificationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,21 @@ Task SendReferralBonusGrantedAsync(
/// </summary>
Task SendFirstOpenReminderAsync(User user, CancellationToken ct);

/// <summary>
/// A first-week message (see <c>FirstWeekNudgeService</c>): the text and one web-app button straight into
/// the lesson, tagged <c>src=push_first_week_d&lt;day&gt;</c>. 403 → user flagged inactive; 429 → single retry.
/// </summary>
/// <summary>
/// The day-7 offer of the old prices (see <c>EngagedOffer</c>): the text and one web-app button that opens the
/// paywall, tagged <c>src=push_engaged_offer</c>. 403 → user flagged inactive; 429 → single retry.
/// </summary>
Task SendEngagedOfferAsync(User user, string text, string button, CancellationToken ct);

/// <summary>
/// A first-week message (see <c>FirstWeekNudgeService</c>): the text and one web-app button straight into
/// the lesson, tagged <c>src=push_first_week_d&lt;day&gt;</c>. 403 → user flagged inactive; 429 → single retry.
/// </summary>
Task SendFirstWeekNudgeAsync(User user, Application.Notifications.FirstWeekNudge nudge, CancellationToken ct);

/// <summary>
/// The tip to pin the chat with the bot (see <c>PinChatTip</c>): plain text, no button. Sent from the
/// lesson-complete request, so no bulk delay and no retry. 403 → user flagged inactive.
/// </summary>
Task SendPinChatTipAsync(User user, string text, CancellationToken ct);
}
35 changes: 34 additions & 1 deletion src/Application/MiniApp/Commands/CompleteLessonProgress.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -17,7 +20,9 @@ public class CompleteLessonProgress : IRequest<CompleteLessonProgressResult>

public class Handler(
ITraleDbContext dbContext,
IProgressCalculator progressCalculator)
IProgressCalculator progressCalculator,
IUserNotificationService notificationService,
ILoggerFactory loggerFactory)
: IRequestHandler<CompleteLessonProgress, CompleteLessonProgressResult>
{
public async Task<CompleteLessonProgressResult> Handle(CompleteLessonProgress request, CancellationToken ct)
Expand All @@ -32,10 +37,38 @@ public async Task<CompleteLessonProgressResult> 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));
}

/// <summary>Once per person; a failure to send never fails the lesson.</summary>
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<CompleteLessonProgress>().LogWarning(ex, "Pin-chat tip for user {UserId} was not sent", userId);
}
}
}
}

Expand Down
49 changes: 49 additions & 0 deletions src/Application/MiniApp/PinChatTip.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System.Text.Json;

namespace Application.MiniApp;

/// <summary>
/// The tip sent once, when a person has got into it — right after a newly finished lesson that makes
/// <see cref="MinLessons"/> 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
/// <see cref="Source"/> never expires.
/// </summary>
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 = "нажми на этот чат правой кнопкой и выбери «Закрепить»";

/// <param name="platform"><c>Telegram.WebApp.platform</c> of the person's last visit; null — unknown, all three ways are listed.</param>
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}
""";
}

/// <summary>Finished lessons in all modules (the welcome scene is not a lesson).</summary>
public static int LessonsDone(string? completedLessonsJson)
{
try
{
var completed = JsonSerializer.Deserialize<Dictionary<string, List<int>>>(completedLessonsJson ?? "") ?? [];
return completed.Where(kv => kv.Key != "onboarding").Sum(kv => kv.Value.Count);
}
catch { return 0; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
147 changes: 147 additions & 0 deletions tests/IntegrationTests/MiniApp/PinChatTipTests.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
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<ITelegramBotClient>();
}

[OneTimeTearDown]
public async Task StopSignedApp() => await _app.DisposeAsync();

private async Task<User> NewUser(Action<User>? configure = null)
{
await using var scope = _app.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<ITraleDbContext>();
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<ITraleDbContext>();
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<SendMessageRequest> SentTo(User user) =>
_telegram.Requests.OfType<SendMessageRequest>().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<ITraleDbContext>();
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<ITraleDbContext>().NotificationTriggers
.AnyAsync(t => t.Source == PinChatTip.Source && t.UserId == silent.TelegramId))
.Should().BeFalse();
}
}
Loading