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
5 changes: 3 additions & 2 deletions FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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). |

---

Expand Down Expand Up @@ -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<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
- `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)
Expand Down
11 changes: 11 additions & 0 deletions src/Application/Common/Interfaces/IFirstWeekNudgeService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Application.Common.Interfaces;

/// <summary>
/// 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. <c>HourlyNotificationWorker</c> calls <see cref="DispatchAsync"/> every hour;
/// the implementation decides who is due and sends each day's message at most once per person.
/// </summary>
public interface IFirstWeekNudgeService
{
Task DispatchAsync(CancellationToken ct);
}
6 changes: 6 additions & 0 deletions src/Application/Common/Interfaces/IUserNotificationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,10 @@ Task SendReferralBonusGrantedAsync(
/// first message. 403 → user flagged inactive; 429 → single retry after the suggested delay.
/// </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>
Task SendFirstWeekNudgeAsync(User user, Application.Notifications.FirstWeekNudge nudge, CancellationToken ct);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,19 @@
public interface IMiniAppContentProvider
{
List<StarterWordDto> GetStarterVocabulary();

/// <summary>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.</summary>
IReadOnlyList<LessonOutline> LessonOrder(string moduleId);

/// <summary>The module's title as the mini-app shows it; null — no such module.</summary>
string? ModuleTitle(string moduleId);
}

/// <summary>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 — «და (да)».</summary>
public record LessonOutline(int Id, string Title, string Goal);

public class StarterWordDto
{
public string Word { get; set; }
Expand All @@ -14,7 +25,7 @@
public string Example { get; set; }
public string? AudioUrl { get; set; }

public StarterWordDto() { }

Check warning on line 28 in src/Application/Common/Interfaces/MiniApp/IMiniAppContentProvider.cs

View workflow job for this annotation

GitHub Actions / test

Non-nullable property 'Example' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 28 in src/Application/Common/Interfaces/MiniApp/IMiniAppContentProvider.cs

View workflow job for this annotation

GitHub Actions / test

Non-nullable property 'Definition' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 28 in src/Application/Common/Interfaces/MiniApp/IMiniAppContentProvider.cs

View workflow job for this annotation

GitHub Actions / test

Non-nullable property 'Word' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

public StarterWordDto(string word, string definition, string example, string? audioUrl = null)
{
Expand Down
5 changes: 5 additions & 0 deletions src/Application/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ public static IServiceCollection AddApplication(this IServiceCollection services
services.AddScoped<IFirstOpenReminderService>(
sp => sp.GetRequiredService<FirstOpenReminderService>());

// Days 1, 3 and 7 of a newcomer who opened the mini-app: the next lesson to take.
services.AddScoped<FirstWeekNudgeService>();
services.AddScoped<IFirstWeekNudgeService>(
sp => sp.GetRequiredService<FirstWeekNudgeService>());

// Holiday catalog (#894 / #992). Pure stateless lookup — singleton.
services.AddSingleton<IHolidayCalendarService, HolidayCalendarService>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
145 changes: 145 additions & 0 deletions src/Application/Notifications/FirstWeekNudgeService.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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 <c>MiniAppUserProgress</c>; those who never opened it get
/// <see cref="FirstOpenReminderService"/>), has not blocked the bot and has not switched notifications off.
/// Only people registered after the first run of this release (marker <see cref="SwitchedOnSource"/>), so
/// the existing base gets nothing. While someone is in their first week, <see cref="DailyReturnNotificationService"/>
/// leaves them to these messages.
///
/// Once per day and person: the trigger <c>first_week_d1</c> / <c>_d3</c> / <c>_d7</c> 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.
/// </summary>
public class FirstWeekNudgeService(
ITraleDbContext db,
IMiniAppContentProvider content,
IUserNotificationService notificationService,
ILoggerFactory loggerFactory) : IFirstWeekNudgeService
{
private readonly ILogger _logger = loggerFactory.CreateLogger<FirstWeekNudgeService>();

public static readonly int[] Days = [1, 3, 7];
public static string SourceFor(int day) => $"first_week_d{day}";

/// <summary>Marker row: <c>LastSentAt</c> is when the first-week messages were switched on. Not a real user.</summary>
public const string SwitchedOnSource = "first_week_switched_on";
public const long SwitchedOnUserId = 0;

/// <summary>Studied this recently — no need to remind today.</summary>
public static readonly TimeSpan RecentlyPlayed = TimeSpan.FromHours(20);

/// <summary>The length of the first week: until then <see cref="DailyReturnNotificationService"/> stays away.</summary>
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);
}

/// <summary>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.</summary>
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<int>(), 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 минуты в день.",
};
}

/// <summary>When the messages were switched on — the first run stores now. Shared with the daily return push.</summary>
internal static async Task<DateTime> 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<string, List<int>> ParseCompletedLessons(string? json)
{
try { return JsonSerializer.Deserialize<Dictionary<string, List<int>>>(json ?? "") ?? []; }
catch { return []; }
}
}

/// <summary>One first-week message: the text and the lesson its button opens.</summary>
public record FirstWeekNudge(int Day, string Text, string ModuleId, int LessonId);
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 2 additions & 0 deletions src/Trale/HostedServices/HourlyNotificationWorker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ public async Task RunOnceAsync(DateTime nowUtc, CancellationToken ct)
await DispatchSafelyAsync<ICoinsNotificationService>(sp, "Coins", ct);
await DispatchSafelyAsync<IStreakNotificationService>(sp, "Streak", ct);
await DispatchSafelyAsync<IFirstOpenReminderService>(sp, "FirstOpenReminder", ct);
await DispatchSafelyAsync<IFirstWeekNudgeService>(sp, "FirstWeekNudge", ct);
}

private async Task DispatchSafelyAsync<TService>(IServiceProvider sp, string contextName, CancellationToken ct)
Expand Down Expand Up @@ -124,6 +125,7 @@ private static Task InvokeDispatchAsync<TService>(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}"),
};
Expand Down
11 changes: 11 additions & 0 deletions src/Trale/MiniApp/MiniAppContentProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,17 @@ public MiniAppContentProvider()

public CatalogDto GetCatalog() => _catalog;

public IReadOnlyList<LessonOutline> 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<LessonOutline>)[];

public string? ModuleTitle(string moduleId) => _catalog.Modules.FirstOrDefault(m => m.Id == moduleId)?.Title;

/// <summary>Every Georgian word gets its Cyrillic reading in brackets: «Слова: და (да), არა (ара)».</summary>
public static string WithReading(string text) =>
System.Text.RegularExpressions.Regex.Replace(text, "[\u10D0-\u10FF]+", m => $"{m.Value} ({CyrOf(m.Value)})");

public List<AlphabetQuizQuestionDto> GetAlphabetLessonQuestions(int lessonId)
{
if (!_alphabetLessonLetters.TryGetValue(lessonId, out var letters))
Expand Down
Loading
Loading