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
6 changes: 6 additions & 0 deletions FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ Location: `src/Trale/miniapp-src/src/`. The test greps the base file name (e.g.
| File | Screen kind | Purpose |
|---|---|---|
| `Dashboard.tsx` | `dashboard` | Main hub: launch-path bar, module tiles, streak, XP, mascot. Under the "what next" suggestion sits the «Глаголы» tile (`verbs/section/VerbsTile`): visible to everyone from day one, with or without trial/Pro; one line under the title («178 глаголов · игры по 2 минуты», «Продолжить: «X»», «Пора повторить: «X»», «Выучено N из 178»), a «новое» mark until the section was opened once. Opens `VerbsSection.tsx`. |
| `daily/DailyTask.tsx` | `daily` | «Задание дня»: a 2-minute session the server assembles every day from what the learner already has — forms due by the repetition schedule, forms that slipped, weak forms, own dictionary words, a long-unseen verb. Intro (Bombora says why, «Почему так» sheet) → warm-up (pick the translation) → «Собери пары» against the clock (starts on the first tap; time out — unmatched pairs count as mistakes, play again) → check (one form of the game among look-alikes) → finale (streak, +20 XP) with the «new» if the game went clean: fresh forms of a verb (opens its verb session), the next course lesson, or a one-minute check of a module whose final lesson is passed while lessons were skipped (six questions from the skipped lessons; all right — the trainer stops offering them, otherwise they come back one by one). Mode and level come from rules (a week away → «Возвращение», 3 forms, 1 minute; many mistakes → «Закрепляем», nothing new; else «Обычный день», level by smoothed accuracy). The dashboard card (`daily/DailyCard`, first under the hero) shows the task, then the offer, then «Сделано сегодня». Opened by the card or `?screen=daily` (the bot message). On the local stand the card has «+1 день · +7 дней · сообщение бота». In production it is open to the owner only for now (`DailyTaskAudience`: the server answers 404 to everyone else, and the card is not shown). A daily bot message (`DailyTaskReminderService`, ticked by `HourlyNotificationWorker`) carries today's task in Bombora's words and a button into it (`?screen=daily&src=push_daily_task`): once a UTC day, at the hour the person last studied kept within 10:00–21:00 Tbilisi (19:00 without a habit), not after 22:00, not when the task is done; whoever gets it is left out of the daily-return push. |
| `VerbsSection.tsx` | `verbs` | The «Глаголы» section. Top to bottom: «Выучено N из 178»; one big "what to do now" card — the app picks the verb (the one in progress, else one with forms due, else the next of the ladder) and the button starts its 2–3 minute session at once; five levels («по порядку») as collapsible groups with a bar each, the current one open, inside — packs of about five verbs by theme, a pack opens to its verbs (Russian first, Georgian with Cyrillic), a verb opens its card; at the bottom «Мои глаголы» (verbs the learner translated or saved in the bot or the dictionary and verbs already played; a model-made one the owner has not approved carries a quiet «составлено нейросетью», the same words as on its card; empty — one line, an input «Введи любой глагол по-русски» and three example chips that go through the usual translation). Nothing is locked; a pack is «пройден» when all its verbs are learned. First-run tour (`verbs/section/tour.ts`, `Spotlight`): «начни с этого» on first entry, after the first game, top to bottom — the level bar, where the verb's forms are, «Мои глаголы» (the spotlight scrolls to its target); each step once (server-side `ui:` hints), skippable, never blocking. The first own translated verb is celebrated once (`OwnVerbUnlocked`, also in the dictionary). A beginner who has not finished the alphabet gets one dismissible line leading to it. Without trial/Pro the section is an overview (Russian names, counts, no Georgian); play / open a verb / add one lead to the paywall. Opened by the dashboard tile, by `?screen=verbs` (broadcast button, `/start verbs_<tag>` button) or `startapp=verbs_<tag>` (`verbs/section/link.ts`); the way in is reported to the server. After a campaign open that gave a gift: one line «Подарок: 3 дня полного доступа — до <дата>», once. |
| `ModuleMap.tsx` | `module` | Lesson list for a module. |
| `LessonTheory.tsx` | `lesson-theory` | Theory blocks + reveal overlay; launches Practice. For `alphabet-progressive` it shows the lesson opener instead (`alphabet/opener/LessonOpener.tsx`): «Сегодня 3 новые буквы», three face-down cards dealt one by one (each opens in its intro scene), «К концу урока прочитаешь» with three lesson words, «Начать»; the theory (without the letters table) only behind «подробнее» in a bottom sheet; fits the screen. |
Expand Down Expand Up @@ -262,6 +263,10 @@ Location: `src/Trale/Controllers/`. Routes relative to controller base. Test gre
| GET | `/api/miniapp/verbs` | (not used by the mini-app UI yet) List of verbs (id, masdar title, translation, kind, 1sg present, `status` verified/generated — `generated` = written by a model and approved by a second one; SEO pages must still skip it). 401 without auth, 402 without trial/Pro. |
| GET | `/api/miniapp/verbs/section` | The «Глаголы» section in one call (`VerbSectionQuery`, a fixed handful of queries): `total`, `learned`, `levels` → `packs` → `verbs` (id, title, ru, the learner's `level`, forms `due`), `next` — what to do now (`continue` / `review` / `new` with the verb and its pack), `currentLevel`, `myVerbs` (started ∪ saved in the dictionary; `generated`, `levelId`), `examples` (three Russian glosses of ladder verbs the learner does not have), `alphabetHint`, `hasAccess`. 401 without auth. Not behind 402: without trial/Pro it is an overview — `id` and `title` of every verb are null, nothing Georgian is returned. A level also carries `families` — family cards (id `family-{id}`, `baseLearned`, `members` with `role`, `direction`, `toward`, `directionRu`, `inCard`, level and due; no ids and no Georgian without access). `next` never offers a family member as a ladder of its own: while the base verb is not learned it offers the base verb, afterwards the member with `familyBase` set (its session is the short prefix session). |
| POST | `/api/miniapp/verbs/section/open` | The section was opened; `{source}` — `home` (dashboard tile), a campaign key, or the tag of a link. One row per (user, source) in `VerbSectionVisits` with first / last open and a counter; recorded for people without access too. 400 for a tag outside `[A-Za-z0-9_-]{1,64}`. |
| GET | `/api/miniapp/daily-task` | Today's «Задание дня» (`DailyTaskService` → `DailyTaskPlanner`, `CoursePlanner`): composed on the first call of the UTC day and kept in `DailyTaskStates.TaskJson`, so the screen and the bot message agree. `available: false` when there is nothing to build it from. 401 / 402 like the verbs; in production 404 for everyone but the owner (`BotConfiguration.OwnerTelegramId`) — all `daily-task` endpoints. |
| POST | `/api/miniapp/daily-task/result` | The task played to the end: `{day, warmWrong, pairWrong, errors, checkErrors, seconds}`. Form outcomes go through `VerbProgressService.SaveAsync` (same schedule as verb sessions), dictionary words get answer counters, +20 XP and the streak via `CreditPractice`, accuracy and missed forms are remembered; the «new» is offered when there was at most one mistake and the day was not «Закрепляем». Idempotent per day; 409 for a stale day. |
| POST | `/api/miniapp/daily-task/offer` | The «new» was opened (`opened`) or the one-minute module check ended (`passed` / `failed`): the next offer alternates forms and course, a passed module is not offered again, a failed one returns its skipped lessons one by one. |
| POST | `/api/miniapp/daily-task/dev/next-day`, `/dev/push` | Local stand only (404 elsewhere): move the learner's data `days` back as if that time passed, and send today's reminder now — the very message the hourly worker sends. |
| GET | `/api/miniapp/verbs/families/{id}` | A verb family for the prefix session: every member with its six main tenses and their plain meanings, the learner's level of each, `baseLearned`, and `intro` — `lessonDone` plus the screens made of the direction-prefix lessons' own theory lines. 401 / 402 as other verb endpoints, 404 for an unknown family. The card of a curated family verb (`GET /api/miniapp/verbs/{id}`) carries `family` too (`VerbFamilyQuery.DecorateCardAsync`): role (base / member), the prefixes to highlight, direction, «туда / сюда», the lesson module and the other members. |
| GET | `/api/miniapp/verbs/summary` | (not used by the mini-app UI since the «Глаголы» tile) What the dashboard may say about verbs: `dictionaryVerbs` — how many of the user's own dictionary entries contain a known verb form; `continueVerb` — the verb the learner played most recently and has not learned yet (id, title, translation, level), or null. 401 without auth, 402 without trial/Pro. |
| GET | `/api/miniapp/verbs/parse?form=` | Parse an exact Georgian form into (verb, tense, person) hits; empty list when unknown. |
Expand Down Expand Up @@ -419,6 +424,7 @@ Location: `src/Persistence/Migrations/`. Test greps the migration class name (af
| `WidenNotificationTriggerVariant` | `NotificationTriggers.Variant` 10 → 32 chars: holiday keys longer than 10 (`svetitskhovloba`, `independence`, `language-day`) failed the claim insert, so those holiday pushes never went out. |
| `AddCampaignSendAllRequest` | Adds `BroadcastCampaigns.SendAllRequestedAtUtc` (null by default): the owner asked the server to send the campaign to everyone picked; `CampaignSendWorker` clears it when no one is left waiting. |
| `AddCampaignSchedule` | Adds `BroadcastCampaigns.ScheduledAtUtc` and `ScheduledTimeZone` (both null by default): the moment the campaign goes out by itself and the IANA zone the owner set it in (only to show the time back). Cleared when the sending starts or the owner cancels. |
| `AddDailyTaskState` | Adds `DailyTaskStates` (one row per user): smoothed accuracy of the «Задание дня» game, mistakes and missed forms of the last game, what «new» was opened last, verdicts of the one-minute module checks, the task composed for the current day with its result. |

---

Expand Down
1 change: 1 addition & 0 deletions src/Application/Common/ITraleDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public interface ITraleDbContext
DbSet<VerbFormProgress> VerbFormProgresses { get; }
DbSet<UserVerb> UserVerbs { get; }
DbSet<VerbSession> VerbSessions { get; }
DbSet<DailyTaskState> DailyTaskStates { get; }
DbSet<VerbSectionVisit> VerbSectionVisits { get; }
DbSet<LessonEvent> LessonEvents { get; }
DbSet<AppEvent> AppEvents { get; }
Expand Down
6 changes: 6 additions & 0 deletions src/Application/Common/Interfaces/IUserNotificationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ Task SendReferralBonusGrantedAsync(
/// </summary>
Task SendFirstWeekNudgeAsync(User user, Application.Notifications.FirstWeekNudge nudge, CancellationToken ct);

/// <summary>
/// The «Задание дня» reminder (see <c>DailyTaskReminderService</c>): today's task in Bombora's words and one
/// web-app button into it, tagged <c>src=push_daily_task</c>. 403 → user flagged inactive; 429 → single retry.
/// </summary>
Task SendDailyTaskReminderAsync(User user, string text, string button, 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.
Expand Down
147 changes: 147 additions & 0 deletions src/Application/DailyTask/CoursePlanner.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Application.Common;

namespace Application.DailyTask;

public record CourseLesson(int Id, string Title);

public record CourseModule(string Id, string Title, IReadOnlyList<CourseLesson> Lessons);

/// <summary>
/// The next step of the course for a learner who walked it out of order: what to finish, what is
/// already known (and only needs a one-minute check) and where to go next. Rules only — the order of
/// modules is written by hand, the rest is counted from passed lessons.
/// </summary>
public static class CoursePlanner
{
/// <summary>The check was passed: the module's skipped lessons are not offered.</summary>
public const string Known = "known";

/// <summary>The check was failed: the skipped lessons come back one at a time.</summary>
public const string Lessons = "lessons";

public const int CheckQuestions = 6;

/// <summary>
/// With this many lessons passed outside the alphabet the learner evidently reads: the alphabet's
/// word-reading lessons are not offered once the letters are done.
/// </summary>
private const int ReadsAlready = 10;

/// <summary>A started module from this share of passed lessons is finished before anything else.</summary>
private const double AlmostDone = 0.5;

/// <summary>The order the course is walked in; modules missing here follow in catalog order.</summary>
private static readonly string[] Order =
{
LearningConstants.Modules.Alphabet, "intro", "my-day", "numbers", "pronouns", "present-tense", "cases",
"postpositions", "adjectives", "cafe", "taxi", "shopping", "doctor", "emergency", "verbs-of-movement"
};

public static DailyNew? Next(
IReadOnlyList<CourseModule> catalog,
IReadOnlyDictionary<string, IReadOnlyCollection<int>> completed,
IReadOnlyDictionary<string, string> verdicts)
{
var modules = catalog
.Where(m => m.Lessons.Count > 0)
.Select(m =>
{
var done = completed.TryGetValue(m.Id, out var ids) ? ids : Array.Empty<int>();
var left = m.Lessons.Where(l => !done.Contains(l.Id)).ToList();
return new State(m, m.Lessons.Count - left.Count, left, verdicts.GetValueOrDefault(m.Id));
})
.Where(s => s.Left.Count > 0 && s.Verdict != Known)
.ToList();

// The alphabet: letters are done and plenty is passed elsewhere — its reading lessons are not needed.
var outsideAlphabet = completed
.Where(c => c.Key != LearningConstants.Modules.Alphabet && catalog.Any(m => m.Id == c.Key))
.Sum(c => c.Value.Count);
modules.RemoveAll(s =>
s.Module.Id == LearningConstants.Modules.Alphabet
&& s.Left.All(l => l.Id > LearningConstants.Modules.AlphabetLetterLessons)
&& outsideAlphabet >= ReadsAlready);

// 1. Almost finished — finish it: the closest to the end first.
var almost = modules
.Where(s => s.Done > 0 && s.Done >= s.Module.Lessons.Count * AlmostDone)
.OrderBy(s => s.Left.Count)
.FirstOrDefault();
if (almost != null)
{
var left = almost.Left.Count - 1;
return Lesson(almost, almost.Left[0],
$"Модуль «{almost.Module.Title}»: пройдено {almost.Done} из {almost.Module.Lessons.Count}. "
+ (left == 0
? "Это последний урок — пройди его и закрой модуль."
: $"Пройди этот урок — до конца модуля останется {left}."));
}

var ordered = modules
.OrderBy(s => Array.IndexOf(Order, s.Module.Id) is var i && i >= 0 ? i : int.MaxValue)
.ToList();

// 2. The final lesson is passed while lessons before it are skipped: either the learner knows
// the module (a one-minute check settles it), or the check showed gaps and lessons come back.
var jumped = ordered.FirstOrDefault(s => s.Left.All(l => l.Id != s.Module.Lessons[^1].Id));
if (jumped != null)
{
if (jumped.Verdict == Lessons)
{
return Lesson(jumped, jumped.Left[0],
$"Проверка показала пробелы. Пройди пропущенные уроки модуля «{jumped.Module.Title}» по одному: осталось {jumped.Left.Count}.");
}

var questions = Math.Min(CheckQuestions, jumped.Left.Count);
return new DailyNew(
DailyNew.Check,
jumped.Module.Title,
"проверка на минуту",
$"Последний урок модуля «{jumped.Module.Title}» у тебя пройден, а {DailyTaskPlanner.Count(jumped.Left.Count, "урок пропущен", "урока пропущены", "уроков пропущены")}. "
+ $"Ответь без ошибок на {DailyTaskPlanner.Count(questions, "вопрос", "вопроса", "вопросов")} из них — и модуль закрыт.",
"Пройти проверку",
ModuleId: jumped.Module.Id,
CheckLessons: Spread(jumped.Left.Select(l => l.Id).ToList(), questions));
}

// 3. The next module of the course.
var next = ordered.FirstOrDefault();
if (next == null)
{
return null;
}

return Lesson(next, next.Left[0], next.Done == 0
? $"Следующий модуль курса — «{next.Module.Title}»: {DailyTaskPlanner.Count(next.Module.Lessons.Count, "короткий урок", "коротких урока", "коротких уроков")}. Пройди первый."
: $"Модуль «{next.Module.Title}»: пройдено {next.Done} из {next.Module.Lessons.Count}. Пройди следующий урок.");
}

private record State(CourseModule Module, int Done, List<CourseLesson> Left, string? Verdict);

private static DailyNew Lesson(State state, CourseLesson lesson, string say)
{
var number = state.Module.Lessons.ToList().FindIndex(l => l.Id == lesson.Id) + 1;
return new DailyNew(
DailyNew.Lesson,
state.Module.Title,
$"урок {number} из {state.Module.Lessons.Count} · {lesson.Title}",
say,
"Пройти урок",
ModuleId: state.Module.Id,
LessonId: lesson.Id);
}

/// <summary>Evenly over the skipped lessons, so the check covers the whole module.</summary>
private static List<int> Spread(List<int> ids, int count)
{
if (ids.Count <= count)
{
return ids;
}

return Enumerable.Range(0, count).Select(i => ids[i * (ids.Count - 1) / (count - 1)]).Distinct().ToList();
}
}
19 changes: 19 additions & 0 deletions src/Application/DailyTask/DailyTaskAudience.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System.Collections.Generic;
using System.Linq;

namespace Application.DailyTask;

/// <summary>
/// Who gets «Задание дня» — the card, the endpoints and the daily reminder. While it is being tried out:
/// in production only the listed people (the owner), on the local stand everyone.
/// </summary>
public class DailyTaskAudience(bool everyone, IEnumerable<long> telegramIds)
{
private readonly HashSet<long> _telegramIds = telegramIds.ToHashSet();

public bool Everyone => everyone;

public IReadOnlyCollection<long> TelegramIds => _telegramIds;

public bool Includes(long telegramId) => everyone || _telegramIds.Contains(telegramId);
}
Loading
Loading