diff --git a/FEATURES.md b/FEATURES.md index 8c12d64b..954efa63 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -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_` button) or `startapp=verbs_` (`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. | @@ -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. | @@ -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. | --- diff --git a/src/Application/Common/ITraleDbContext.cs b/src/Application/Common/ITraleDbContext.cs index f18920ed..072a303e 100644 --- a/src/Application/Common/ITraleDbContext.cs +++ b/src/Application/Common/ITraleDbContext.cs @@ -28,6 +28,7 @@ public interface ITraleDbContext DbSet VerbFormProgresses { get; } DbSet UserVerbs { get; } DbSet VerbSessions { get; } + DbSet DailyTaskStates { get; } DbSet VerbSectionVisits { get; } DbSet LessonEvents { get; } DbSet AppEvents { get; } diff --git a/src/Application/Common/Interfaces/IUserNotificationService.cs b/src/Application/Common/Interfaces/IUserNotificationService.cs index 5d21571f..354057ad 100644 --- a/src/Application/Common/Interfaces/IUserNotificationService.cs +++ b/src/Application/Common/Interfaces/IUserNotificationService.cs @@ -80,6 +80,12 @@ Task SendReferralBonusGrantedAsync( /// Task SendFirstWeekNudgeAsync(User user, Application.Notifications.FirstWeekNudge nudge, CancellationToken ct); + /// + /// The «Задание дня» reminder (see DailyTaskReminderService): today's task in Bombora's words and one + /// web-app button into it, tagged src=push_daily_task. 403 → user flagged inactive; 429 → single retry. + /// + Task SendDailyTaskReminderAsync(User user, string text, string button, 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. diff --git a/src/Application/DailyTask/CoursePlanner.cs b/src/Application/DailyTask/CoursePlanner.cs new file mode 100644 index 00000000..b71d603f --- /dev/null +++ b/src/Application/DailyTask/CoursePlanner.cs @@ -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 Lessons); + +/// +/// 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. +/// +public static class CoursePlanner +{ + /// The check was passed: the module's skipped lessons are not offered. + public const string Known = "known"; + + /// The check was failed: the skipped lessons come back one at a time. + public const string Lessons = "lessons"; + + public const int CheckQuestions = 6; + + /// + /// 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. + /// + private const int ReadsAlready = 10; + + /// A started module from this share of passed lessons is finished before anything else. + private const double AlmostDone = 0.5; + + /// The order the course is walked in; modules missing here follow in catalog order. + 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 catalog, + IReadOnlyDictionary> completed, + IReadOnlyDictionary verdicts) + { + var modules = catalog + .Where(m => m.Lessons.Count > 0) + .Select(m => + { + var done = completed.TryGetValue(m.Id, out var ids) ? ids : Array.Empty(); + 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 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); + } + + /// Evenly over the skipped lessons, so the check covers the whole module. + private static List Spread(List 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(); + } +} diff --git a/src/Application/DailyTask/DailyTaskAudience.cs b/src/Application/DailyTask/DailyTaskAudience.cs new file mode 100644 index 00000000..6eabce0c --- /dev/null +++ b/src/Application/DailyTask/DailyTaskAudience.cs @@ -0,0 +1,19 @@ +using System.Collections.Generic; +using System.Linq; + +namespace Application.DailyTask; + +/// +/// 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. +/// +public class DailyTaskAudience(bool everyone, IEnumerable telegramIds) +{ + private readonly HashSet _telegramIds = telegramIds.ToHashSet(); + + public bool Everyone => everyone; + + public IReadOnlyCollection TelegramIds => _telegramIds; + + public bool Includes(long telegramId) => everyone || _telegramIds.Contains(telegramId); +} diff --git a/src/Application/DailyTask/DailyTaskModels.cs b/src/Application/DailyTask/DailyTaskModels.cs new file mode 100644 index 00000000..7c5ff9ca --- /dev/null +++ b/src/Application/DailyTask/DailyTaskModels.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; + +namespace Application.DailyTask; + +// What the mini-app gets (mirrored in miniapp-src/src/daily/types.ts). All learner-facing text is +// composed here, so the bot message and the screen say the same thing. + +/// A verb form or a dictionary word. Key: "v:lemma:tense:person" or "w:entryId". +public record DailyItem( + string Key, string Kind, string Ka, string Ru, + string? Lemma = null, string? VerbRu = null, string? Tense = null, int? Person = null); + +public record DailyOption(string Ru, bool Ok); + +/// The form came by the repetition schedule (its answer moves the schedule); otherwise it is a long-unseen verb. +public record DailyWarmRound(DailyItem Item, IReadOnlyList Options, bool Due); + +public record DailyPick(DailyItem Item, bool Ok, string Message); + +public record DailyCheck(string Prompt, string Intro, IReadOnlyList Picks); + +/// The "new" at the end: fresh forms of a verb, a course lesson or a one-minute module check. +public record DailyNew( + string Kind, string Title, string Line, string Say, string Button, + string? VerbId = null, string? ModuleId = null, int? LessonId = null, IReadOnlyList? CheckLessons = null) +{ + public const string Forms = "forms"; + public const string Lesson = "lesson"; + public const string Check = "check"; +} + +public record DailyResult(int Errors, int XpEarned, int Streak); + +public record DailyTaskDto +{ + /// False when there is nothing to build a task from — the card is not shown. + public bool Available { get; init; } + public string Day { get; init; } = ""; + public bool Done { get; init; } + public string Mode { get; init; } = DailyMode.Mix; + public int Level { get; init; } = 1; + public string Title { get; init; } = ""; + public IReadOnlyList Chat { get; init; } = []; + public string Button { get; init; } = ""; + public IReadOnlyList Why { get; init; } = []; + public int Seconds { get; init; } + public IReadOnlyList Warm { get; init; } = []; + public IReadOnlyList Pairs { get; init; } = []; + public DailyCheck Check { get; init; } = new("", "", []); + /// What will be offered at the end if the game goes clean. + public DailyNew? Next { get; init; } + /// What is actually offered after the result; null — nothing new today. + public DailyNew? Offer { get; init; } + public bool OfferTaken { get; init; } + public DailyResult? Result { get; init; } + /// Local stand only: the mini-app shows the "next day" controls. + public bool Dev { get; init; } +} + +public static class DailyMode +{ + public const string Comeback = "comeback"; + public const string Review = "review"; + public const string Mix = "mix"; +} + +/// What the mini-app reports when the task is played to the end. +public record DailyReport( + string Day, IReadOnlyCollection WarmWrong, IReadOnlyCollection PairWrong, int Errors, int CheckErrors); + +// What the planner is given. + +/// A form the learner has already opened, with its place on the ladder. +public record DailyForm( + string Lemma, string VerbRu, string Tense, int Person, string Ka, string Ru, + int Step, int BestStep, int Reviews, DateTime? DueAtUtc, DateTime UpdatedAtUtc) +{ + public string Key => $"v:{Lemma}:{Tense}:{Person}"; +} + +/// +/// A started verb whose session would open new forms now, and the forms it would open first +/// (the session's own order, up to three) with their meaning. +/// +public record DailyUnopened(string Lemma, string VerbRu, IReadOnlyList Next); + +public record DailyFresh(string Tense, int Person, string Ru); + +public record DailyWord(Guid Id, string Ka, string Ru, int Ok, int Bad, DateTime AddedAtUtc, DateTime UpdatedAtUtc) +{ + public string Key => $"w:{Id}"; +} + +public record DailyInput +{ + public required DateTime Now { get; init; } + /// Full days without practice before today (0 — practised yesterday or today). + public int Away { get; init; } + /// The streak as it stands; tells whether today is already in it. + public int Streak { get; init; } + public bool PlayedToday { get; init; } + public bool PlayedYesterday { get; init; } + public int? Accuracy { get; init; } + public int LastErrors { get; init; } + /// The last task was finished yesterday (its mistakes are "yesterday's"). + public bool LastTaskYesterday { get; init; } + public string? LastNew { get; init; } + public IReadOnlyCollection Missed { get; init; } = []; + public IReadOnlyList Forms { get; init; } = []; + public IReadOnlyList Unopened { get; init; } = []; + public IReadOnlyList Words { get; init; } = []; + /// The next step of the course, already chosen by . + public DailyNew? Course { get; init; } + /// Makes shuffles repeatable within a day. + public int Seed { get; init; } +} diff --git a/src/Application/DailyTask/DailyTaskPlanner.cs b/src/Application/DailyTask/DailyTaskPlanner.cs new file mode 100644 index 00000000..4df274e5 --- /dev/null +++ b/src/Application/DailyTask/DailyTaskPlanner.cs @@ -0,0 +1,482 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Application.Translation.Languages; +using Domain.Entities; + +namespace Application.DailyTask; + +/// +/// Builds the task of the day out of what the learner already has: forms that are due, forms that +/// slipped, weak forms and their own dictionary. No model is involved: the mode and the level come +/// from thresholds, the content from fixed queues, the texts from templates. +/// Pure: the same input gives the same task. +/// +public static class DailyTaskPlanner +{ + public const int XpReward = 20; + + /// The accuracy assumed before the first game: it starts the learner on the middle level. + public const int StartAccuracy = 78; + + /// A verb nobody touched for this long is brought back in the warm-up. + private const int StaleDays = 21; + + /// Dictionary words added within these days and never trained count as fresh. + private const int FreshDays = 7; + + /// After a break this long the task is the easiest one. + private const int ComebackDays = 7; + + /// Mistakes in the last game from which the next day only repeats. + private const int ManyErrors = 3; + + private const int Mastered = VerbFormProgress.MasteredStep; + + private record LevelSpec(int Pairs, int Seconds, int Options, int Rounds); + + private static LevelSpec Spec(int level) => level switch + { + 1 => new LevelSpec(3, 60, 2, 3), + 2 => new LevelSpec(4, 45, 3, 5), + _ => new LevelSpec(5, 35, 3, 5) + }; + + /// Tenses are never called by their textbook names in front of a learner. + public static string TenseName(string tense) => tense switch + { + "present" => "сейчас", + "aorist" => "прошедшее: сделал", + "imperfect" => "прошедшее: делал", + "future" => "будущее", + "optative" => "надо сделать", + "conditional" => "сделал бы", + _ => tense + }; + + /// + /// Forms and the course take turns: after fresh forms comes a lesson, after a lesson — forms. + /// + public static DailyNew? PickNew(DailyNew? portion, DailyNew? course, string? lastNew) => + (lastNew == DailyNew.Forms || portion == null) && course != null ? course : portion ?? course; + + /// The new accuracy after a game: recent games weigh more, one bad game does not drop the level. + public static int NextAccuracy(int? accuracy, int errors) + { + var score = errors switch { <= 0 => 100, <= 2 => 80, <= 4 => 60, _ => 40 }; + var next = (int)Math.Round(0.6 * (accuracy ?? StartAccuracy) + 0.4 * score, MidpointRounding.AwayFromZero); + return Math.Clamp(next, 40, 100); + } + + public static DailyTaskDto Compose(DailyInput input) + { + var now = input.Now; + var today = now.Date; + var day = DateOnly.FromDateTime(today).ToString("yyyy-MM-dd"); + var random = new Random(input.Seed); + var forms = input.Forms; + var accuracy = input.Accuracy ?? StartAccuracy; + + var mode = input.Away >= ComebackDays ? DailyMode.Comeback + : input.LastErrors >= ManyErrors || accuracy < 60 ? DailyMode.Review + : DailyMode.Mix; + var level = mode != DailyMode.Mix ? 1 : accuracy < 73 ? 1 : accuracy < 85 ? 2 : 3; + var spec = Spec(level); + + // When each verb was last practised: recent verbs go first, long-unseen ones are "stale". + var last = forms.GroupBy(f => f.Lemma).ToDictionary(g => g.Key, g => g.Max(f => f.UpdatedAtUtc)); + + bool IsDue(DailyForm f) => f.Step == Mastered && f.DueAtUtc != null && f.DueAtUtc <= now; + bool Slipped(DailyForm f) => f.Step < f.BestStep; + + var due = forms.Where(IsDue).OrderBy(f => f.DueAtUtc).ToList(); + var slip = forms.Where(Slipped) + .OrderByDescending(f => last[f.Lemma]).ThenBy(f => f.Step).ThenByDescending(f => f.BestStep - f.Step) + .ToList(); + var low = forms.Where(f => f.Step < Mastered && !Slipped(f)) + .OrderBy(f => f.Step).ThenByDescending(f => last[f.Lemma]) + .ToList(); + var staleVerbs = last.Where(v => (today - v.Value.Date).Days >= StaleDays) + .OrderByDescending(v => v.Value).Select(v => v.Key) + .ToList(); + var fresh = input.Words.Where(w => w.Ok + w.Bad == 0 && (today - w.AddedAtUtc.Date).Days <= FreshDays) + .OrderByDescending(w => w.AddedAtUtc) + .ToList(); + var weak = input.Words.Where(w => w.Bad > w.Ok).OrderByDescending(w => w.UpdatedAtUtc).ToList(); + var own = fresh.Concat(weak).Select(Item).Where(TileOk).ToList(); + + // Warm-up: what the schedule brought today, then a verb that was not touched for long. + var warm = new List<(DailyForm Form, bool Due)>(); + string? staleVerb = null; + if (mode != DailyMode.Comeback) + { + warm.AddRange(due.Take(spec.Rounds).Select(f => (f, true))); + if (mode == DailyMode.Mix && warm.Count < spec.Rounds && staleVerbs.Count > 0) + { + var stale = forms + .Where(f => f.Lemma == staleVerbs[0] && !Slipped(f) && warm.All(w => w.Form != f)) + .OrderByDescending(f => f.Step) + .Take(spec.Rounds - warm.Count) + .ToList(); + if (stale.Count > 0) + { + staleVerb = staleVerbs[0]; + warm.AddRange(stale.Select(f => (f, false))); + } + } + } + + var rounds = new List(); + foreach (var (form, isDue) in warm) + { + var wrong = Shuffle(forms.Where(o => o.Lemma == form.Lemma), random) + .Concat(Shuffle(forms.Where(o => o.Lemma != form.Lemma), random)) + .Select(o => o.Ru) + .Where(ru => ru != form.Ru) + .Distinct() + .Take(spec.Options - 1) + .Select(ru => new DailyOption(ru, false)) + .ToList(); + if (wrong.Count == 0) + { + continue; + } + + var options = Shuffle(wrong.Append(new DailyOption(form.Ru, true)), random); + rounds.Add(new DailyWarmRound(Item(form), options, isDue)); + } + + var inWarm = rounds.Select(r => r.Item.Key).ToHashSet(); + + // The game: a pair is never taken twice, neither by its Georgian nor by its Russian side. + var pairs = new List(); + void Take(IEnumerable candidates, int upTo) + { + foreach (var item in candidates) + { + if (pairs.Count >= upTo) + { + return; + } + + if (pairs.All(p => p.Ka != item.Ka && p.Ru != item.Ru)) + { + pairs.Add(item); + } + } + } + + IEnumerable Tiles(IEnumerable source) => + source.Where(f => !inWarm.Contains(f.Key)).Select(Item).Where(TileOk); + + if (mode == DailyMode.Comeback) + { + Take(Tiles(forms.OrderByDescending(f => f.Step).ThenByDescending(f => last[f.Lemma])), spec.Pairs); + } + else + { + var wantOwn = mode == DailyMode.Mix ? Math.Min(level - 1, own.Count) : 0; + if (mode == DailyMode.Review) + { + Take(Tiles(forms.Where(f => input.Missed.Contains(f.Key) && f.Step < Mastered)), spec.Pairs); + } + + Take(Tiles(slip), spec.Pairs - wantOwn); + Take(Tiles(low), spec.Pairs - wantOwn); + Take(own, spec.Pairs); + Take(Tiles(low), spec.Pairs); + } + + // Not enough of the usual: anything opened (longest unseen first), then the dictionary. + Take(Tiles(forms.OrderBy(f => f.UpdatedAtUtc)), spec.Pairs); + Take(input.Words.OrderByDescending(w => w.Bad - w.Ok).ThenBy(w => w.UpdatedAtUtc).Select(Item).Where(TileOk), spec.Pairs); + + if (pairs.Count < 2) + { + return new DailyTaskDto { Available = false, Day = day }; + } + + var mainVerb = pairs.Where(p => p.Lemma != null) + .GroupBy(p => p.Lemma!) + .OrderByDescending(g => g.Count()) + .Select(g => g.Key) + .FirstOrDefault(); + var portion = Portion(input.Unopened, last, mainVerb); + var next = mode == DailyMode.Review ? null : PickNew(portion, input.Course, input.LastNew); + + var verbForms = rounds.Select(r => r.Item).Concat(pairs).Count(i => i.Kind == "verb"); + var ownWords = pairs.Count(i => i.Kind == "word"); + var streakTail = input.PlayedToday ? "" + : input.PlayedYesterday ? $", и в серии будет {Count(input.Streak + 1, "день", "дня", "дней")}" + : ", и начнётся новая серия"; + + string title; + string button; + var chat = new List(); + switch (mode) + { + case DailyMode.Comeback: + title = "Возвращение"; + button = "Вспомнить за минуту"; + chat.Add($"Давно не виделись: тебя не было {Count(input.Away, "день", "дня", "дней")}."); + chat.Add(ownWords == 0 + ? $"Начни с лёгкого: {Count(pairs.Count, "форма", "формы", "форм")} из тех, что ты знаешь лучше всего. Это одна минута{streakTail}." + : $"Начни с лёгкого: самое знакомое из того, что ты уже учил. Это одна минута{streakTail}."); + break; + + case DailyMode.Review: + title = "Закрепляем"; + button = "Повторить знакомое"; + chat.Add(input.LastErrors >= ManyErrors && input.LastTaskYesterday + ? "Вчера в игре было много ошибок." + : "В последних играх много ошибок."); + chat.Add("Сегодня без новых слов и форм: повтори " + + (pairs.Any(p => input.Missed.Contains(p.Key)) ? "те, где были ошибки" : "то, что уже было") + + $". Это две минуты{streakTail}."); + break; + + default: + title = "Обычный день"; + button = "Повторить"; + chat.Add(MixReason(input, rounds, pairs, forms, staleVerb, last, Slipped)); + var what = verbForms > 0 + ? Accusative(verbForms) + + (ownWords > 0 ? $" и {Count(ownWords, "слово", "слова", "слов")} из своего словаря" : "") + : $"{Count(ownWords, "слово", "слова", "слов")} из своего словаря"; + chat.Add($"Повтори сегодня {what}. Это две минуты{streakTail}."); + break; + } + + return new DailyTaskDto + { + Available = true, + Day = day, + Mode = mode, + Level = level, + Title = title, + Chat = chat, + Button = button, + Why = Why(input, mode, level, due, slip, staleVerbs, fresh.Count, weak.Count, next), + Seconds = spec.Seconds, + Warm = rounds, + Pairs = pairs, + Check = Check(pairs, forms, input.Words, level, spec.Options, random), + Next = next + }; + } + + /// The first sentence of an ordinary day: what exactly brought today's forms here. + private static string MixReason( + DailyInput input, List rounds, List pairs, IReadOnlyList forms, + string? staleVerb, Dictionary last, Func slipped) + { + var dueItems = rounds.Where(r => r.Due).Select(r => r.Item).ToList(); + var slippedKeys = forms.Where(slipped).Select(f => f.Key).ToHashSet(); + var slippedItems = pairs.Where(p => slippedKeys.Contains(p.Key)).ToList(); + + var text = ""; + if (dueItems.Count > 0) + { + text = OfVerb(dueItems, capital: true) + + $"{Count(dueItems.Count, "форма ждёт", "формы ждут", "форм ждут")} повторения"; + } + + if (slippedItems.Count > 0) + { + var tail = $"{Count(slippedItems.Count, "форма стала", "формы стали", "форм стали")} получаться хуже"; + text = text.Length > 0 + ? $"{text}, а {OfVerb(slippedItems, capital: false)}{tail}" + : OfVerb(slippedItems, capital: true) + tail; + } + + text = text.Length > 0 ? text + "." : "Сегодня формы и слова, которые пока держатся слабее всего."; + if (input.Away > 0) + { + text = $"{Count(input.Away, "день", "дня", "дней")} без занятий. {text}"; + } + + if (staleVerb != null) + { + var verbRu = forms.First(f => f.Lemma == staleVerb).VerbRu; + text += $" Глагол «{verbRu}» без практики с {Date(last[staleVerb])} — начни с него."; + } + + return text; + + // «У глагола «иметь» » when all the forms belong to one verb, nothing otherwise. + static string OfVerb(List items, bool capital) + { + var verbs = items.Select(i => i.VerbRu).Distinct().ToList(); + return verbs.Count == 1 && verbs[0] != null ? $"{(capital ? "У" : "у")} глагола «{verbs[0]}» " : ""; + } + } + + private static List Why( + DailyInput input, string mode, int level, List due, List slip, List staleVerbs, + int fresh, int weak, DailyNew? next) + { + var why = new List(); + if (input.Away > 0) + { + why.Add($"Без занятий: {Count(input.Away, "день", "дня", "дней")}."); + } + + if (mode == DailyMode.Review && input.LastErrors > 0) + { + why.Add($"Ошибок в прошлой игре: {input.LastErrors}."); + } + + if (due.Count > 0) + { + var verbs = string.Join(", ", due.Select(f => $"«{f.VerbRu}»").Distinct().Take(3)); + why.Add($"Ждут повторения по расписанию: {Count(due.Count, "форма", "формы", "форм")} ({verbs})."); + } + + if (slip.Count > 0) + { + why.Add($"Стали получаться хуже: {Count(slip.Count, "форма", "формы", "форм")}."); + } + + if (staleVerbs.Count > 0) + { + why.Add($"Три недели и дольше без практики: {Count(staleVerbs.Count, "глагол", "глагола", "глаголов")}."); + } + + if (input.Words.Count > 0) + { + why.Add($"В словаре {Count(input.Words.Count, "слово", "слова", "слов")}: новых за неделю — {fresh}, с ошибками — {weak}."); + } + + why.Add(input.Accuracy == null + ? "Это первая игра, поэтому уровень средний." + : $"Точность последних игр: {input.Accuracy}% — уровень {level} из 3."); + why.Add(mode == DailyMode.Review ? "Нового сегодня нет: сначала закрепляем." + : next != null ? $"Новое в конце, если игра пройдёт чисто: {next.Title} — {next.Line}." + : "Нового в конце сегодня нет."); + return why; + } + + /// The last task: one form of today's game among look-alikes. + private static DailyCheck Check( + List pairs, IReadOnlyList forms, IReadOnlyList words, int level, int options, + Random random) + { + var key = pairs.FirstOrDefault(p => p.Kind == "verb" && CheckOk(p)) ?? pairs.FirstOrDefault(CheckOk) ?? pairs[0]; + var isVerb = key.Kind == "verb"; + + IEnumerable pool; + if (isVerb) + { + var same = forms.Where(f => f.Lemma == key.Lemma && f.Key != key.Key).ToList(); + var sameTense = Shuffle(same.Where(f => f.Tense == key.Tense), random); + var otherTense = Shuffle(same.Where(f => f.Tense != key.Tense), random); + // The higher the level, the more alike the options. + var own = level >= 3 ? sameTense.Concat(otherTense) + : level == 1 ? otherTense.Concat(sameTense) + : Shuffle(same, random); + pool = own.Concat(Shuffle(forms.Where(f => f.Lemma != key.Lemma), random)).Select(Item); + } + else + { + pool = Shuffle(words.Where(w => w.Key != key.Key), random).Select(Item).Where(i => TileOk(i) && CheckOk(i)); + } + + var wrong = new List(); + foreach (var item in pool) + { + if (wrong.Count >= options - 1) + { + break; + } + + if (item.Ka != key.Ka && item.Ru != key.Ru && wrong.All(w => w.Ka != item.Ka && w.Ru != item.Ru)) + { + wrong.Add(item); + } + } + + var other = isVerb ? "другую форму" : "другое слово"; + var picks = wrong + .Select(w => new DailyPick(w, false, $"«{w.Ka}» ({Cyr(w.Ka)}) — это «{w.Ru}». Нажми {other}.")) + .Append(new DailyPick(key, true, $"Верно: «{key.Ka}» ({Cyr(key.Ka)}) — {key.Ru}.")); + + return new DailyCheck( + isVerb ? $"Нажми форму, которая значит «{key.Ru}»" : $"Нажми слово, которое значит «{key.Ru}»", + !isVerb ? "Последнее задание: одно слово из сегодняшней игры." + : level >= 3 ? "Последнее задание. Формы похожи, смотри внимательно." + : "Последнее задание: одна форма из сегодняшней игры.", + Shuffle(picks, random)); + } + + /// + /// The forms the verb session would open next: of the verb the game was mostly about, else of the + /// most recently practised one. The session decides which forms; the offer only names them. + /// + private static DailyNew? Portion(IReadOnlyList unopened, Dictionary last, string? prefer) + { + var verb = unopened.Where(u => u.Next.Count > 0) + .OrderByDescending(u => u.Lemma == prefer) + .ThenByDescending(u => last.GetValueOrDefault(u.Lemma)) + .FirstOrDefault(); + if (verb == null) + { + return null; + } + + var meanings = string.Join(", ", verb.Next.Select(f => $"«{f.Ru}»")); + return new DailyNew( + DailyNew.Forms, + $"Новые формы глагола «{verb.VerbRu}»", + string.Join(" · ", verb.Next.Select(f => f.Ru)), + $"Игра прошла чисто — можно брать новое. Открой у глагола «{verb.VerbRu}» {Count(verb.Next.Count, "новую форму", "новые формы", "новых форм")}: {meanings}. Это короткая сессия.", + "Открыть новые формы", + VerbId: verb.Lemma); + } + + private static DailyItem Item(DailyForm f) => + new(f.Key, "verb", f.Ka, f.Ru, f.Lemma, f.VerbRu, f.Tense, f.Person); + + private static DailyItem Item(DailyWord w) => new(w.Key, "word", w.Ka, w.Ru); + + /// Fits a tile of the pairs game on a phone. + private static bool TileOk(DailyItem item) => item.Ka.Length <= 20 && item.Ru.Length <= 24; + + /// Short and unambiguous enough to be the answer of the last task. + private static bool CheckOk(DailyItem item) => + item.Ka.Length <= 12 && (item.Kind == "verb" || item.Ru.IndexOfAny([',', '(', ')', '/', '?']) < 0); + + private static string Cyr(string georgian) => GeorgianTranscriptionExtension.GetTranscription(georgian); + + private static List Shuffle(IEnumerable source, Random random) + { + var list = source.ToList(); + for (var i = list.Count - 1; i > 0; i--) + { + var j = random.Next(i + 1); + (list[i], list[j]) = (list[j], list[i]); + } + + return list; + } + + /// «1 форма», «3 формы», «5 форм». + public static string Count(int n, string one, string few, string many) => $"{n} {Plural(n, one, few, many)}"; + + public static string Plural(int n, string one, string few, string many) + { + var tens = Math.Abs(n) % 100; + var units = tens % 10; + return tens is >= 11 and <= 14 ? many : units == 1 ? one : units is >= 2 and <= 4 ? few : many; + } + + /// «повтори 1 форму / 3 формы / 5 форм». + private static string Accusative(int n) => Count(n, "форму", "формы", "форм"); + + private static readonly string[] Months = + { + "января", "февраля", "марта", "апреля", "мая", "июня", + "июля", "августа", "сентября", "октября", "ноября", "декабря" + }; + + private static string Date(DateTime date) => $"{date.Day} {Months[date.Month - 1]}"; +} diff --git a/src/Application/DailyTask/DailyTaskReminderService.cs b/src/Application/DailyTask/DailyTaskReminderService.cs new file mode 100644 index 00000000..b0a27641 --- /dev/null +++ b/src/Application/DailyTask/DailyTaskReminderService.cs @@ -0,0 +1,111 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Application.Common; +using Application.Common.Interfaces; +using Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Application.DailyTask; + +/// +/// The daily message about «Задание дня»: what today's task is (the same words Bombora says on its +/// first screen) and one button straight into it, tagged src=push_daily_task. +/// +/// Who: the people listed in (the owner for now; on the stand too), active, notifications on, +/// the task has material and is not done today. +/// When: once a UTC day, from the hour the person last studied (their habit), kept within +/// 10:00–21:00 Tbilisi; without a habit yet — at 19:00 Tbilisi. A tick missed by the worker is made up +/// later the same day, never after 22:00 Tbilisi. +/// Once a day: the daily_task trigger is claimed before sending; it can be claimed again only +/// on the next UTC day. Whoever gets this message is left out of DailyReturnNotificationService. +/// +public class DailyTaskReminderService( + ITraleDbContext db, + DailyTaskService daily, + DailyTaskAudience audience, + IUserNotificationService notifications, + ILoggerFactory loggerFactory) : IDailyTaskReminderService +{ + private readonly ILogger _logger = loggerFactory.CreateLogger(); + + public const string Source = "daily_task"; + + // Tbilisi is UTC+4 all year. + private const int EarliestHourUtc = 6; // 10:00 Tbilisi + private const int LatestHourUtc = 17; // 21:00 Tbilisi + private const int DefaultHourUtc = 15; // 19:00 Tbilisi + private const int LastChanceHourUtc = 18; // after 22:00 Tbilisi — silence until tomorrow + + public Task DispatchAsync(CancellationToken ct) => DispatchAsync(DateTime.UtcNow, ct); + + public async Task DispatchAsync(DateTime nowUtc, CancellationToken ct) + { + if (nowUtc.Hour >= LastChanceHourUtc) + { + return; + } + + // Only the listed people, even where the task is open to everyone (the local stand): the stand's + // database holds other people's Telegram ids, and they must not hear from the test bot. + var ids = audience.TelegramIds.ToList(); + var users = await db.Users + .Where(u => u.IsActive && u.NotificationsEnabled && ids.Contains(u.TelegramId)) + .ToListAsync(ct); + + foreach (var user in users) + { + var lastPlayed = await db.MiniAppUserProgresses + .Where(p => p.UserId == user.Id) + .Select(p => p.LastPlayedAtUtc) + .FirstOrDefaultAsync(ct); + if (nowUtc.Hour < SendHourUtc(lastPlayed)) + { + continue; + } + + await RemindAsync(user, nowUtc, force: false, ct); + } + + // The sender flags people who have blocked the bot as inactive — keep that. + await db.SaveChangesAsync(ct); + } + + /// + /// Sends today's reminder to one person now. (the stand's «сообщение бота») + /// skips the once-a-day claim. False when there is nothing to remind about: no task, or it is done. + /// + public async Task RemindAsync(User user, DateTime nowUtc, bool force, CancellationToken ct) + { + var task = await daily.GetAsync(user, nowUtc, dev: false, ct); + if (!task.Available || task.Done) + { + return false; + } + + if (!force) + { + var claimed = await db.TryClaimNotificationTriggerAsync( + user.TelegramId, Source, task.Mode, nowUtc, nowUtc.Date.AddTicks(-1), ct); + if (!claimed) + { + return false; + } + } + + _logger.LogInformation("Daily task reminder to {TelegramId}: {Mode}", user.TelegramId, task.Mode); + await notifications.SendDailyTaskReminderAsync(user, string.Join("\n\n", task.Chat), task.Button, ct); + return true; + } + + /// The hour (UTC) the person last studied, within the day window; 19:00 Tbilisi when unknown. + public static int SendHourUtc(DateTime? lastPlayedUtc) => + lastPlayedUtc is { } at ? Math.Clamp(at.Hour, EarliestHourUtc, LatestHourUtc) : DefaultHourUtc; +} + +public interface IDailyTaskReminderService +{ + Task DispatchAsync(CancellationToken ct); +} diff --git a/src/Application/DailyTask/DailyTaskService.cs b/src/Application/DailyTask/DailyTaskService.cs new file mode 100644 index 00000000..36c096fb --- /dev/null +++ b/src/Application/DailyTask/DailyTaskService.cs @@ -0,0 +1,454 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading; +using System.Threading.Tasks; +using Application.Common; +using Application.Common.Interfaces.MiniApp; +using Application.MiniApp; +using Application.Verbs; +using Domain.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Application.DailyTask; + +/// What the result endpoint returns: the played task, the XP credited and the mini-app progress after it. +public record DailySaved(DailyTaskDto Task, int XpEarned, object? Progress); + +/// +/// The task of the day for one learner: composed once a day from their forms and dictionary +/// (, ), kept for the day so the screen and +/// the bot message agree, and played out — form outcomes go through +/// so the repetition schedule stays the same as in verb sessions. +/// Service per ARCHITECTURE.md. +/// +public class DailyTaskService( + ITraleDbContext dbContext, + VerbProgressService verbProgress, + IProgressCalculator progressCalculator, + ICourseCatalog catalog) +{ + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + private static readonly string[] LadderTenses = + { "present", "aorist", "imperfect", "optative", "conditional", "future" }; + + private static readonly string[] Persons = { "я", "ты", "он", "мы", "вы", "они" }; + + // The verb session's rules for new forms (miniapp-src/src/verbs/session/plan.ts and ladder/engine.ts): + // how many it opens at once, from which step a form counts as settled, how many unsettled ones it allows. + private const int NewFormsPerSession = 3; + private const int SettledStep = 3; + private const int MaxUnsettled = 3; + private static readonly int[] PersonOrder = { 0, 2, 1, 3, 5, 4 }; + private static readonly string[] FirstTenses = { "present", "aorist", "future" }; + + /// + /// The order the session introduces forms in (introOrder in ladder/engine.ts): я/он/ты of the first + /// tenses, then «я» of the rest, then мы/они/вы of the first tenses, then everything else. + /// + private static IEnumerable<(string Tense, int Person)> IntroOrder(IEnumerable<(string Tense, int Person)> cells) => + cells.OrderBy(c => + { + var person = Array.IndexOf(PersonOrder, c.Person); + var first = FirstTenses.Contains(c.Tense); + var round = first ? (person < 3 ? 0 : 2) : (person == 0 ? 1 : 3); + return round * 1000 + person * 10 + Array.IndexOf(LadderTenses, c.Tense); + }); + + /// Today's task; composed on the first call of the day. + public async Task GetAsync(User user, DateTime now, bool dev, CancellationToken ct) + { + var state = await LoadStateAsync(user.Id, now, ct); + var today = DateOnly.FromDateTime(now); + if (state.Day == today && state.TaskJson != null) + { + return Read(state.TaskJson) with { Dev = dev }; + } + + var task = await ComposeAsync(user, state, now, ct); + state.Day = today; + state.TaskJson = Write(task); + state.UpdatedAtUtc = now; + await dbContext.SaveChangesAsync(ct); + return task with { Dev = dev }; + } + + /// + /// Plays the task out: moves the forms on the ladder, counts dictionary answers, credits XP and + /// the streak, decides whether "new" is offered. A repeated report of the same day changes nothing. + /// Null when there is no task of that day. + /// + public async Task SaveResultAsync(User user, DailyReport report, DateTime now, bool dev, CancellationToken ct) + { + var state = await LoadStateAsync(user.Id, now, ct); + if (state.TaskJson == null || state.Day?.ToString("yyyy-MM-dd") != report.Day) + { + return null; + } + + var task = Read(state.TaskJson); + var progress = await MiniAppHelpers.LoadOrCreateProgressAsync(dbContext, user.Id, ct); + if (task.Done) + { + return new DailySaved(task with { Dev = dev }, 0, progressCalculator.SerializeProgress(progress)); + } + + var warmWrong = report.WarmWrong.ToHashSet(); + var pairWrong = report.PairWrong.ToHashSet(); + var errors = Math.Max(report.Errors, pairWrong.Count); + + await ApplyFormsAsync(user.Id, task, warmWrong, pairWrong, now, ct); + await ApplyWordsAsync(user.Id, task, pairWrong, now, ct); + + progressCalculator.CreditPractice(progress, DailyTaskPlanner.XpReward); + + state.Accuracy = DailyTaskPlanner.NextAccuracy(state.Accuracy, errors); + state.LastErrors = errors; + state.MissedJson = JsonSerializer.Serialize(task.Pairs.Where(p => p.Kind == "verb" && pairWrong.Contains(p.Key)).Select(p => p.Key)); + state.DoneDay = state.Day; + + var offer = errors <= 1 && task.Mode != DailyMode.Review ? task.Next : null; + task = task with + { + Done = true, + Offer = offer, + Result = new DailyResult(errors, DailyTaskPlanner.XpReward, progress.Streak) + }; + state.TaskJson = Write(task); + state.UpdatedAtUtc = now; + await dbContext.SaveChangesAsync(ct); + + return new DailySaved(task with { Dev = dev }, DailyTaskPlanner.XpReward, progressCalculator.SerializeProgress(progress)); + } + + /// + /// The offer was taken: fresh forms or a lesson were opened ("opened"), or the one-minute module check + /// ended ("passed" / "failed"). Remembered so the next offer alternates and the check is not asked again. + /// + public async Task ReportOfferAsync(User user, string day, string outcome, DateTime now, bool dev, CancellationToken ct) + { + var state = await LoadStateAsync(user.Id, now, ct); + if (state.TaskJson == null || state.Day?.ToString("yyyy-MM-dd") != day) + { + return null; + } + + var task = Read(state.TaskJson); + if (task.Offer == null) + { + return task with { Dev = dev }; + } + + state.LastNew = task.Offer.Kind == DailyNew.Forms ? DailyNew.Forms : DailyNew.Lesson; + if (task.Offer.Kind == DailyNew.Check && task.Offer.ModuleId != null && outcome is "passed" or "failed") + { + var course = ReadCourse(state.CourseJson); + course[task.Offer.ModuleId] = outcome == "passed" ? CoursePlanner.Known : CoursePlanner.Lessons; + state.CourseJson = JsonSerializer.Serialize(course); + } + + task = task with { OfferTaken = true }; + state.TaskJson = Write(task); + state.UpdatedAtUtc = now; + await dbContext.SaveChangesAsync(ct); + return task with { Dev = dev }; + } + + /// + /// Local stand only: moves everything the learner did days back, as if that + /// much time passed — the next task is composed by the same rules as on a real next day. + /// + public async Task DevShiftAsync(Guid userId, int days, CancellationToken ct) + { + var shift = TimeSpan.FromDays(days); + foreach (var f in await dbContext.VerbFormProgresses.Where(p => p.UserId == userId).ToListAsync(ct)) + { + f.UpdatedAtUtc -= shift; + f.CreatedAtUtc -= shift; + f.NextDueAtUtc -= shift; + } + + foreach (var w in await dbContext.VocabularyEntries.Where(e => e.UserId == userId).ToListAsync(ct)) + { + w.UpdatedAtUtc -= shift; + w.DateAddedUtc -= shift; + } + + var progress = await dbContext.MiniAppUserProgresses.FirstOrDefaultAsync(p => p.UserId == userId, ct); + if (progress != null) + { + progress.LastPlayedAtUtc -= shift; + var activity = JsonSerializer.Deserialize>(progress.ActivityDaysJson ?? "[]") ?? []; + progress.ActivityDaysJson = JsonSerializer.Serialize(activity.Select(d => d - shift)); + } + + var state = await dbContext.DailyTaskStates.FirstOrDefaultAsync(s => s.UserId == userId, ct); + if (state != null) + { + state.Day = state.Day?.AddDays(-days); + state.DoneDay = state.DoneDay?.AddDays(-days); + } + + await dbContext.SaveChangesAsync(ct); + } + + private async Task ComposeAsync( + User user, DailyTaskState state, DateTime now, CancellationToken ct) + { + var today = DateOnly.FromDateTime(now); + var progress = await dbContext.MiniAppUserProgresses.AsNoTracking().FirstOrDefaultAsync(p => p.UserId == user.Id, ct); + var lastPlayed = progress?.LastPlayedAtUtc is { } at ? DateOnly.FromDateTime(at) : (DateOnly?)null; + var away = lastPlayed == null ? 0 : Math.Max(0, today.DayNumber - lastPlayed.Value.DayNumber - 1); + + // A skipped day wipes the memory of the last game: its mistakes are no longer "yesterday's". + var fresh = state.DoneDay != null && today.DayNumber - state.DoneDay.Value.DayNumber <= 1; + + var (forms, unopened) = await LoadFormsAsync(user.Id, ct); + var words = await LoadWordsAsync(user.Id, ct); + var completed = ReadCompleted(progress?.CompletedLessonsJson); + + var input = new DailyInput + { + Now = now, + Away = away, + Streak = progress?.Streak ?? 0, + PlayedToday = lastPlayed == today, + PlayedYesterday = lastPlayed == today.AddDays(-1), + Accuracy = state.Accuracy, + LastErrors = fresh ? state.LastErrors : 0, + LastTaskYesterday = state.DoneDay == today.AddDays(-1), + LastNew = state.LastNew, + Missed = fresh ? JsonSerializer.Deserialize>(state.MissedJson) ?? [] : [], + Forms = forms, + Unopened = unopened, + Words = words, + Course = CoursePlanner.Next(catalog.Modules(), completed, ReadCourse(state.CourseJson)), + // Not HashCode.Combine: it is randomized per process, and the day's shuffle must not depend on a restart. + Seed = user.Id.GetHashCode() ^ today.DayNumber + }; + return DailyTaskPlanner.Compose(input); + } + + /// Opened forms with their text and meaning, and what is still closed in the started verbs. + private async Task<(List Forms, List Unopened)> LoadFormsAsync(Guid userId, CancellationToken ct) + { + var rows = await dbContext.VerbFormProgresses + .AsNoTracking() + .Where(p => p.UserId == userId) + .ToListAsync(ct); + var verbIds = rows.Select(r => r.VerbId).Distinct().ToList(); + var verbs = await dbContext.Verbs + .AsNoTracking() + .Where(v => verbIds.Contains(v.Id)) + .Select(v => new { v.Id, v.Lemma, v.Translation, v.CardJson }) + .ToListAsync(ct); + var meanings = await dbContext.VerbForms + .AsNoTracking() + .Where(f => verbIds.Contains(f.VerbId) && f.Meaning != null) + .Select(f => new { f.VerbId, f.Tense, f.Person, f.Form, f.Meaning }) + .ToListAsync(ct); + var levels = await dbContext.UserVerbs + .AsNoTracking() + .Where(v => v.UserId == userId && verbIds.Contains(v.VerbId)) + .ToDictionaryAsync(v => v.VerbId, v => v.Level, ct); + + string Meaning(Guid verbId, string tense, int person, string ka) => + meanings.FirstOrDefault(m => m.VerbId == verbId && m.Tense == tense && m.Person == person && m.Form == ka)?.Meaning + ?? meanings.FirstOrDefault(m => m.VerbId == verbId && m.Tense == tense && m.Person == person)?.Meaning + ?? $"{Persons[person]} · {DailyTaskPlanner.TenseName(tense)}"; + + var forms = new List(); + var unopened = new List(); + foreach (var verb in verbs) + { + var cells = Cells(verb.CardJson); + var verbRu = verb.Translation.Split(',')[0].Trim(); + var own = rows.Where(r => r.VerbId == verb.Id).ToDictionary(r => (r.Tense, r.Person)); + + // The verb session opens new forms only while the verb is not near its exam and what was + // started has settled (verbs/session/plan.ts: canMeet) — the offer must not promise more. + var level = levels.GetValueOrDefault(verb.Id); + var unsettled = own.Values.Count(r => r.Step is > 0 and < SettledStep); + if (level < VerbLevel.ExamReady && unsettled <= MaxUnsettled) + { + var next = IntroOrder(cells.Where(c => !own.ContainsKey(c.Key)).Select(c => c.Key)) + .Take(NewFormsPerSession) + .Select(c => new DailyFresh(c.Tense, c.Person, Meaning(verb.Id, c.Tense, c.Person, cells.First(x => x.Key == c).Value))) + .ToList(); + if (next.Count > 0) + { + unopened.Add(new DailyUnopened(verb.Lemma, verbRu, next)); + } + } + + foreach (var ((tense, person), ka) in cells) + { + if (!own.TryGetValue((tense, person), out var row)) + { + continue; + } + + var ru = Meaning(verb.Id, tense, person, ka); + forms.Add(new DailyForm( + verb.Lemma, verbRu, tense, person, ka, ru, + row.Step, row.BestStep, row.Reviews, row.NextDueAtUtc, row.UpdatedAtUtc)); + } + } + + return (forms, unopened); + } + + /// Dictionary entries that have a Georgian side. + private async Task> LoadWordsAsync(Guid userId, CancellationToken ct) + { + var entries = await dbContext.VocabularyEntries + .AsNoTracking() + .Where(e => e.UserId == userId) + .ToListAsync(ct); + return entries + .Select(e => (Entry: e, Sides: MiniAppHelpers.GetSides(e))) + .Where(x => MiniAppHelpers.ContainsGeorgian(x.Sides.georgian) && !MiniAppHelpers.ContainsGeorgian(x.Sides.russian)) + .Select(x => new DailyWord( + x.Entry.Id, x.Sides.georgian.Trim(), x.Sides.russian.Trim(), + x.Entry.SuccessAnswersCount + x.Entry.SuccessAnswersCountInReverseDirection, + x.Entry.FailedAnswersCount, + x.Entry.DateAddedUtc, + x.Entry.UpdatedAtUtc)) + .ToList(); + } + + private async Task ApplyFormsAsync( + Guid userId, DailyTaskDto task, HashSet warmWrong, HashSet pairWrong, DateTime now, CancellationToken ct) + { + var played = task.Warm.Select(w => (w.Item, Warm: true, w.Due)) + .Concat(task.Pairs.Select(p => (Item: p, Warm: false, Due: false))) + .Where(x => x.Item.Kind == "verb" && x.Item.Lemma != null) + .ToList(); + foreach (var verb in played.GroupBy(x => x.Item.Lemma!)) + { + var state = await verbProgress.GetAsync(userId, verb.Key, now, ct); + if (state == null) + { + continue; + } + + var steps = new List(); + foreach (var (item, warm, due) in verb) + { + var row = state.Forms.FirstOrDefault(f => f.Tense == item.Tense && f.Person == item.Person); + if (row == null) + { + continue; + } + + var mastered = row.Step == VerbFormProgress.MasteredStep; + if (warm) + { + // A due form answered wrong goes one step back into play; a long-unseen verb is only marked as practised. + steps.Add(!due ? new VerbFormStep(row.Tense, row.Person, row.Step, row.Reviews, now) + : warmWrong.Contains(item.Key) ? new VerbFormStep(row.Tense, row.Person, VerbFormProgress.MasteredStep - 1, row.Reviews, now) + : new VerbFormStep(row.Tense, row.Person, row.Step, row.Reviews + 1, now)); + } + else if (!pairWrong.Contains(item.Key)) + { + steps.Add(mastered + ? new VerbFormStep(row.Tense, row.Person, row.Step, row.Reviews + 1, now) + : new VerbFormStep(row.Tense, row.Person, row.Step + 1, row.Step + 1 == VerbFormProgress.MasteredStep ? 0 : row.Reviews, now)); + } + } + + await verbProgress.SaveAsync(userId, verb.Key, steps, now, ct); + } + } + + private async Task ApplyWordsAsync(Guid userId, DailyTaskDto task, HashSet pairWrong, DateTime now, CancellationToken ct) + { + var ids = task.Pairs.Where(p => p.Kind == "word" && Guid.TryParse(p.Key[2..], out _)) + .ToDictionary(p => Guid.Parse(p.Key[2..]), p => p.Key); + if (ids.Count == 0) + { + return; + } + + var entries = await dbContext.VocabularyEntries + .Where(e => e.UserId == userId && ids.Keys.Contains(e.Id)) + .ToListAsync(ct); + foreach (var entry in entries) + { + if (pairWrong.Contains(ids[entry.Id])) + { + entry.FailedAnswersCount++; + } + else + { + entry.SuccessAnswersCount++; + } + + entry.UpdatedAtUtc = now; + } + } + + private async Task LoadStateAsync(Guid userId, DateTime now, CancellationToken ct) + { + var state = await dbContext.DailyTaskStates.FirstOrDefaultAsync(s => s.UserId == userId, ct); + if (state != null) + { + return state; + } + + state = new DailyTaskState { Id = Guid.NewGuid(), UserId = userId, CreatedAtUtc = now, UpdatedAtUtc = now }; + dbContext.DailyTaskStates.Add(state); + return state; + } + + /// The ladder's cells of a verb with the form text, in the card's order — as the verb sessions teach them. + private static List> Cells(string cardJson) + { + var cells = new List>(); + var card = JsonNode.Parse(cardJson); + if (card?["tenses"] is not JsonObject tenses) + { + return cells; + } + + var unverified = VerbVerification.Of(card); + foreach (var tense in LadderTenses.Where(t => !unverified.Contains(t))) + { + if (tenses[tense] is not JsonArray persons) + { + continue; + } + + for (var person = 0; person < persons.Count; person++) + { + if (persons[person] is JsonArray { Count: > 0 } variants && variants[0]?.GetValue() is { Length: > 0 } form) + { + cells.Add(new((tense, person), form)); + } + } + } + + return cells; + } + + private static Dictionary> ReadCompleted(string? json) + { + if (string.IsNullOrWhiteSpace(json)) + { + return new(); + } + + var parsed = JsonSerializer.Deserialize>>(json) ?? new(); + return parsed.ToDictionary(p => p.Key, p => (IReadOnlyCollection)p.Value.ToHashSet()); + } + + private static Dictionary ReadCourse(string json) => + JsonSerializer.Deserialize>(json) ?? new(); + + private static DailyTaskDto Read(string json) => JsonSerializer.Deserialize(json, Json)!; + + private static string Write(DailyTaskDto task) => JsonSerializer.Serialize(task with { Dev = false }, Json); +} diff --git a/src/Application/DailyTask/ICourseCatalog.cs b/src/Application/DailyTask/ICourseCatalog.cs new file mode 100644 index 00000000..0b2b6238 --- /dev/null +++ b/src/Application/DailyTask/ICourseCatalog.cs @@ -0,0 +1,9 @@ +using System.Collections.Generic; + +namespace Application.DailyTask; + +/// The course as the trainer sees it: modules with their lessons, in catalog order. +public interface ICourseCatalog +{ + IReadOnlyList Modules(); +} diff --git a/src/Application/DependencyInjection.cs b/src/Application/DependencyInjection.cs index 53eca454..6def828e 100644 --- a/src/Application/DependencyInjection.cs +++ b/src/Application/DependencyInjection.cs @@ -107,6 +107,11 @@ public static IServiceCollection AddApplication(this IServiceCollection services services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + // «Задание дня»: the daily reminder; HourlyNotificationWorker ticks it. + services.AddScoped(); + services.AddScoped( + sp => sp.GetRequiredService()); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/Application/Notifications/DailyReturnNotificationService.cs b/src/Application/Notifications/DailyReturnNotificationService.cs index f14c1ccc..9fc12515 100644 --- a/src/Application/Notifications/DailyReturnNotificationService.cs +++ b/src/Application/Notifications/DailyReturnNotificationService.cs @@ -18,7 +18,8 @@ namespace Application.Notifications; public class DailyReturnNotificationService( ITraleDbContext db, IUserNotificationService notificationService, - ILoggerFactory loggerFactory) : IDailyReturnNotificationService + ILoggerFactory loggerFactory, + DailyTask.DailyTaskAudience? dailyTask = null) : IDailyReturnNotificationService { private readonly ILogger _logger = loggerFactory.CreateLogger(); private const string Source = "daily_return"; @@ -59,6 +60,10 @@ public async Task DispatchAsync(CancellationToken ct) if (!userMap.TryGetValue(progress.UserId, out var user)) continue; + // Whoever gets the «Задание дня» reminder (the listed people) gets it instead (DailyTaskReminderService). + if (dailyTask?.TelegramIds.Contains(user.TelegramId) == true) + continue; + var completedLessons = ParseCompletedLessons(progress.CompletedLessonsJson); var validModules = completedLessons .Where(kv => kv.Value.Count > 0) diff --git a/src/Domain/Entities/DailyTaskState.cs b/src/Domain/Entities/DailyTaskState.cs new file mode 100644 index 00000000..adc8e66b --- /dev/null +++ b/src/Domain/Entities/DailyTaskState.cs @@ -0,0 +1,43 @@ +// ReSharper disable PropertyCanBeMadeInitOnly.Global +// ReSharper disable UnusedAutoPropertyAccessor.Global +namespace Domain.Entities; + +/// +/// What the "task of the day" remembers about one learner between days: how the last games went +/// (that is what picks today's mode and level), what was offered as "new" last time, and the task +/// composed for the current day together with its result. +/// One row per learner; appears with the first task. +/// +public class DailyTaskState +{ + public Guid Id { get; set; } + public Guid UserId { get; set; } + public virtual User User { get; set; } = null!; + + /// Smoothed accuracy of the pairs game, 40..100; null until the first game. + public int? Accuracy { get; set; } + + /// Mistakes in the last finished game. + public int LastErrors { get; set; } + + /// What "new" was opened last: "forms" or "lesson" — the next offer alternates. + public string? LastNew { get; set; } + + /// JSON array of form keys ("v:lemma:tense:person") missed in the last game. + public string MissedJson { get; set; } = "[]"; + + /// JSON object moduleId → "known" | "lessons": how the one-minute module checks ended. + public string CourseJson { get; set; } = "{}"; + + /// The day (UTC, same as the streak) the task in was composed for. + public DateOnly? Day { get; set; } + + /// The task of as the mini-app got it, with the result once it is played. + public string? TaskJson { get; set; } + + /// The last day a task was finished. + public DateOnly? DoneDay { get; set; } + + public DateTime CreatedAtUtc { get; set; } + public DateTime UpdatedAtUtc { get; set; } +} diff --git a/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs b/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs index 19159dd1..5f3a9acc 100644 --- a/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs +++ b/src/Infrastructure/Telegram/Services/TelegramNotificationService.cs @@ -513,6 +513,39 @@ public async Task SendFirstWeekNudgeAsync(Domain.Entities.User user, Application await Task.Delay(BulkSendDelay, ct); } + public async Task SendDailyTaskReminderAsync(Domain.Entities.User user, string text, string button, CancellationToken ct) + { + if (!_botConfig.MiniAppEnabled || string.IsNullOrEmpty(_botConfig.HostAddress)) return; + + var url = $"{_botConfig.NormalizedHost()}/?screen=daily&src=push_daily_task"; + var keyboard = new InlineKeyboardMarkup(new[] + { + new[] { InlineKeyboardButton.WithWebApp(button, new WebAppInfo { Url = url }) } + }); + + try + { + await _client.SendTextMessageAsync(chatId: user.TelegramId, text: text, replyMarkup: keyboard, cancellationToken: ct); + } + catch (ApiRequestException ex) when (ex.ErrorCode == 429) + { + var retryAfterSeconds = ex.Parameters?.RetryAfter ?? 1; + _logger.LogInformation( + "Daily task reminder 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: text, replyMarkup: keyboard, cancellationToken: ct); + } + catch (ApiRequestException ex) when (ex.ErrorCode == 403) + { + _logger.LogInformation("Daily task reminder 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; diff --git a/src/Persistence/Configurations/DailyTaskStateConfiguration.cs b/src/Persistence/Configurations/DailyTaskStateConfiguration.cs new file mode 100644 index 00000000..ffa3758b --- /dev/null +++ b/src/Persistence/Configurations/DailyTaskStateConfiguration.cs @@ -0,0 +1,26 @@ +using Domain.Entities; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Persistence.Configurations; + +public class DailyTaskStateConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(s => s.Id); + + builder.Property(s => s.LastNew).HasMaxLength(16); + builder.Property(s => s.MissedJson).HasColumnType("text"); + builder.Property(s => s.CourseJson).HasColumnType("text"); + builder.Property(s => s.TaskJson).HasColumnType("text"); + + builder.HasOne(s => s.User) + .WithMany() + .HasForeignKey(s => s.UserId) + .OnDelete(DeleteBehavior.Cascade); + + // One row per learner. + builder.HasIndex(s => s.UserId).IsUnique(); + } +} diff --git a/src/Persistence/Migrations/20261116153713_AddDailyTaskState.Designer.cs b/src/Persistence/Migrations/20261116153713_AddDailyTaskState.Designer.cs new file mode 100644 index 00000000..d222e48c --- /dev/null +++ b/src/Persistence/Migrations/20261116153713_AddDailyTaskState.Designer.cs @@ -0,0 +1,1884 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using Persistence; + +#nullable disable + +namespace Persistence.Migrations +{ + [DbContext(typeof(TraleDbContext))] + [Migration("20261116153713_AddDailyTaskState")] + partial class AddDailyTaskState + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.25") + .HasAnnotation("Proxies:ChangeTracking", false) + .HasAnnotation("Proxies:CheckEquality", false) + .HasAnnotation("Proxies:LazyLoading", true) + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Domain.Entities.Achievement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AchievementTypeId") + .HasColumnType("uuid"); + + b.Property("DateAddedUtc") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text"); + + b.Property("Icon") + .IsRequired() + .HasColumnType("text"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Achievements"); + }); + + modelBuilder.Entity("Domain.Entities.AppEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Event") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Platform") + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("StartParam") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Target") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Value") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Event", "CreatedAtUtc"); + + b.HasIndex("UserId", "CreatedAtUtc"); + + b.ToTable("AppEvents", (string)null); + }); + + modelBuilder.Entity("Domain.Entities.BroadcastCampaign", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Audience") + .HasColumnType("integer"); + + b.Property("ButtonQuery") + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ButtonText") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("GiftDays") + .HasColumnType("integer"); + + b.Property("GiftOfferEndsAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(48) + .HasColumnType("character varying(48)"); + + b.Property("Message") + .IsRequired() + .HasColumnType("text"); + + b.Property("ScheduledAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ScheduledTimeZone") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("SendAllRequestedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("SurveyJson") + .HasColumnType("jsonb"); + + b.HasKey("Id"); + + b.HasIndex("Key") + .IsUnique(); + + b.ToTable("BroadcastCampaigns"); + }); + + modelBuilder.Entity("Domain.Entities.BroadcastDelivery", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CampaignId") + .HasColumnType("uuid"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Error") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("GiftAccessUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("GiftGrantedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("IsSample") + .HasColumnType("boolean"); + + b.Property("OpenedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("SentAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("SurveyFinishedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("SurveyOpenedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TelegramId") + .HasColumnType("bigint"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("CampaignId", "Status"); + + b.HasIndex("CampaignId", "UserId") + .IsUnique(); + + b.ToTable("BroadcastDeliveries"); + }); + + modelBuilder.Entity("Domain.Entities.DailyTaskState", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Accuracy") + .HasColumnType("integer"); + + b.Property("CourseJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Day") + .HasColumnType("date"); + + b.Property("DoneDay") + .HasColumnType("date"); + + b.Property("LastErrors") + .HasColumnType("integer"); + + b.Property("LastNew") + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("MissedJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("TaskJson") + .HasColumnType("text"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("DailyTaskStates"); + }); + + modelBuilder.Entity("Domain.Entities.FeedbackReply", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ClientToken") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Error") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("Quote") + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Text") + .HasMaxLength(3500) + .HasColumnType("character varying(3500)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ClientToken") + .IsUnique(); + + b.HasIndex("UserId", "CreatedAtUtc"); + + b.ToTable("FeedbackReplies"); + }); + + modelBuilder.Entity("Domain.Entities.GeorgianQuizSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CorrectAnswersCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("CurrentQuestionIndex") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("IncorrectAnswersCount") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("QuestionsJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("StartedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TelegramUserId") + .HasColumnType("bigint"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("WeakVerbsJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("[]"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAtUtc"); + + b.HasIndex("TelegramUserId"); + + b.HasIndex("UserId"); + + b.ToTable("GeorgianQuizSessions"); + }); + + modelBuilder.Entity("Domain.Entities.Invoice", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PreCheckoutQueryId") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Invoices"); + }); + + modelBuilder.Entity("Domain.Entities.LessonEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Event") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("LessonId") + .HasColumnType("integer"); + + b.Property("ModuleId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Step") + .HasColumnType("integer"); + + b.Property("StepKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Value") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "CreatedAtUtc"); + + b.HasIndex("ModuleId", "LessonId", "CreatedAtUtc"); + + b.ToTable("LessonEvents", (string)null); + }); + + modelBuilder.Entity("Domain.Entities.MiniAppUserProgress", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ActivityDaysJson") + .HasColumnType("text"); + + b.Property("CompletedLessonsJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("{}"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Hearts") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(5); + + b.Property("HeartsUpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastFedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastPlayedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastTreatIndex") + .HasColumnType("integer"); + + b.Property("Level") + .HasColumnType("text"); + + b.Property("MaxHearts") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(5); + + b.Property("OnboardingHintsJson") + .HasColumnType("text"); + + b.Property("SentenceBuilderProgressJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("{}"); + + b.Property("Streak") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("TotalTreatsGiven") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Xp") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("XpSpent") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("MiniAppUserProgresses"); + }); + + modelBuilder.Entity("Domain.Entities.ModelBudgetDay", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Day") + .HasColumnType("date"); + + b.Property("Generations") + .HasColumnType("integer"); + + b.Property("Requests") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Day", "UserId") + .IsUnique(); + + b.ToTable("ModelBudgetDays"); + }); + + modelBuilder.Entity("Domain.Entities.NotificationTrigger", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("LastSentAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("UserId") + .HasColumnType("bigint"); + + b.Property("Variant") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "Source") + .IsUnique(); + + b.ToTable("NotificationTriggers"); + }); + + modelBuilder.Entity("Domain.Entities.Payment", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Amount") + .HasColumnType("integer"); + + b.Property("Currency") + .IsRequired() + .HasMaxLength(8) + .HasColumnType("character varying(8)"); + + b.Property("PayloadId") + .IsRequired() + .HasColumnType("text"); + + b.Property("Plan") + .HasColumnType("integer"); + + b.Property("PurchasedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RefundedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TelegramPaymentChargeId") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("TelegramPaymentChargeId") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("Payments"); + }); + + modelBuilder.Entity("Domain.Entities.ProcessedUpdate", b => + { + b.Property("UpdateId") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("UpdateId")); + + b.Property("ProcessedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("RequestType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("character varying(1000)"); + + b.Property("UserTelegramId") + .HasColumnType("bigint"); + + b.HasKey("UpdateId"); + + b.HasIndex("ProcessedAt") + .HasDatabaseName("IX_ProcessedUpdate_ProcessedAt"); + + b.ToTable("ProcessedUpdates"); + }); + + modelBuilder.Entity("Domain.Entities.QueuedTranslation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("ChatId") + .HasColumnType("bigint"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("FinishedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LeaseOwner") + .HasColumnType("uuid"); + + b.Property("LeaseUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("MessageId") + .HasColumnType("integer"); + + b.Property("NoticeSent") + .HasColumnType("boolean"); + + b.Property("Outcome") + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Source") + .HasColumnType("integer"); + + b.Property("Stage") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("State") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("VerbLookup") + .HasColumnType("boolean"); + + b.Property("VocabularyEntryId") + .HasColumnType("uuid"); + + b.Property("Word") + .IsRequired() + .HasColumnType("text"); + + b.Property("WordKey") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAtUtc"); + + b.HasIndex("UserId", "WordKey", "CreatedAtUtc"); + + b.ToTable("QueuedTranslations", (string)null); + }); + + modelBuilder.Entity("Domain.Entities.Quiz", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CorrectAnswersCount") + .HasColumnType("integer"); + + b.Property("DateStarted") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone"); + + b.Property("IncorrectAnswersCount") + .HasColumnType("integer"); + + b.Property("IsCompleted") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("QuizType") + .IsRequired() + .HasMaxLength(13) + .HasColumnType("character varying(13)"); + + b.Property("ShareableQuizId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("Quizzes"); + + b.HasDiscriminator("QuizType").HasValue("Quiz"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("Domain.Entities.QuizQuestion", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Answer") + .IsRequired() + .HasColumnType("text"); + + b.Property("Example") + .IsRequired() + .HasColumnType("text"); + + b.Property("OrderInQuiz") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("Question") + .IsRequired() + .HasColumnType("text"); + + b.Property("QuestionType") + .IsRequired() + .HasMaxLength(34) + .HasColumnType("character varying(34)"); + + b.Property("QuizId") + .HasColumnType("uuid"); + + b.Property("VocabularyEntryId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("QuizId"); + + b.HasIndex("VocabularyEntryId"); + + b.ToTable("QuizQuestions"); + + b.HasDiscriminator("QuestionType").HasValue("QuizQuestion"); + + b.UseTphMappingStrategy(); + }); + + modelBuilder.Entity("Domain.Entities.Referral", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ActivatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("ActivationTrigger") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("BonusRefereeDays") + .HasColumnType("integer"); + + b.Property("BonusReferrerDays") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RefereeUserId") + .HasColumnType("uuid"); + + b.Property("ReferrerUserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RefereeUserId") + .IsUnique(); + + b.HasIndex("ReferrerUserId", "RefereeUserId") + .IsUnique(); + + b.ToTable("Referrals"); + }); + + modelBuilder.Entity("Domain.Entities.ShareableQuiz", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("CreatedByUserName") + .IsRequired() + .HasColumnType("text"); + + b.Property("DateAddedUtc") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone"); + + b.Property("QuizId") + .HasColumnType("uuid"); + + b.Property("QuizType") + .HasColumnType("integer"); + + b.Property("VocabularyEntriesIds") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByUserId"); + + b.HasIndex("QuizId") + .IsUnique(); + + b.ToTable("ShareableQuizzes"); + }); + + modelBuilder.Entity("Domain.Entities.TranslationCacheEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AdditionalInfo") + .IsRequired() + .HasColumnType("text"); + + b.Property("Classified") + .HasColumnType("boolean"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Definition") + .IsRequired() + .HasColumnType("text"); + + b.Property("Direction") + .HasColumnType("integer"); + + b.Property("Example") + .IsRequired() + .HasColumnType("text"); + + b.Property("HitCount") + .HasColumnType("integer"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("LastHitAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("Key", "Direction") + .IsUnique(); + + b.ToTable("TranslationCache", (string)null); + }); + + modelBuilder.Entity("Domain.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AccountType") + .HasColumnType("integer"); + + b.Property("AcquisitionSource") + .HasColumnType("text"); + + b.Property("BonusAccessUntilUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("InitialLanguageSet") + .HasColumnType("boolean"); + + b.Property("IsActive") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true); + + b.Property("IsPro") + .HasColumnType("boolean"); + + b.Property("NotificationsEnabled") + .HasColumnType("boolean"); + + b.Property("ProPurchasedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("RegisteredAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone"); + + b.Property("SubscribedUntil") + .HasColumnType("timestamp with time zone"); + + b.Property("SubscriptionPlan") + .HasColumnType("integer"); + + b.Property("TelegramId") + .HasColumnType("bigint"); + + b.Property("TrialBonusDays") + .HasColumnType("integer"); + + b.Property("UserSettingsId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Domain.Entities.UserFeedback", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CampaignKey") + .HasMaxLength(48) + .HasColumnType("character varying(48)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("Option") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("QuestionId") + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Text") + .HasMaxLength(2000) + .HasColumnType("character varying(2000)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAtUtc"); + + b.HasIndex("UserId", "CampaignKey", "QuestionId") + .IsUnique() + .HasFilter("\"Kind\" = 1"); + + b.HasIndex("UserId", "Kind", "CreatedAtUtc"); + + b.ToTable("UserFeedback", (string)null); + }); + + modelBuilder.Entity("Domain.Entities.UserSettings", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CurrentLanguage") + .HasColumnType("integer"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("UsersSettings"); + }); + + modelBuilder.Entity("Domain.Entities.UserVerb", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ExamPassedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastPlayedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Level") + .HasColumnType("integer"); + + b.Property("RecentScenesJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("SessionsPlayed") + .HasColumnType("integer"); + + b.Property("StartedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("StoryCompleted") + .HasColumnType("boolean"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("VerbId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("VerbId"); + + b.HasIndex("UserId", "VerbId") + .IsUnique(); + + b.ToTable("UserVerbs"); + }); + + modelBuilder.Entity("Domain.Entities.Verb", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CardJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("ContentHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("Lemma") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("PresentJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("SortOrder") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Translation") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("Lemma") + .IsUnique(); + + b.ToTable("Verbs"); + }); + + modelBuilder.Entity("Domain.Entities.VerbForm", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Form") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Meaning") + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("MeaningNote") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Person") + .HasColumnType("integer"); + + b.Property("Tense") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Unverified") + .HasColumnType("boolean"); + + b.Property("VerbId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Form"); + + b.HasIndex("VerbId"); + + b.ToTable("VerbForms"); + }); + + modelBuilder.Entity("Domain.Entities.VerbFormProgress", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("BestStep") + .HasColumnType("integer"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("NextDueAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Person") + .HasColumnType("integer"); + + b.Property("Reviews") + .HasColumnType("integer"); + + b.Property("Step") + .HasColumnType("integer"); + + b.Property("Tense") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("VerbId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("VerbId"); + + b.HasIndex("UserId", "NextDueAtUtc"); + + b.HasIndex("UserId", "VerbId", "Tense", "Person") + .IsUnique(); + + b.ToTable("VerbFormProgresses"); + }); + + modelBuilder.Entity("Domain.Entities.VerbProvenance", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ApprovedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("AskedText") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("CompletedTensesJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("[]"); + + b.Property("FormsAttested") + .HasColumnType("integer"); + + b.Property("FormsTotal") + .HasColumnType("integer"); + + b.Property("GeneratorModel") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("LemmaInLexicon") + .HasColumnType("boolean"); + + b.Property("MissingTensesJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("[]"); + + b.Property("OwnerApprovedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("OwnerApprovedBy") + .HasColumnType("bigint"); + + b.Property("RepairRounds") + .HasColumnType("integer"); + + b.Property("ReviewerModel") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ReviewerReasons") + .IsRequired() + .HasColumnType("text"); + + b.Property("RevisedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("TenseReviewsJson") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnType("text") + .HasDefaultValue("[]"); + + b.Property("UnattestedFormsJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("VerbId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("VerbId") + .IsUnique(); + + b.ToTable("VerbProvenances"); + }); + + modelBuilder.Entity("Domain.Entities.VerbSectionVisit", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("FirstOpenedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("LastOpenedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Opens") + .HasColumnType("integer"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Source"); + + b.HasIndex("UserId", "Source") + .IsUnique(); + + b.ToTable("VerbSectionVisits"); + }); + + modelBuilder.Entity("Domain.Entities.VerbSession", b => + { + b.Property("Id") + .HasColumnType("uuid"); + + b.Property("Done") + .HasColumnType("integer"); + + b.Property("FinishedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("PlanJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("Scene") + .HasColumnType("integer"); + + b.Property("StartedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("VerbId") + .HasColumnType("uuid"); + + b.Property("XpEarned") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("VerbId"); + + b.HasIndex("UserId", "FinishedAtUtc"); + + b.HasIndex("UserId", "VerbId", "FinishedAtUtc"); + + b.ToTable("VerbSessions"); + }); + + modelBuilder.Entity("Domain.Entities.VocabularyEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AdditionalInfo") + .IsRequired() + .HasColumnType("text"); + + b.Property("DateAddedUtc") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone"); + + b.Property("Definition") + .IsRequired() + .HasColumnType("text"); + + b.Property("Example") + .IsRequired() + .HasColumnType("text"); + + b.Property("FailedAnswersCount") + .HasColumnType("integer"); + + b.Property("Language") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0); + + b.Property("SuccessAnswersCount") + .HasColumnType("integer"); + + b.Property("SuccessAnswersCountInReverseDirection") + .HasColumnType("integer"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("Word") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.HasIndex("DateAddedUtc"); + + b.HasIndex("UserId"); + + b.ToTable("VocabularyEntries"); + }); + + modelBuilder.Entity("Domain.Entities.WaitlistEntry", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(254) + .HasColumnType("character varying(254)"); + + b.Property("Language") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.Property("Source") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAtUtc"); + + b.HasIndex("Email", "Language") + .IsUnique(); + + b.ToTable("WaitlistEntries", (string)null); + }); + + modelBuilder.Entity("Domain.Entities.SharedQuiz", b => + { + b.HasBaseType("Domain.Entities.Quiz"); + + b.Property("CreatedByUserName") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedByUserScore") + .HasColumnType("double precision"); + + b.HasDiscriminator().HasValue("SharedQuiz"); + }); + + modelBuilder.Entity("Domain.Entities.UserQuiz", b => + { + b.HasBaseType("Domain.Entities.Quiz"); + + b.HasDiscriminator().HasValue("UserQuiz"); + }); + + modelBuilder.Entity("Domain.Entities.QuizQuestionWithTypeAnswer", b => + { + b.HasBaseType("Domain.Entities.QuizQuestion"); + + b.HasDiscriminator().HasValue("QuizQuestionWithTypeAnswer"); + }); + + modelBuilder.Entity("Domain.Entities.QuizQuestionWithVariants", b => + { + b.HasBaseType("Domain.Entities.QuizQuestion"); + + b.Property("Variants") + .IsRequired() + .HasColumnType("text"); + + b.HasDiscriminator().HasValue("QuizQuestionWithVariants"); + }); + + modelBuilder.Entity("Domain.Entities.Achievement", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany("Achievements") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.AppEvent", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.BroadcastDelivery", b => + { + b.HasOne("Domain.Entities.BroadcastCampaign", null) + .WithMany() + .HasForeignKey("CampaignId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Domain.Entities.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Domain.Entities.DailyTaskState", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.FeedbackReply", b => + { + b.HasOne("Domain.Entities.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Domain.Entities.GeorgianQuizSession", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.Invoice", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany("Invoices") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.LessonEvent", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.MiniAppUserProgress", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.Payment", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany("Payments") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.QueuedTranslation", b => + { + b.HasOne("Domain.Entities.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Domain.Entities.Quiz", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany("Quizzes") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.QuizQuestion", b => + { + b.HasOne("Domain.Entities.Quiz", null) + .WithMany("QuizQuestions") + .HasForeignKey("QuizId"); + + b.HasOne("Domain.Entities.VocabularyEntry", "VocabularyEntry") + .WithMany("QuizQuestions") + .HasForeignKey("VocabularyEntryId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("VocabularyEntry"); + }); + + modelBuilder.Entity("Domain.Entities.ShareableQuiz", b => + { + b.HasOne("Domain.Entities.User", "CreatedByUser") + .WithMany("ShareableQuizzes") + .HasForeignKey("CreatedByUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Domain.Entities.Quiz", "Quiz") + .WithOne("ShareableQuiz") + .HasForeignKey("Domain.Entities.ShareableQuiz", "QuizId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CreatedByUser"); + + b.Navigation("Quiz"); + }); + + modelBuilder.Entity("Domain.Entities.UserFeedback", b => + { + b.HasOne("Domain.Entities.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Domain.Entities.UserSettings", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithOne("Settings") + .HasForeignKey("Domain.Entities.UserSettings", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.UserVerb", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Domain.Entities.Verb", "Verb") + .WithMany() + .HasForeignKey("VerbId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + + b.Navigation("Verb"); + }); + + modelBuilder.Entity("Domain.Entities.VerbForm", b => + { + b.HasOne("Domain.Entities.Verb", "Verb") + .WithMany("Forms") + .HasForeignKey("VerbId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Verb"); + }); + + modelBuilder.Entity("Domain.Entities.VerbFormProgress", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Domain.Entities.Verb", "Verb") + .WithMany() + .HasForeignKey("VerbId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + + b.Navigation("Verb"); + }); + + modelBuilder.Entity("Domain.Entities.VerbProvenance", b => + { + b.HasOne("Domain.Entities.Verb", "Verb") + .WithOne() + .HasForeignKey("Domain.Entities.VerbProvenance", "VerbId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Verb"); + }); + + modelBuilder.Entity("Domain.Entities.VerbSectionVisit", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.VerbSession", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Domain.Entities.Verb", "Verb") + .WithMany() + .HasForeignKey("VerbId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + + b.Navigation("Verb"); + }); + + modelBuilder.Entity("Domain.Entities.VocabularyEntry", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany("VocabularyEntries") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Domain.Entities.Quiz", b => + { + b.Navigation("QuizQuestions"); + + b.Navigation("ShareableQuiz"); + }); + + modelBuilder.Entity("Domain.Entities.User", b => + { + b.Navigation("Achievements"); + + b.Navigation("Invoices"); + + b.Navigation("Payments"); + + b.Navigation("Quizzes"); + + b.Navigation("Settings") + .IsRequired(); + + b.Navigation("ShareableQuizzes"); + + b.Navigation("VocabularyEntries"); + }); + + modelBuilder.Entity("Domain.Entities.Verb", b => + { + b.Navigation("Forms"); + }); + + modelBuilder.Entity("Domain.Entities.VocabularyEntry", b => + { + b.Navigation("QuizQuestions"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Persistence/Migrations/20261116153713_AddDailyTaskState.cs b/src/Persistence/Migrations/20261116153713_AddDailyTaskState.cs new file mode 100644 index 00000000..245b8926 --- /dev/null +++ b/src/Persistence/Migrations/20261116153713_AddDailyTaskState.cs @@ -0,0 +1,56 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Persistence.Migrations +{ + /// + public partial class AddDailyTaskState : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "DailyTaskStates", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + UserId = table.Column(type: "uuid", nullable: false), + Accuracy = table.Column(type: "integer", nullable: true), + LastErrors = table.Column(type: "integer", nullable: false), + LastNew = table.Column(type: "character varying(16)", maxLength: 16, nullable: true), + MissedJson = table.Column(type: "text", nullable: false), + CourseJson = table.Column(type: "text", nullable: false), + Day = table.Column(type: "date", nullable: true), + TaskJson = table.Column(type: "text", nullable: true), + DoneDay = table.Column(type: "date", nullable: true), + CreatedAtUtc = table.Column(type: "timestamp with time zone", nullable: false), + UpdatedAtUtc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_DailyTaskStates", x => x.Id); + table.ForeignKey( + name: "FK_DailyTaskStates_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_DailyTaskStates_UserId", + table: "DailyTaskStates", + column: "UserId", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "DailyTaskStates"); + } + } +} diff --git a/src/Persistence/Migrations/TraleDbContextModelSnapshot.cs b/src/Persistence/Migrations/TraleDbContextModelSnapshot.cs index 944954d1..caacd091 100644 --- a/src/Persistence/Migrations/TraleDbContextModelSnapshot.cs +++ b/src/Persistence/Migrations/TraleDbContextModelSnapshot.cs @@ -215,6 +215,56 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("BroadcastDeliveries"); }); + modelBuilder.Entity("Domain.Entities.DailyTaskState", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Accuracy") + .HasColumnType("integer"); + + b.Property("CourseJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("CreatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("Day") + .HasColumnType("date"); + + b.Property("DoneDay") + .HasColumnType("date"); + + b.Property("LastErrors") + .HasColumnType("integer"); + + b.Property("LastNew") + .HasMaxLength(16) + .HasColumnType("character varying(16)"); + + b.Property("MissedJson") + .IsRequired() + .HasColumnType("text"); + + b.Property("TaskJson") + .HasColumnType("text"); + + b.Property("UpdatedAtUtc") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("DailyTaskStates"); + }); + modelBuilder.Entity("Domain.Entities.FeedbackReply", b => { b.Property("Id") @@ -1541,6 +1591,17 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsRequired(); }); + modelBuilder.Entity("Domain.Entities.DailyTaskState", b => + { + b.HasOne("Domain.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + modelBuilder.Entity("Domain.Entities.FeedbackReply", b => { b.HasOne("Domain.Entities.User", null) diff --git a/src/Persistence/TraleDbContext.cs b/src/Persistence/TraleDbContext.cs index d463e3a8..775b91bf 100644 --- a/src/Persistence/TraleDbContext.cs +++ b/src/Persistence/TraleDbContext.cs @@ -37,6 +37,7 @@ public TraleDbContext(DbContextOptions options) public DbSet VerbFormProgresses { get; set; } = null!; public DbSet UserVerbs { get; set; } = null!; public DbSet VerbSessions { get; set; } = null!; + public DbSet DailyTaskStates { get; set; } = null!; public DbSet VerbSectionVisits { get; set; } = null!; public DbSet LessonEvents { get; set; } = null!; public DbSet AppEvents { get; set; } = null!; @@ -224,6 +225,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.ApplyConfiguration(new VerbFormProgressConfiguration()); modelBuilder.ApplyConfiguration(new UserVerbConfiguration()); modelBuilder.ApplyConfiguration(new VerbSessionConfiguration()); + modelBuilder.ApplyConfiguration(new DailyTaskStateConfiguration()); modelBuilder.ApplyConfiguration(new VerbSectionVisitConfiguration()); modelBuilder.ApplyConfiguration(new LessonEventConfiguration()); modelBuilder.ApplyConfiguration(new AppEventConfiguration()); diff --git a/src/Trale/Controllers/MiniAppController.cs b/src/Trale/Controllers/MiniAppController.cs index 80be4d1f..15262a3c 100644 --- a/src/Trale/Controllers/MiniAppController.cs +++ b/src/Trale/Controllers/MiniAppController.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Application.Common; +using Application.DailyTask; using Application.MiniApp; using Application.MiniApp.Commands; using Application.MiniApp.Queries; @@ -18,7 +19,9 @@ using Infrastructure.Telegram.BotCommands.PaymentCommands; using MediatR; using Infrastructure.Telegram.Services; +using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -1768,6 +1771,125 @@ public async Task SaveVerbSession( }; /// The caller when they may use the verbs section; otherwise the response to return. + // ── «Задание дня» ────────────────────────────────────────────────────────── + + /// + /// Today's task, composed once a day from the learner's own forms and dictionary. + /// available: false when there is nothing to build it from. + /// + [HttpGet("daily-task")] + public async Task GetDailyTask( + [FromServices] DailyTaskService daily, [FromServices] DailyTaskAudience audience, [FromServices] IWebHostEnvironment env, CancellationToken ct) + { + var (user, denied) = await ResolveVerbsUserAsync(ct); + if (denied != null) return denied; + if (!audience.Includes(user.TelegramId)) return NotFound(); + + return Ok(await daily.GetAsync(user, DateTime.UtcNow, IsStand(env), ct)); + } + + public class DailyResultRequest + { + public string Day { get; set; } = ""; + public List WarmWrong { get; set; } = new(); + public List PairWrong { get; set; } = new(); + public int Errors { get; set; } + public int CheckErrors { get; set; } + public int Seconds { get; set; } + } + + /// The task is played to the end. Idempotent: a repeated report returns what was saved. + [HttpPost("daily-task/result")] + public async Task SaveDailyTaskResult( + [FromBody] DailyResultRequest request, + [FromServices] DailyTaskService daily, + [FromServices] DailyTaskAudience audience, + [FromServices] IWebHostEnvironment env, + CancellationToken ct) + { + var (user, denied) = await ResolveVerbsUserAsync(ct); + if (denied != null) return denied; + if (!audience.Includes(user.TelegramId)) return NotFound(); + if (request == null || request.WarmWrong.Count > 50 || request.PairWrong.Count > 50) + { + return BadRequest(new { error = "invalid_result" }); + } + + var report = new DailyReport(request.Day, request.WarmWrong, request.PairWrong, Math.Max(0, request.Errors), Math.Max(0, request.CheckErrors)); + var saved = await daily.SaveResultAsync(user, report, DateTime.UtcNow, IsStand(env), ct); + return saved == null + ? Conflict(new { error = "stale_day" }) + : Ok(new { task = saved.Task, xpEarned = saved.XpEarned, progress = saved.Progress }); + } + + public class DailyOfferRequest + { + public string Day { get; set; } = ""; + public string Outcome { get; set; } = ""; + } + + /// The "new" offered after the task was opened, or the one-minute module check ended. + [HttpPost("daily-task/offer")] + public async Task ReportDailyTaskOffer( + [FromBody] DailyOfferRequest request, + [FromServices] DailyTaskService daily, + [FromServices] DailyTaskAudience audience, + [FromServices] IWebHostEnvironment env, + CancellationToken ct) + { + var (user, denied) = await ResolveVerbsUserAsync(ct); + if (denied != null) return denied; + if (!audience.Includes(user.TelegramId)) return NotFound(); + if (request == null || request.Outcome is not ("opened" or "passed" or "failed")) + { + return BadRequest(new { error = "invalid_outcome" }); + } + + var task = await daily.ReportOfferAsync(user, request.Day, request.Outcome, DateTime.UtcNow, IsStand(env), ct); + return task == null ? Conflict(new { error = "stale_day" }) : Ok(new { task }); + } + + public class DailyShiftRequest + { + public int Days { get; set; } = 1; + } + + /// Local stand only: as if days days passed — the task of the "next day" is composed. + [HttpPost("daily-task/dev/next-day")] + public async Task DailyTaskNextDay( + [FromBody] DailyShiftRequest request, + [FromServices] DailyTaskService daily, + [FromServices] DailyTaskAudience audience, + [FromServices] IWebHostEnvironment env, + CancellationToken ct) + { + if (!IsStand(env)) return NotFound(); + var (user, denied) = await ResolveVerbsUserAsync(ct); + if (denied != null) return denied; + if (!audience.Includes(user.TelegramId)) return NotFound(); + + await daily.DevShiftAsync(user.Id, Math.Clamp(request?.Days ?? 1, 1, 60), ct); + return Ok(new { task = await daily.GetAsync(user, DateTime.UtcNow, true, ct) }); + } + + /// Local stand only: today's reminder (the same message the hourly worker sends) — now. + [HttpPost("daily-task/dev/push")] + public async Task DailyTaskPush( + [FromServices] DailyTaskReminderService reminder, + [FromServices] DailyTaskAudience audience, + [FromServices] IWebHostEnvironment env, + CancellationToken ct) + { + if (!IsStand(env)) return NotFound(); + var (user, denied) = await ResolveVerbsUserAsync(ct); + if (denied != null) return denied; + if (!audience.Includes(user.TelegramId)) return NotFound(); + + return Ok(new { ok = await reminder.RemindAsync(user, DateTime.UtcNow, force: true, ct) }); + } + + private static bool IsStand(IWebHostEnvironment env) => env.IsEnvironment("local") || env.IsDevelopment(); + private async Task<(User User, IActionResult Denied)> ResolveVerbsUserAsync(CancellationToken ct) { var user = await ResolveUserAsync(ct); diff --git a/src/Trale/HostedServices/HourlyNotificationWorker.cs b/src/Trale/HostedServices/HourlyNotificationWorker.cs index 6885e0de..ec1c9fd0 100644 --- a/src/Trale/HostedServices/HourlyNotificationWorker.cs +++ b/src/Trale/HostedServices/HourlyNotificationWorker.cs @@ -85,6 +85,7 @@ public async Task RunOnceAsync(DateTime nowUtc, CancellationToken ct) await DispatchSafelyAsync(sp, "Streak", ct); await DispatchSafelyAsync(sp, "FirstOpenReminder", ct); await DispatchSafelyAsync(sp, "FirstWeekNudge", ct); + await DispatchSafelyAsync(sp, "DailyTaskReminder", ct); } private async Task DispatchSafelyAsync(IServiceProvider sp, string contextName, CancellationToken ct) @@ -126,6 +127,7 @@ private static Task InvokeDispatchAsync(TService service, Cancellation IStreakNotificationService s => s.DispatchAsync(ct), IFirstOpenReminderService f => f.DispatchAsync(ct), IFirstWeekNudgeService w => w.DispatchAsync(ct), + Application.DailyTask.IDailyTaskReminderService d => d.DispatchAsync(ct), _ => throw new InvalidOperationException( $"Unsupported dispatcher type {typeof(TService).FullName}"), }; diff --git a/src/Trale/MiniApp/MiniAppCourseCatalog.cs b/src/Trale/MiniApp/MiniAppCourseCatalog.cs new file mode 100644 index 00000000..954a726d --- /dev/null +++ b/src/Trale/MiniApp/MiniAppCourseCatalog.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; +using System.Linq; +using Application.DailyTask; + +namespace Trale.MiniApp; + +/// The mini-app catalog for «Задание дня»: built once, the catalog does not change while the app runs. +public class MiniAppCourseCatalog(ITraleMiniAppContentProvider content) : ICourseCatalog +{ + /// The owner when BotConfiguration.OwnerTelegramId is not set — as in the admin screens. + public const long DefaultOwnerTelegramId = 309149393; + + private IReadOnlyList? _modules; + + public IReadOnlyList Modules() => _modules ??= content.GetCatalog().Modules + .Select(m => new CourseModule(m.Id, m.Title, m.Lessons.Select(l => new CourseLesson(l.Id, l.Title)).ToList())) + .ToList(); +} diff --git a/src/Trale/Program.cs b/src/Trale/Program.cs index 8bcd036b..923bff0f 100644 --- a/src/Trale/Program.cs +++ b/src/Trale/Program.cs @@ -38,6 +38,15 @@ builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddScoped(); +builder.Services.AddSingleton(); +// «Задание дня» is tried out by the owner first: in production only the owner gets it, on the local stand everyone. +builder.Services.AddSingleton(sp => +{ + var env = sp.GetRequiredService(); + var bot = sp.GetRequiredService(); + var owner = bot.OwnerTelegramId != 0 ? bot.OwnerTelegramId : Trale.MiniApp.MiniAppCourseCatalog.DefaultOwnerTelegramId; + return new Application.DailyTask.DailyTaskAudience(Microsoft.Extensions.Hosting.HostEnvironmentEnvExtensions.IsEnvironment(env, "local") || Microsoft.Extensions.Hosting.HostEnvironmentEnvExtensions.IsDevelopment(env), [owner]); +}); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddHostedService(); diff --git a/src/Trale/miniapp-src/e2e/daily-task.spec.ts b/src/Trale/miniapp-src/e2e/daily-task.spec.ts new file mode 100644 index 00000000..36c5c5b9 --- /dev/null +++ b/src/Trale/miniapp-src/e2e/daily-task.spec.ts @@ -0,0 +1,286 @@ +import { test, expect, type Page } from '@playwright/test' +import { readFileSync, mkdirSync } from 'fs' +import { dirname, resolve } from 'path' +import { fileURLToPath } from 'url' + +// «Задание дня» глазами человека: карточка на главной → вступление → разминка → пары → проверка → итог → «новое». +// Задания — настоящие ответы сервера на настоящем профиле (fixtures/daily, их пишет DailyTaskService), вопросы +// минутной проверки — из файлов уроков «Знакомства»: грузинское здесь не пишется от руки. +// DAILY_SHOTS=<папка> — сохранить снимки каждого шага (375×667) для проверки глазами. + +const here = dirname(fileURLToPath(import.meta.url)) +const fixture = (name: string) => JSON.parse(readFileSync(resolve(here, 'fixtures/daily', name), 'utf8')) +const introQuestions = (lessonId: number) => + JSON.parse(readFileSync(resolve(here, `../../Lessons/GeorgianVocabIntro/questions${lessonId}.json`), 'utf8')).questions + .map((q: any) => ({ id: q.id, question: q.question, options: q.options, answerIndex: q.answer_index, explanation: q.explanation, questionType: 'choice' })) + +const TODAY = fixture('today.json') +const CLEAN = fixture('after-result.json') +const WITH_ERRORS = fixture('errors/after-result.json') +const CHECK = { + kind: 'check', title: 'Знакомство', line: 'проверка на минуту', button: 'Пройти проверку', + say: 'Последний урок модуля «Знакомство» у тебя пройден, а 22 урока пропущены. Ответь без ошибок на 6 вопросов из них — и модуль закрыт.', + moduleId: 'intro', checkLessons: [10, 11, 12, 13, 14, 15] +} + +interface Mock { + task: any + access?: boolean + /** Задание пока открыто только владельцу: остальным сервер отвечает 404. */ + owner?: boolean + results: any[] + offers: any[] + requests: string[] +} + +async function setup(page: Page, task: any, patch: Partial = {}): Promise { + const mock: Mock = { task, access: true, owner: true, results: [], offers: [], requests: [], ...patch } + await page.addInitScript(() => { + ;(window as any).Telegram = { + WebApp: { + initData: 'user=%7B%22id%22%3A123456%7D', + BackButton: { show: () => {}, hide: () => {}, onClick: () => {}, offClick: () => {} }, + MainButton: { show: () => {}, hide: () => {} }, + HapticFeedback: { impactOccurred: () => {}, notificationOccurred: () => {} }, + openTelegramLink: () => {} + } + } + }) + const catalog = { + botUsername: 'TraleBot', miniAppEnabled: true, + modules: [ + { id: 'alphabet-progressive', title: 'Алфавит', emoji: '', description: '', lessons: [{ id: 1, title: 'Первые буквы', short: '' }] }, + { id: 'cases', title: 'Падежи', emoji: '', description: '', lessons: Array.from({ length: 10 }, (_, i) => ({ id: i + 1, title: `Урок ${i + 1}`, short: '' })) }, + { id: 'intro', title: 'Знакомство', emoji: '', description: '', lessons: Array.from({ length: 33 }, (_, i) => ({ id: i + 1, title: `Урок ${i + 1}`, short: '' })) } + ] + } + const progress = { xp: 2173, streak: 2, lastPlayedAtUtc: '2026-11-16T09:31:43Z', completedLessons: { 'alphabet-progressive': [1], cases: [1, 2, 3, 4, 5, 6, 7] }, xpSpent: 0, totalTreatsGiven: 0, lastFedAtUtc: null, lastTreatIndex: null } + await page.route('**/api/miniapp/**', (route: any) => { + const request = route.request() + const path = decodeURIComponent(new URL(request.url()).pathname).replace('/api/miniapp/', '') + const body = () => { try { return JSON.parse(request.postData() ?? '{}') } catch { return {} } } + mock.requests.push(path) + if (path === 'content') return route.fulfill({ json: catalog }) + if (path === 'me') { + return route.fulfill({ json: { + authenticated: true, isPro: mock.access, isTrialActive: false, trialDaysLeft: 0, hasAccess: mock.access, + shouldShowReferralExtensionCta: false, level: 'beginner', vocabularyCount: 752, uiHintsSeen: [], progress + } }) + } + if (path === 'daily-task') { + if (!mock.owner) return route.fulfill({ status: 404, json: {} }) + return mock.access ? route.fulfill({ json: mock.task }) : route.fulfill({ status: 402, json: { error: 'subscription_required' } }) + } + if (path === 'daily-task/result') { + const report = body() + mock.results.push(report) + const played = report.pairWrong.length > 1 ? WITH_ERRORS : CLEAN + mock.task = { ...played, dev: false } + return route.fulfill({ json: { task: mock.task, xpEarned: 20, progress: { ...progress, xp: progress.xp + 20, streak: 3 } } }) + } + if (path === 'daily-task/offer') { + mock.offers.push(body()) + mock.task = { ...mock.task, offerTaken: true } + return route.fulfill({ json: { task: mock.task } }) + } + const lesson = path.match(/^modules\/intro\/lessons\/(\d+)\/questions$/) + if (lesson) return route.fulfill({ json: introQuestions(Number(lesson[1])) }) + if (path === 'verbs/section') return route.fulfill({ json: { levels: [], mine: [], learned: 0, total: 0, next: null } }) + if (path.startsWith('activity-days')) return route.fulfill({ json: { dates: [] } }) + return route.fulfill({ status: 404, json: {} }) + }) + return mock +} + +const shotsDir = process.env.DAILY_SHOTS +async function shot(page: Page, name: string) { + // На каждом шаге всё помещается в экран: прокрутки нет. + const fits = await page.evaluate(() => document.scrollingElement!.scrollHeight <= window.innerHeight + 1) + expect(fits, `${name}: экран прокручивается`).toBe(true) + if (!shotsDir) return + mkdirSync(shotsDir, { recursive: true }) + await page.waitForTimeout(400) + await page.screenshot({ path: resolve(shotsDir, `${name}.png`) }) +} + +async function openFromCard(page: Page) { + await page.goto('/?playwright=1') + const card = page.getByTestId('dashboard-daily') + await expect(card).toBeVisible({ timeout: 10_000 }) + await card.click() +} + +async function playWarm(page: Page, wrongFirst = false) { + for (let i = 0; i < TODAY.warm.length; i++) { + await expect(page.getByTestId('daily-warm-word')).toHaveAttribute('data-key', TODAY.warm[i].item.key) + if (i === 0) await shot(page, '2-warm') + await page.locator(`[data-testid="daily-warm-option"][data-ok="${wrongFirst && i === 0 ? 'no' : 'yes'}"]`).first().click() + } +} + +async function playPairs(page: Page, pairs: any[], mistakes = 0) { + await expect(page.getByTestId('daily-game')).toBeVisible({ timeout: 5000 }) + await shot(page, '3-game') + for (let m = 0; m < mistakes; m++) { + await page.locator(`[data-testid="daily-tile-l"][data-key="${pairs[m].key}"]`).click() + await page.locator(`[data-testid="daily-tile-r"][data-key="${pairs[m + 1].key}"]`).click() + await page.waitForTimeout(450) + } + for (const p of pairs) { + await page.locator(`[data-testid="daily-tile-l"][data-key="${p.key}"]`).click() + await page.locator(`[data-testid="daily-tile-r"][data-key="${p.key}"]`).click() + } + await expect(page.getByTestId('daily-game-say')).toHaveText('Все пары собраны.') +} + +async function playCheck(page: Page) { + await expect(page.getByTestId('daily-check')).toBeVisible({ timeout: 5000 }) + await expect(page.getByTestId('daily-check-say')).toHaveText(TODAY.check.intro) + await shot(page, '4-check') + const wrong = TODAY.check.picks.findIndex((p: any) => !p.ok) + await page.getByTestId('daily-pick').nth(wrong).click() + await expect(page.getByTestId('daily-check-say')).toHaveText(TODAY.check.picks[wrong].message) + await page.locator('[data-testid="daily-pick"][data-ok="yes"]').click() + await expect(page.getByTestId('daily-check-say')).toHaveText(TODAY.check.picks.find((p: any) => p.ok).message) + await page.getByRole('button', { name: 'Готово' }).click() +} + +test.describe('Задание дня', () => { + test.use({ viewport: { width: 375, height: 667 } }) + + test('чистый проход: карточка → разминка → пары → проверка → итог → новые формы', async ({ page }) => { + const mock = await setup(page, TODAY) + await page.goto('/?playwright=1') + const card = page.getByTestId('dashboard-daily') + await expect(card).toBeVisible({ timeout: 10_000 }) + await expect(card).toHaveAttribute('data-state', 'todo') + await expect(page.getByTestId('dashboard-daily-title')).toHaveText(TODAY.title) + await shot(page, '0-dashboard') + await card.click() + + await expect(page.getByTestId('daily-chat')).toHaveText(TODAY.chat) + await shot(page, '1-intro') + await page.getByTestId('daily-why-link').click() + await expect(page.getByTestId('daily-why')).toContainText(TODAY.why[0]) + await page.getByRole('button', { name: 'Понятно' }).click() + await expect(page.getByTestId('daily-why')).toBeHidden() + await page.getByRole('button', { name: TODAY.button }).click() + + await expect(page.getByTestId('daily-steps')).toHaveAttribute('data-steps', '3') + await playWarm(page) + await playPairs(page, TODAY.pairs) + await playCheck(page) + + await expect(page.getByTestId('daily-finale')).toBeVisible() + expect(mock.results).toHaveLength(1) + expect(mock.results[0]).toMatchObject({ day: TODAY.day, warmWrong: [], pairWrong: [], errors: 0, checkErrors: 1 }) + await expect(page.getByTestId('daily-streak')).toContainText('2') + await expect(page.getByTestId('daily-xp')).toContainText('+20') + await expect(page.getByTestId('daily-offer')).toHaveAttribute('data-kind', 'forms') + await expect(page.getByTestId('daily-finale-say')).toHaveText(CLEAN.offer.say) + await shot(page, '5-finale') + + await page.getByRole('button', { name: CLEAN.offer.button }).click() + await expect.poll(() => mock.offers).toEqual([{ day: TODAY.day, outcome: 'opened' }]) + // Новые формы открываются сессией глагола — она просит у сервера сам глагол. + await expect.poll(() => mock.requests.some(r => r.startsWith(`verbs/${CLEAN.offer.verbId}`))).toBe(true) + }) + + test('ошибки в разминке и в парах уходят на сервер, нового нет', async ({ page }) => { + const mock = await setup(page, TODAY) + await openFromCard(page) + await page.getByRole('button', { name: TODAY.button }).click() + await playWarm(page, true) + await playPairs(page, TODAY.pairs, 2) + await playCheck(page) + + await expect(page.getByTestId('daily-finale')).toBeVisible() + const report = mock.results[0] + expect(report.warmWrong).toEqual([TODAY.warm[0].item.key]) + expect(report.errors).toBe(2) + expect(report.pairWrong).toEqual(expect.arrayContaining([TODAY.pairs[0].key, TODAY.pairs[1].key, TODAY.pairs[2].key])) + await expect(page.getByTestId('daily-offer')).toHaveCount(0) + await expect(page.getByTestId('daily-finale-say')).toContainText('Нового сегодня нет') + await page.getByRole('button', { name: 'На главную' }).click() + await expect(page.getByTestId('dashboard-daily')).toHaveAttribute('data-state', 'done') + await expect(page.getByTestId('dashboard-daily-title')).toHaveText('Сделано сегодня') + }) + + test('время вышло: несобранное — ошибки, можно сыграть ещё раз', async ({ page }) => { + await page.clock.install() + const mock = await setup(page, { ...TODAY, warm: [] }) + await openFromCard(page) + await page.getByRole('button', { name: TODAY.button }).click() + await expect(page.getByTestId('daily-steps')).toHaveAttribute('data-steps', '2') + const first = TODAY.pairs[0] + await page.locator(`[data-testid="daily-tile-l"][data-key="${first.key}"]`).click() + await page.locator(`[data-testid="daily-tile-r"][data-key="${first.key}"]`).click() + await page.clock.runFor((TODAY.seconds + 1) * 1000) + await expect(page.getByText('Время вышло').first()).toBeVisible() + await shot(page, '3-timeout') + await page.getByRole('button', { name: 'Сыграть ещё раз' }).click() + await playPairs(page, TODAY.pairs) + await page.clock.runFor(1500) + await expect(page.getByTestId('daily-check')).toBeVisible() + await page.locator('[data-testid="daily-pick"][data-ok="yes"]').click() + await page.getByRole('button', { name: 'Готово' }).click() + await expect.poll(() => mock.results.length).toBe(1) + expect(mock.results[0].errors).toBe(TODAY.pairs.length - 1) + expect(mock.results[0].pairWrong).toEqual(TODAY.pairs.slice(1).map((p: any) => p.key)) + }) + + test('уже сделано сегодня: карточка ведёт к «новому», потом — «сделано»', async ({ page }) => { + const mock = await setup(page, CLEAN) + await page.goto('/?playwright=1') + await expect(page.getByTestId('dashboard-daily')).toHaveAttribute('data-state', 'offer', { timeout: 10_000 }) + await expect(page.getByTestId('dashboard-daily-title')).toHaveText(CLEAN.offer.title) + await page.getByTestId('dashboard-daily').click() + await expect(page.getByTestId('daily-finale')).toBeVisible() + await expect(page.getByTestId('daily-offer')).toBeVisible() + expect(mock.results).toHaveLength(0) + }) + + for (const passed of [true, false]) { + test(`минутная проверка модуля: ${passed ? 'пройдена' : 'не пройдена'}`, async ({ page }) => { + const mock = await setup(page, { ...CLEAN, offer: CHECK, next: CHECK }) + await openFromCard(page) + await expect(page.getByTestId('daily-offer')).toHaveAttribute('data-kind', 'check') + await page.getByRole('button', { name: 'Пройти проверку' }).click() + for (let i = 0; i < CHECK.checkLessons.length; i++) { + await expect(page.getByTestId('daily-steps')).toHaveAttribute('data-at', String(i + 1)) + if (i === 0) { + await expect(page.getByTestId('daily-minute-cyr')).toBeVisible() + await shot(page, '6-minute') + } + await page.locator(`[data-testid="daily-minute-option"][data-ok="${!passed && i === 2 ? 'no' : 'yes'}"]`).first().click() + await page.getByRole('button', { name: i + 1 < CHECK.checkLessons.length ? 'Дальше' : 'Готово' }).click() + } + await expect(page.getByTestId('daily-minute-say')).toContainText(passed ? 'тебе не нужны' : 'пригодятся') + await shot(page, passed ? '7-minute-passed' : '7-minute-failed') + expect(mock.offers).toEqual([{ day: CLEAN.day, outcome: passed ? 'passed' : 'failed' }]) + await page.getByRole('button', { name: 'Готово' }).click() + await expect(page.getByTestId('daily-finale')).toBeVisible() + await expect(page.getByTestId('daily-offer')).toHaveCount(0) + }) + } + + test('без доступа карточки нет', async ({ page }) => { + await setup(page, TODAY, { access: false }) + await page.goto('/?playwright=1') + await expect(page.getByTestId('dashboard-verbs-tile')).toBeVisible({ timeout: 10_000 }) + await expect(page.getByTestId('dashboard-daily')).toHaveCount(0) + }) + + test('пока задание открыто только владельцу: остальным карточки нет', async ({ page }) => { + await setup(page, TODAY, { owner: false }) + await page.goto('/?playwright=1') + await expect(page.getByTestId('dashboard-verbs-tile')).toBeVisible({ timeout: 10_000 }) + await expect(page.getByTestId('dashboard-daily')).toHaveCount(0) + }) + + test('ссылка из сообщения бота открывает задание', async ({ page }) => { + await setup(page, TODAY) + await page.goto('/?playwright=1&screen=daily') + await expect(page.getByTestId('daily-intro')).toBeVisible({ timeout: 10_000 }) + }) +}) diff --git a/src/Trale/miniapp-src/e2e/fixtures/daily/after-1-days.json b/src/Trale/miniapp-src/e2e/fixtures/daily/after-1-days.json new file mode 100644 index 00000000..298fa1df --- /dev/null +++ b/src/Trale/miniapp-src/e2e/fixtures/daily/after-1-days.json @@ -0,0 +1,221 @@ +{ + "available": true, + "day": "2026-11-16", + "done": false, + "mode": "mix", + "level": 3, + "title": "Обычный день", + "chat": [ + "1 день без занятий. У глагола «иметь» 1 форма ждёт повторения, а 3 формы стали получаться хуже. Глагол «идти» без практики с 20 октября — начни с него.", + "Повтори сегодня 6 форм и 2 слова из своего словаря. Это две минуты, и начнётся новая серия." + ], + "button": "Повторить", + "why": [ + "Без занятий: 1 день.", + "Ждут повторения по расписанию: 1 форма («иметь»).", + "Стали получаться хуже: 14 форм.", + "Три недели и дольше без практики: 5 глаголов.", + "В словаре 752 слова: новых за неделю — 2, с ошибками — 14.", + "Точность последних игр: 87% — уровень 3 из 3.", + "Новое в конце, если игра пройдёт чисто: Падежи — урок 8 из 10 · Итоговое повторение." + ], + "seconds": 35, + "warm": [ + { + "item": { + "key": "v:აქვს:present:0", + "kind": "verb", + "ka": "მაქვს", + "ru": "у меня есть", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "present", + "person": 0 + }, + "options": [ + { + "ru": "у меня есть", + "ok": true + }, + { + "ru": "у меня было бы", + "ok": false + }, + { + "ru": "у них есть", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:მიდის:optative:0", + "kind": "verb", + "ka": "წავიდე", + "ru": "мне надо идти", + "lemma": "მიდის", + "verbRu": "идти", + "tense": "optative", + "person": 0 + }, + "options": [ + { + "ru": "я иду", + "ok": false + }, + { + "ru": "ты идёшь", + "ok": false + }, + { + "ru": "мне надо идти", + "ok": true + } + ], + "due": false + }, + { + "item": { + "key": "v:მიდის:present:1", + "kind": "verb", + "ka": "მიდიხარ", + "ru": "ты идёшь", + "lemma": "მიდის", + "verbRu": "идти", + "tense": "present", + "person": 1 + }, + "options": [ + { + "ru": "я буду идти", + "ok": false + }, + { + "ru": "ты идёшь", + "ok": true + }, + { + "ru": "я иду", + "ok": false + } + ], + "due": false + } + ], + "pairs": [ + { + "key": "v:არის:aorist:5", + "kind": "verb", + "ka": "იყვნენ", + "ru": "они были", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 5 + }, + { + "key": "v:აქვს:imperfect:0", + "kind": "verb", + "ka": "მქონდა", + "ru": "у меня было", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "imperfect", + "person": 0 + }, + { + "key": "v:აქვს:future:3", + "kind": "verb", + "ka": "გვექნება", + "ru": "у нас будет", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "future", + "person": 3 + }, + { + "key": "w:00000000-0000-4000-8000-000000000003", + "kind": "word", + "ka": "ძინება", + "ru": "спать", + "lemma": null, + "verbRu": null, + "tense": null, + "person": null + }, + { + "key": "w:00000000-0000-4000-8000-000000000001", + "kind": "word", + "ka": "ვიპოვე", + "ru": "я находил(а)", + "lemma": null, + "verbRu": null, + "tense": null, + "person": null + } + ], + "check": { + "prompt": "Нажми форму, которая значит «они были»", + "intro": "Последнее задание. Формы похожи, смотри внимательно.", + "picks": [ + { + "item": { + "key": "v:არის:aorist:5", + "kind": "verb", + "ka": "იყვნენ", + "ru": "они были", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 5 + }, + "ok": true, + "message": "Верно: «იყვნენ» (икъвнэн) — они были." + }, + { + "item": { + "key": "v:არის:aorist:0", + "kind": "verb", + "ka": "ვიყავი", + "ru": "я был(а)", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 0 + }, + "ok": false, + "message": "«ვიყავი» (викъави) — это «я был(а)». Нажми другую форму." + }, + { + "item": { + "key": "v:არის:aorist:2", + "kind": "verb", + "ka": "იყო", + "ru": "он был", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 2 + }, + "ok": false, + "message": "«იყო» (икъо) — это «он был». Нажми другую форму." + } + ] + }, + "next": { + "kind": "lesson", + "title": "Падежи", + "line": "урок 8 из 10 · Итоговое повторение", + "say": "Модуль «Падежи»: пройдено 7 из 10. Пройди этот урок — до конца модуля останется 2.", + "button": "Пройти урок", + "verbId": null, + "moduleId": "cases", + "lessonId": 8, + "checkLessons": null + }, + "offer": null, + "offerTaken": false, + "result": null, + "dev": true +} \ No newline at end of file diff --git a/src/Trale/miniapp-src/e2e/fixtures/daily/after-offer.json b/src/Trale/miniapp-src/e2e/fixtures/daily/after-offer.json new file mode 100644 index 00000000..29c1d0d8 --- /dev/null +++ b/src/Trale/miniapp-src/e2e/fixtures/daily/after-offer.json @@ -0,0 +1,278 @@ +{ + "available": true, + "day": "2026-11-16", + "done": true, + "mode": "mix", + "level": 2, + "title": "Обычный день", + "chat": [ + "У глагола «быть» 5 форм ждут повторения, а у глагола «иметь» 3 формы стали получаться хуже.", + "Повтори сегодня 8 форм и 1 слово из своего словаря. Это две минуты." + ], + "button": "Повторить", + "why": [ + "Ждут повторения по расписанию: 5 форм («быть»).", + "Стали получаться хуже: 16 форм.", + "Три недели и дольше без практики: 5 глаголов.", + "В словаре 752 слова: новых за неделю — 3, с ошибками — 14.", + "Это первая игра, поэтому уровень средний.", + "Новое в конце, если игра пройдёт чисто: Новые формы глагола «идти» — я шёл / шла · он идёт · он будет идти." + ], + "seconds": 45, + "warm": [ + { + "item": { + "key": "v:არის:aorist:4", + "kind": "verb", + "ka": "იყავით", + "ru": "вы были", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 4 + }, + "options": [ + { + "ru": "вы были", + "ok": true + }, + { + "ru": "он был", + "ok": false + }, + { + "ru": "вы есть", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:0", + "kind": "verb", + "ka": "ვარ", + "ru": "я есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 0 + }, + "options": [ + { + "ru": "он был", + "ok": false + }, + { + "ru": "они будут", + "ok": false + }, + { + "ru": "я есть", + "ok": true + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:3", + "kind": "verb", + "ka": "ვართ", + "ru": "мы есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 3 + }, + "options": [ + { + "ru": "мы были", + "ok": false + }, + { + "ru": "мы есть", + "ok": true + }, + { + "ru": "я буду", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:aorist:1", + "kind": "verb", + "ka": "იყავი", + "ru": "ты был(а)", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 1 + }, + "options": [ + { + "ru": "я есть", + "ok": false + }, + { + "ru": "ты был(а)", + "ok": true + }, + { + "ru": "я буду", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:2", + "kind": "verb", + "ka": "არის", + "ru": "он есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 2 + }, + "options": [ + { + "ru": "мне надо быть", + "ok": false + }, + { + "ru": "он есть", + "ok": true + }, + { + "ru": "ты был(а)", + "ok": false + } + ], + "due": true + } + ], + "pairs": [ + { + "key": "v:აქვს:future:3", + "kind": "verb", + "ka": "გვექნება", + "ru": "у нас будет", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "future", + "person": 3 + }, + { + "key": "v:აქვს:present:4", + "kind": "verb", + "ka": "გაქვთ", + "ru": "у вас есть", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "present", + "person": 4 + }, + { + "key": "v:აქვს:imperfect:1", + "kind": "verb", + "ka": "გქონდა", + "ru": "у тебя было", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "imperfect", + "person": 1 + }, + { + "key": "w:00000000-0000-4000-8000-000000000002", + "kind": "word", + "ka": "სახრახნისი", + "ru": "отвертка", + "lemma": null, + "verbRu": null, + "tense": null, + "person": null + } + ], + "check": { + "prompt": "Нажми форму, которая значит «у нас будет»", + "intro": "Последнее задание: одна форма из сегодняшней игры.", + "picks": [ + { + "item": { + "key": "v:აქვს:conditional:1", + "kind": "verb", + "ka": "გექნებოდა", + "ru": "у тебя было бы", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "conditional", + "person": 1 + }, + "ok": false, + "message": "«გექნებოდა» (гэкнэбода) — это «у тебя было бы». Нажми другую форму." + }, + { + "item": { + "key": "v:აქვს:future:3", + "kind": "verb", + "ka": "გვექნება", + "ru": "у нас будет", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "future", + "person": 3 + }, + "ok": true, + "message": "Верно: «გვექნება» (гвэкнэба) — у нас будет." + }, + { + "item": { + "key": "v:აქვს:conditional:2", + "kind": "verb", + "ka": "ექნებოდა", + "ru": "у него было бы", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "conditional", + "person": 2 + }, + "ok": false, + "message": "«ექნებოდა» (экнэбода) — это «у него было бы». Нажми другую форму." + } + ] + }, + "next": { + "kind": "forms", + "title": "Новые формы глагола «идти»", + "line": "я шёл / шла · он идёт · он будет идти", + "say": "Игра прошла чисто — можно брать новое. Открой у глагола «идти» 3 новые формы: «я шёл / шла», «он идёт», «он будет идти». Это короткая сессия.", + "button": "Открыть новые формы", + "verbId": "მიდის", + "moduleId": null, + "lessonId": null, + "checkLessons": null + }, + "offer": { + "kind": "forms", + "title": "Новые формы глагола «идти»", + "line": "я шёл / шла · он идёт · он будет идти", + "say": "Игра прошла чисто — можно брать новое. Открой у глагола «идти» 3 новые формы: «я шёл / шла», «он идёт», «он будет идти». Это короткая сессия.", + "button": "Открыть новые формы", + "verbId": "მიდის", + "moduleId": null, + "lessonId": null, + "checkLessons": null + }, + "offerTaken": true, + "result": { + "errors": 0, + "xpEarned": 20, + "streak": 2 + }, + "dev": true +} \ No newline at end of file diff --git a/src/Trale/miniapp-src/e2e/fixtures/daily/after-result.json b/src/Trale/miniapp-src/e2e/fixtures/daily/after-result.json new file mode 100644 index 00000000..ec402d63 --- /dev/null +++ b/src/Trale/miniapp-src/e2e/fixtures/daily/after-result.json @@ -0,0 +1,278 @@ +{ + "available": true, + "day": "2026-11-16", + "done": true, + "mode": "mix", + "level": 2, + "title": "Обычный день", + "chat": [ + "У глагола «быть» 5 форм ждут повторения, а у глагола «иметь» 3 формы стали получаться хуже.", + "Повтори сегодня 8 форм и 1 слово из своего словаря. Это две минуты." + ], + "button": "Повторить", + "why": [ + "Ждут повторения по расписанию: 5 форм («быть»).", + "Стали получаться хуже: 16 форм.", + "Три недели и дольше без практики: 5 глаголов.", + "В словаре 752 слова: новых за неделю — 3, с ошибками — 14.", + "Это первая игра, поэтому уровень средний.", + "Новое в конце, если игра пройдёт чисто: Новые формы глагола «идти» — я шёл / шла · он идёт · он будет идти." + ], + "seconds": 45, + "warm": [ + { + "item": { + "key": "v:არის:aorist:4", + "kind": "verb", + "ka": "იყავით", + "ru": "вы были", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 4 + }, + "options": [ + { + "ru": "вы были", + "ok": true + }, + { + "ru": "он был", + "ok": false + }, + { + "ru": "вы есть", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:0", + "kind": "verb", + "ka": "ვარ", + "ru": "я есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 0 + }, + "options": [ + { + "ru": "он был", + "ok": false + }, + { + "ru": "они будут", + "ok": false + }, + { + "ru": "я есть", + "ok": true + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:3", + "kind": "verb", + "ka": "ვართ", + "ru": "мы есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 3 + }, + "options": [ + { + "ru": "мы были", + "ok": false + }, + { + "ru": "мы есть", + "ok": true + }, + { + "ru": "я буду", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:aorist:1", + "kind": "verb", + "ka": "იყავი", + "ru": "ты был(а)", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 1 + }, + "options": [ + { + "ru": "я есть", + "ok": false + }, + { + "ru": "ты был(а)", + "ok": true + }, + { + "ru": "я буду", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:2", + "kind": "verb", + "ka": "არის", + "ru": "он есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 2 + }, + "options": [ + { + "ru": "мне надо быть", + "ok": false + }, + { + "ru": "он есть", + "ok": true + }, + { + "ru": "ты был(а)", + "ok": false + } + ], + "due": true + } + ], + "pairs": [ + { + "key": "v:აქვს:future:3", + "kind": "verb", + "ka": "გვექნება", + "ru": "у нас будет", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "future", + "person": 3 + }, + { + "key": "v:აქვს:present:4", + "kind": "verb", + "ka": "გაქვთ", + "ru": "у вас есть", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "present", + "person": 4 + }, + { + "key": "v:აქვს:imperfect:1", + "kind": "verb", + "ka": "გქონდა", + "ru": "у тебя было", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "imperfect", + "person": 1 + }, + { + "key": "w:00000000-0000-4000-8000-000000000002", + "kind": "word", + "ka": "სახრახნისი", + "ru": "отвертка", + "lemma": null, + "verbRu": null, + "tense": null, + "person": null + } + ], + "check": { + "prompt": "Нажми форму, которая значит «у нас будет»", + "intro": "Последнее задание: одна форма из сегодняшней игры.", + "picks": [ + { + "item": { + "key": "v:აქვს:conditional:1", + "kind": "verb", + "ka": "გექნებოდა", + "ru": "у тебя было бы", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "conditional", + "person": 1 + }, + "ok": false, + "message": "«გექნებოდა» (гэкнэбода) — это «у тебя было бы». Нажми другую форму." + }, + { + "item": { + "key": "v:აქვს:future:3", + "kind": "verb", + "ka": "გვექნება", + "ru": "у нас будет", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "future", + "person": 3 + }, + "ok": true, + "message": "Верно: «გვექნება» (гвэкнэба) — у нас будет." + }, + { + "item": { + "key": "v:აქვს:conditional:2", + "kind": "verb", + "ka": "ექნებოდა", + "ru": "у него было бы", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "conditional", + "person": 2 + }, + "ok": false, + "message": "«ექნებოდა» (экнэбода) — это «у него было бы». Нажми другую форму." + } + ] + }, + "next": { + "kind": "forms", + "title": "Новые формы глагола «идти»", + "line": "я шёл / шла · он идёт · он будет идти", + "say": "Игра прошла чисто — можно брать новое. Открой у глагола «идти» 3 новые формы: «я шёл / шла», «он идёт», «он будет идти». Это короткая сессия.", + "button": "Открыть новые формы", + "verbId": "მიდის", + "moduleId": null, + "lessonId": null, + "checkLessons": null + }, + "offer": { + "kind": "forms", + "title": "Новые формы глагола «идти»", + "line": "я шёл / шла · он идёт · он будет идти", + "say": "Игра прошла чисто — можно брать новое. Открой у глагола «идти» 3 новые формы: «я шёл / шла», «он идёт», «он будет идти». Это короткая сессия.", + "button": "Открыть новые формы", + "verbId": "მიდის", + "moduleId": null, + "lessonId": null, + "checkLessons": null + }, + "offerTaken": false, + "result": { + "errors": 0, + "xpEarned": 20, + "streak": 2 + }, + "dev": true +} \ No newline at end of file diff --git a/src/Trale/miniapp-src/e2e/fixtures/daily/errors/after-1-days.json b/src/Trale/miniapp-src/e2e/fixtures/daily/errors/after-1-days.json new file mode 100644 index 00000000..fd3b8c56 --- /dev/null +++ b/src/Trale/miniapp-src/e2e/fixtures/daily/errors/after-1-days.json @@ -0,0 +1,119 @@ +{ + "available": true, + "day": "2026-11-16", + "done": false, + "mode": "review", + "level": 1, + "title": "Закрепляем", + "chat": [ + "Вчера в игре было много ошибок.", + "Сегодня без новых слов и форм: повтори те, где были ошибки. Это две минуты, и в серии будет 3 дня." + ], + "button": "Повторить знакомое", + "why": [ + "Ошибок в прошлой игре: 4.", + "Ждут повторения по расписанию: 1 форма («иметь»).", + "Стали получаться хуже: 16 форм.", + "Три недели и дольше без практики: 5 глаголов.", + "В словаре 752 слова: новых за неделю — 2, с ошибками — 14.", + "Точность последних игр: 71% — уровень 1 из 3.", + "Нового сегодня нет: сначала закрепляем." + ], + "seconds": 60, + "warm": [ + { + "item": { + "key": "v:აქვს:present:0", + "kind": "verb", + "ka": "მაქვს", + "ru": "у меня есть", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "present", + "person": 0 + }, + "options": [ + { + "ru": "у меня есть", + "ok": true + }, + { + "ru": "у меня было бы", + "ok": false + } + ], + "due": true + } + ], + "pairs": [ + { + "key": "v:აქვს:present:4", + "kind": "verb", + "ka": "გაქვთ", + "ru": "у вас есть", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "present", + "person": 4 + }, + { + "key": "v:აქვს:imperfect:1", + "kind": "verb", + "ka": "გქონდა", + "ru": "у тебя было", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "imperfect", + "person": 1 + }, + { + "key": "v:აქვს:future:3", + "kind": "verb", + "ka": "გვექნება", + "ru": "у нас будет", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "future", + "person": 3 + } + ], + "check": { + "prompt": "Нажми форму, которая значит «у вас есть»", + "intro": "Последнее задание: одна форма из сегодняшней игры.", + "picks": [ + { + "item": { + "key": "v:აქვს:conditional:2", + "kind": "verb", + "ka": "ექნებოდა", + "ru": "у него было бы", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "conditional", + "person": 2 + }, + "ok": false, + "message": "«ექნებოდა» (экнэбода) — это «у него было бы». Нажми другую форму." + }, + { + "item": { + "key": "v:აქვს:present:4", + "kind": "verb", + "ka": "გაქვთ", + "ru": "у вас есть", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "present", + "person": 4 + }, + "ok": true, + "message": "Верно: «გაქვთ» (гаквт) — у вас есть." + } + ] + }, + "next": null, + "offer": null, + "offerTaken": false, + "result": null, + "dev": true +} \ No newline at end of file diff --git a/src/Trale/miniapp-src/e2e/fixtures/daily/errors/after-result.json b/src/Trale/miniapp-src/e2e/fixtures/daily/errors/after-result.json new file mode 100644 index 00000000..2db41e24 --- /dev/null +++ b/src/Trale/miniapp-src/e2e/fixtures/daily/errors/after-result.json @@ -0,0 +1,268 @@ +{ + "available": true, + "day": "2026-11-16", + "done": true, + "mode": "mix", + "level": 2, + "title": "Обычный день", + "chat": [ + "У глагола «быть» 5 форм ждут повторения, а у глагола «иметь» 3 формы стали получаться хуже.", + "Повтори сегодня 8 форм и 1 слово из своего словаря. Это две минуты." + ], + "button": "Повторить", + "why": [ + "Ждут повторения по расписанию: 5 форм («быть»).", + "Стали получаться хуже: 16 форм.", + "Три недели и дольше без практики: 5 глаголов.", + "В словаре 752 слова: новых за неделю — 3, с ошибками — 14.", + "Это первая игра, поэтому уровень средний.", + "Новое в конце, если игра пройдёт чисто: Новые формы глагола «идти» — я шёл / шла · он идёт · он будет идти." + ], + "seconds": 45, + "warm": [ + { + "item": { + "key": "v:არის:aorist:4", + "kind": "verb", + "ka": "იყავით", + "ru": "вы были", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 4 + }, + "options": [ + { + "ru": "вы были", + "ok": true + }, + { + "ru": "он был", + "ok": false + }, + { + "ru": "вы есть", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:0", + "kind": "verb", + "ka": "ვარ", + "ru": "я есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 0 + }, + "options": [ + { + "ru": "он был", + "ok": false + }, + { + "ru": "они будут", + "ok": false + }, + { + "ru": "я есть", + "ok": true + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:3", + "kind": "verb", + "ka": "ვართ", + "ru": "мы есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 3 + }, + "options": [ + { + "ru": "мы были", + "ok": false + }, + { + "ru": "мы есть", + "ok": true + }, + { + "ru": "я буду", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:aorist:1", + "kind": "verb", + "ka": "იყავი", + "ru": "ты был(а)", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 1 + }, + "options": [ + { + "ru": "я есть", + "ok": false + }, + { + "ru": "ты был(а)", + "ok": true + }, + { + "ru": "я буду", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:2", + "kind": "verb", + "ka": "არის", + "ru": "он есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 2 + }, + "options": [ + { + "ru": "мне надо быть", + "ok": false + }, + { + "ru": "он есть", + "ok": true + }, + { + "ru": "ты был(а)", + "ok": false + } + ], + "due": true + } + ], + "pairs": [ + { + "key": "v:აქვს:future:3", + "kind": "verb", + "ka": "გვექნება", + "ru": "у нас будет", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "future", + "person": 3 + }, + { + "key": "v:აქვს:present:4", + "kind": "verb", + "ka": "გაქვთ", + "ru": "у вас есть", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "present", + "person": 4 + }, + { + "key": "v:აქვს:imperfect:1", + "kind": "verb", + "ka": "გქონდა", + "ru": "у тебя было", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "imperfect", + "person": 1 + }, + { + "key": "w:00000000-0000-4000-8000-000000000002", + "kind": "word", + "ka": "სახრახნისი", + "ru": "отвертка", + "lemma": null, + "verbRu": null, + "tense": null, + "person": null + } + ], + "check": { + "prompt": "Нажми форму, которая значит «у нас будет»", + "intro": "Последнее задание: одна форма из сегодняшней игры.", + "picks": [ + { + "item": { + "key": "v:აქვს:conditional:1", + "kind": "verb", + "ka": "გექნებოდა", + "ru": "у тебя было бы", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "conditional", + "person": 1 + }, + "ok": false, + "message": "«გექნებოდა» (гэкнэбода) — это «у тебя было бы». Нажми другую форму." + }, + { + "item": { + "key": "v:აქვს:future:3", + "kind": "verb", + "ka": "გვექნება", + "ru": "у нас будет", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "future", + "person": 3 + }, + "ok": true, + "message": "Верно: «გვექნება» (гвэкнэба) — у нас будет." + }, + { + "item": { + "key": "v:აქვს:conditional:2", + "kind": "verb", + "ka": "ექნებოდა", + "ru": "у него было бы", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "conditional", + "person": 2 + }, + "ok": false, + "message": "«ექნებოდა» (экнэбода) — это «у него было бы». Нажми другую форму." + } + ] + }, + "next": { + "kind": "forms", + "title": "Новые формы глагола «идти»", + "line": "я шёл / шла · он идёт · он будет идти", + "say": "Игра прошла чисто — можно брать новое. Открой у глагола «идти» 3 новые формы: «я шёл / шла», «он идёт», «он будет идти». Это короткая сессия.", + "button": "Открыть новые формы", + "verbId": "მიდის", + "moduleId": null, + "lessonId": null, + "checkLessons": null + }, + "offer": null, + "offerTaken": false, + "result": { + "errors": 4, + "xpEarned": 20, + "streak": 2 + }, + "dev": true +} \ No newline at end of file diff --git a/src/Trale/miniapp-src/e2e/fixtures/daily/errors/today.json b/src/Trale/miniapp-src/e2e/fixtures/daily/errors/today.json new file mode 100644 index 00000000..9ff58157 --- /dev/null +++ b/src/Trale/miniapp-src/e2e/fixtures/daily/errors/today.json @@ -0,0 +1,264 @@ +{ + "available": true, + "day": "2026-11-16", + "done": false, + "mode": "mix", + "level": 2, + "title": "Обычный день", + "chat": [ + "У глагола «быть» 5 форм ждут повторения, а у глагола «иметь» 3 формы стали получаться хуже.", + "Повтори сегодня 8 форм и 1 слово из своего словаря. Это две минуты." + ], + "button": "Повторить", + "why": [ + "Ждут повторения по расписанию: 5 форм («быть»).", + "Стали получаться хуже: 16 форм.", + "Три недели и дольше без практики: 5 глаголов.", + "В словаре 752 слова: новых за неделю — 3, с ошибками — 14.", + "Это первая игра, поэтому уровень средний.", + "Новое в конце, если игра пройдёт чисто: Новые формы глагола «идти» — я шёл / шла · он идёт · он будет идти." + ], + "seconds": 45, + "warm": [ + { + "item": { + "key": "v:არის:aorist:4", + "kind": "verb", + "ka": "იყავით", + "ru": "вы были", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 4 + }, + "options": [ + { + "ru": "вы были", + "ok": true + }, + { + "ru": "он был", + "ok": false + }, + { + "ru": "вы есть", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:0", + "kind": "verb", + "ka": "ვარ", + "ru": "я есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 0 + }, + "options": [ + { + "ru": "он был", + "ok": false + }, + { + "ru": "они будут", + "ok": false + }, + { + "ru": "я есть", + "ok": true + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:3", + "kind": "verb", + "ka": "ვართ", + "ru": "мы есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 3 + }, + "options": [ + { + "ru": "мы были", + "ok": false + }, + { + "ru": "мы есть", + "ok": true + }, + { + "ru": "я буду", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:aorist:1", + "kind": "verb", + "ka": "იყავი", + "ru": "ты был(а)", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 1 + }, + "options": [ + { + "ru": "я есть", + "ok": false + }, + { + "ru": "ты был(а)", + "ok": true + }, + { + "ru": "я буду", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:2", + "kind": "verb", + "ka": "არის", + "ru": "он есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 2 + }, + "options": [ + { + "ru": "мне надо быть", + "ok": false + }, + { + "ru": "он есть", + "ok": true + }, + { + "ru": "ты был(а)", + "ok": false + } + ], + "due": true + } + ], + "pairs": [ + { + "key": "v:აქვს:future:3", + "kind": "verb", + "ka": "გვექნება", + "ru": "у нас будет", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "future", + "person": 3 + }, + { + "key": "v:აქვს:present:4", + "kind": "verb", + "ka": "გაქვთ", + "ru": "у вас есть", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "present", + "person": 4 + }, + { + "key": "v:აქვს:imperfect:1", + "kind": "verb", + "ka": "გქონდა", + "ru": "у тебя было", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "imperfect", + "person": 1 + }, + { + "key": "w:00000000-0000-4000-8000-000000000002", + "kind": "word", + "ka": "სახრახნისი", + "ru": "отвертка", + "lemma": null, + "verbRu": null, + "tense": null, + "person": null + } + ], + "check": { + "prompt": "Нажми форму, которая значит «у нас будет»", + "intro": "Последнее задание: одна форма из сегодняшней игры.", + "picks": [ + { + "item": { + "key": "v:აქვს:conditional:1", + "kind": "verb", + "ka": "გექნებოდა", + "ru": "у тебя было бы", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "conditional", + "person": 1 + }, + "ok": false, + "message": "«გექნებოდა» (гэкнэбода) — это «у тебя было бы». Нажми другую форму." + }, + { + "item": { + "key": "v:აქვს:future:3", + "kind": "verb", + "ka": "გვექნება", + "ru": "у нас будет", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "future", + "person": 3 + }, + "ok": true, + "message": "Верно: «გვექნება» (гвэкнэба) — у нас будет." + }, + { + "item": { + "key": "v:აქვს:conditional:2", + "kind": "verb", + "ka": "ექნებოდა", + "ru": "у него было бы", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "conditional", + "person": 2 + }, + "ok": false, + "message": "«ექნებოდა» (экнэбода) — это «у него было бы». Нажми другую форму." + } + ] + }, + "next": { + "kind": "forms", + "title": "Новые формы глагола «идти»", + "line": "я шёл / шла · он идёт · он будет идти", + "say": "Игра прошла чисто — можно брать новое. Открой у глагола «идти» 3 новые формы: «я шёл / шла», «он идёт», «он будет идти». Это короткая сессия.", + "button": "Открыть новые формы", + "verbId": "მიდის", + "moduleId": null, + "lessonId": null, + "checkLessons": null + }, + "offer": null, + "offerTaken": false, + "result": null, + "dev": true +} \ No newline at end of file diff --git a/src/Trale/miniapp-src/e2e/fixtures/daily/today.json b/src/Trale/miniapp-src/e2e/fixtures/daily/today.json new file mode 100644 index 00000000..9ff58157 --- /dev/null +++ b/src/Trale/miniapp-src/e2e/fixtures/daily/today.json @@ -0,0 +1,264 @@ +{ + "available": true, + "day": "2026-11-16", + "done": false, + "mode": "mix", + "level": 2, + "title": "Обычный день", + "chat": [ + "У глагола «быть» 5 форм ждут повторения, а у глагола «иметь» 3 формы стали получаться хуже.", + "Повтори сегодня 8 форм и 1 слово из своего словаря. Это две минуты." + ], + "button": "Повторить", + "why": [ + "Ждут повторения по расписанию: 5 форм («быть»).", + "Стали получаться хуже: 16 форм.", + "Три недели и дольше без практики: 5 глаголов.", + "В словаре 752 слова: новых за неделю — 3, с ошибками — 14.", + "Это первая игра, поэтому уровень средний.", + "Новое в конце, если игра пройдёт чисто: Новые формы глагола «идти» — я шёл / шла · он идёт · он будет идти." + ], + "seconds": 45, + "warm": [ + { + "item": { + "key": "v:არის:aorist:4", + "kind": "verb", + "ka": "იყავით", + "ru": "вы были", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 4 + }, + "options": [ + { + "ru": "вы были", + "ok": true + }, + { + "ru": "он был", + "ok": false + }, + { + "ru": "вы есть", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:0", + "kind": "verb", + "ka": "ვარ", + "ru": "я есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 0 + }, + "options": [ + { + "ru": "он был", + "ok": false + }, + { + "ru": "они будут", + "ok": false + }, + { + "ru": "я есть", + "ok": true + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:3", + "kind": "verb", + "ka": "ვართ", + "ru": "мы есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 3 + }, + "options": [ + { + "ru": "мы были", + "ok": false + }, + { + "ru": "мы есть", + "ok": true + }, + { + "ru": "я буду", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:aorist:1", + "kind": "verb", + "ka": "იყავი", + "ru": "ты был(а)", + "lemma": "არის", + "verbRu": "быть", + "tense": "aorist", + "person": 1 + }, + "options": [ + { + "ru": "я есть", + "ok": false + }, + { + "ru": "ты был(а)", + "ok": true + }, + { + "ru": "я буду", + "ok": false + } + ], + "due": true + }, + { + "item": { + "key": "v:არის:present:2", + "kind": "verb", + "ka": "არის", + "ru": "он есть", + "lemma": "არის", + "verbRu": "быть", + "tense": "present", + "person": 2 + }, + "options": [ + { + "ru": "мне надо быть", + "ok": false + }, + { + "ru": "он есть", + "ok": true + }, + { + "ru": "ты был(а)", + "ok": false + } + ], + "due": true + } + ], + "pairs": [ + { + "key": "v:აქვს:future:3", + "kind": "verb", + "ka": "გვექნება", + "ru": "у нас будет", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "future", + "person": 3 + }, + { + "key": "v:აქვს:present:4", + "kind": "verb", + "ka": "გაქვთ", + "ru": "у вас есть", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "present", + "person": 4 + }, + { + "key": "v:აქვს:imperfect:1", + "kind": "verb", + "ka": "გქონდა", + "ru": "у тебя было", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "imperfect", + "person": 1 + }, + { + "key": "w:00000000-0000-4000-8000-000000000002", + "kind": "word", + "ka": "სახრახნისი", + "ru": "отвертка", + "lemma": null, + "verbRu": null, + "tense": null, + "person": null + } + ], + "check": { + "prompt": "Нажми форму, которая значит «у нас будет»", + "intro": "Последнее задание: одна форма из сегодняшней игры.", + "picks": [ + { + "item": { + "key": "v:აქვს:conditional:1", + "kind": "verb", + "ka": "გექნებოდა", + "ru": "у тебя было бы", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "conditional", + "person": 1 + }, + "ok": false, + "message": "«გექნებოდა» (гэкнэбода) — это «у тебя было бы». Нажми другую форму." + }, + { + "item": { + "key": "v:აქვს:future:3", + "kind": "verb", + "ka": "გვექნება", + "ru": "у нас будет", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "future", + "person": 3 + }, + "ok": true, + "message": "Верно: «გვექნება» (гвэкнэба) — у нас будет." + }, + { + "item": { + "key": "v:აქვს:conditional:2", + "kind": "verb", + "ka": "ექნებოდა", + "ru": "у него было бы", + "lemma": "აქვს", + "verbRu": "иметь", + "tense": "conditional", + "person": 2 + }, + "ok": false, + "message": "«ექნებოდა» (экнэбода) — это «у него было бы». Нажми другую форму." + } + ] + }, + "next": { + "kind": "forms", + "title": "Новые формы глагола «идти»", + "line": "я шёл / шла · он идёт · он будет идти", + "say": "Игра прошла чисто — можно брать новое. Открой у глагола «идти» 3 новые формы: «я шёл / шла», «он идёт», «он будет идти». Это короткая сессия.", + "button": "Открыть новые формы", + "verbId": "მიდის", + "moduleId": null, + "lessonId": null, + "checkLessons": null + }, + "offer": null, + "offerTaken": false, + "result": null, + "dev": true +} \ No newline at end of file diff --git a/src/Trale/miniapp-src/src/App.tsx b/src/Trale/miniapp-src/src/App.tsx index efd7d4aa..6cf1fc6d 100644 --- a/src/Trale/miniapp-src/src/App.tsx +++ b/src/Trale/miniapp-src/src/App.tsx @@ -26,6 +26,7 @@ import ProPaywall from './components/ProPaywall' import VerbSheet from './verbs/VerbSheet' import { resolveVerbDeepLink } from './verbs/deepLink' import { closeTopOverlay, useHasOverlay } from './verbs/ui/overlayStack' +import DailyTask from './daily/DailyTask' import { loadSeenHints } from './verbs/ui/hints' import VerbsSection from './screens/VerbsSection' import FeedbackScreen from './screens/FeedbackScreen' @@ -83,6 +84,8 @@ function parseDeepLink(catalog: CatalogDto): Screen | null { if (target === 'feed') return { kind: 'dashboard' } // Bombora is fed on the dashboard if (target === 'vocabulary') return { kind: 'vocabulary-list' } + // ?screen=daily — кнопка сообщения бота о задании дня. + if (target === 'daily') return { kind: 'daily' } if (moduleId) { const mod = catalog.modules.find((m) => m.id === moduleId) if (!mod) return null @@ -279,7 +282,8 @@ export default function App() { screen.kind === 'module' || screen.kind === 'profile' || screen.kind === 'vocabulary-list' || - screen.kind === 'verbs' + screen.kind === 'verbs' || + screen.kind === 'daily' ) { setScreen({ kind: 'dashboard' }) } else if (screen.kind === 'feedback') { @@ -629,6 +633,8 @@ export default function App() { )} ) + case 'daily': + return case 'verbs': return ( <> diff --git a/src/Trale/miniapp-src/src/api.ts b/src/Trale/miniapp-src/src/api.ts index e09dbbe6..b8f124e6 100644 --- a/src/Trale/miniapp-src/src/api.ts +++ b/src/Trale/miniapp-src/src/api.ts @@ -534,6 +534,32 @@ export function fetchVerbSection() { return request('/api/miniapp/verbs/section') } +// ── «Задание дня» ──────────────────────────────────────────────────────────── +/** Занятие на сегодня. Без доступа сервер отвечает 402 — карточки на главной тогда нет. */ +export function fetchDailyTask() { + return request('/api/miniapp/daily-task') +} + +/** Итог занятия. Принимается один раз за день; повтор возвращает уже сохранённое. */ +export function saveDailyResult(report: import('./daily/types').DailyReportDto) { + return request('/api/miniapp/daily-task/result', { method: 'POST', body: JSON.stringify(report) }) +} + +/** «Новое» после занятия: открыли (формы, урок) или чем закончилась минутная проверка. */ +export function reportDailyOffer(report: import('./daily/types').DailyOfferReportDto) { + return request<{ task: import('./daily/types').DailyTaskDto }>('/api/miniapp/daily-task/offer', { method: 'POST', body: JSON.stringify(report) }) +} + +/** Только на стенде: перемотать дни вперёд и получить занятие нового дня. */ +export function devNextDay(days: number) { + return request<{ task: import('./daily/types').DailyTaskDto }>('/api/miniapp/daily-task/dev/next-day', { method: 'POST', body: JSON.stringify({ days }) }) +} + +/** Только на стенде: прислать сообщение бота о задании дня. */ +export function devDailyPush() { + return request<{ ok: boolean }>('/api/miniapp/daily-task/dev/push', { method: 'POST' }) +} + /** Раздел открыли: плиткой с главной (home), кнопкой рассылки (имя кампании) или по ссылке с меткой. */ export function reportVerbSectionOpen(source: string) { return request<{ ok: boolean }>('/api/miniapp/verbs/section/open', { method: 'POST', body: JSON.stringify({ source }) }) diff --git a/src/Trale/miniapp-src/src/daily/DailyCard.tsx b/src/Trale/miniapp-src/src/daily/DailyCard.tsx new file mode 100644 index 00000000..0ec4825b --- /dev/null +++ b/src/Trale/miniapp-src/src/daily/DailyCard.tsx @@ -0,0 +1,86 @@ +import React, { useEffect, useState } from 'react' +import { devDailyPush, devNextDay } from '../api' +import type { Screen } from '../types' +import { cardLine, streakLine } from './logic' +import { cachedDaily, loadDaily, onDaily, setDaily } from './store' +import type { DailyTaskDto } from './types' + +/** Значок задания: листок календаря с галочкой — рисуем сами, без эмодзи. */ +const DayIcon = ({ done }: { done: boolean }) => ( + +) + +/** + * Первая карточка главной: задание на сегодня, потом — «новое» после него, потом — «сделано». + * Без доступа и без материала для задания карточки нет. + */ +export default function DailyCard({ navigate }: { navigate: (s: Screen) => void }) { + const [task, setTask] = useState(cachedDaily) + const [devNote, setDevNote] = useState(null) + + useEffect(() => { + loadDaily().catch(() => {}) + return onDaily(setTask) + }, []) + + if (!task) return null + + const offer = task.done && task.offer && !task.offerTaken ? task.offer : null + const finished = task.done && !offer + const eyebrow = !task.done ? 'Задание дня' : offer ? 'Задание дня · сделано' : 'Задание дня' + const title = !task.done ? task.title : offer ? offer.title : 'Сделано сегодня' + const line = !task.done ? cardLine(task) : offer ? offer.line : `${streakLine(task.result?.streak ?? 0)}. Завтра будет новое.` + + async function dev(action: () => Promise<{ task?: DailyTaskDto; ok?: boolean }>, note: string) { + setDevNote('…') + try { + const r = await action() + if (r.task) setDaily(r.task.available ? r.task : null) + setDevNote(r.ok === false ? 'задание уже сделано — сообщения нет' : note) + } catch { + setDevNote('не получилось') + } + } + + return ( + <> + + {task.dev && ( +
+ стенд: + + · + + · + + {devNote && {devNote}} +
+ )} + + ) +} diff --git a/src/Trale/miniapp-src/src/daily/DailyTask.tsx b/src/Trale/miniapp-src/src/daily/DailyTask.tsx new file mode 100644 index 00000000..19e60a8c --- /dev/null +++ b/src/Trale/miniapp-src/src/daily/DailyTask.tsx @@ -0,0 +1,318 @@ +import React, { useEffect, useRef, useState } from 'react' +import Button from '../components/Button' +import LoaderLetter from '../components/LoaderLetter' +import { api, reportDailyOffer, saveDailyResult, type ProgressDto } from '../api' +import { publishProgress } from '../progress' +import type { Screen } from '../types' +import PlaySession from '../verbs/section/PlaySession' +import { bad, good } from '../verbs/ui/juice' +import { cyr } from '../verbs/types' +import { + buildReport, emptyRun, finaleTitle, flowOf, georgianWords, hasGeorgian, minuteQuestions, plural, streakLine, + type DailyRun, type MinuteQuestion +} from './logic' +import { Check, Intro, PairsGame, Warm } from './steps' +import { cachedDaily, loadDaily, setDaily } from './store' +import { DailyHeader, Geo, LinkButton, Page, Say, StepTitle } from './ui' +import type { DailyNew, DailyTaskDto } from './types' + +// Экран «Задания дня»: вступление → разминка → пары → проверка → итог с «новым». +// Если задание уже сделано, экран сразу открывается итогом: так туда ведёт и карточка на главной. + +type Stage = + | { kind: 'intro' } + | { kind: 'step'; at: number } + | { kind: 'saving' } + | { kind: 'save-failed' } + | { kind: 'finale' } + | { kind: 'minute' } + +export default function DailyTask({ navigate }: { navigate: (s: Screen) => void }) { + const [task, setTask] = useState(cachedDaily) + const [loading, setLoading] = useState(!cachedDaily()) + const [stage, setStage] = useState(() => (cachedDaily()?.done ? { kind: 'finale' } : { kind: 'intro' })) + const [verb, setVerb] = useState(null) + const run = useRef(emptyRun()) + const home = () => navigate({ kind: 'dashboard' }) + + useEffect(() => { + let alive = true + loadDaily() + .then(t => { + if (!alive) return + setTask(t) + if (t?.done) setStage({ kind: 'finale' }) + }) + .catch(() => {}) + .finally(() => alive && setLoading(false)) + return () => { alive = false } + }, []) + + if (loading && !task) { + return
+ } + if (!task) { + return ( + + +
+ Пока не из чего собрать задание: пройди урок или открой глагол — и завтра оно появится. +
+
+
+ ) + } + + const flow = flowOf(task) + + async function save() { + setStage({ kind: 'saving' }) + try { + const saved = await saveDailyResult(buildReport(task!, run.current)) + if (saved.progress) publishProgress(saved.progress as unknown as ProgressDto) + setDaily(saved.task) + setTask(saved.task) + setStage({ kind: 'finale' }) + } catch { + setStage({ kind: 'save-failed' }) + } + } + + function next(at: number) { + if (at + 1 < flow.length) setStage({ kind: 'step', at: at + 1 }) + else save() + } + + async function takeOffer(offer: DailyNew) { + if (offer.kind === 'check') return setStage({ kind: 'minute' }) + // Отметку о взятом «новом» не ждём дольше секунды: человек нажал — сразу открываем. + await Promise.race([ + reportDailyOffer({ day: task!.day, outcome: 'opened' }).then(r => setDaily(r.task)).catch(() => {}), + new Promise(r => setTimeout(r, 1000)) + ]) + if (offer.kind === 'forms' && offer.verbId) setVerb(offer.verbId) + else if (offer.kind === 'lesson' && offer.moduleId && offer.lessonId) { + navigate({ kind: 'lesson-theory', moduleId: offer.moduleId, lessonId: offer.lessonId }) + } + } + + if (verb) return + + switch (stage.kind) { + case 'intro': + return { run.current = emptyRun(); setStage({ kind: 'step', at: 0 }) }} /> + + case 'step': { + const head = { steps: flow.length, at: stage.at + 1, onExit: home } + const step = flow[stage.at] + if (step === 'warm') { + return { run.current = { ...run.current, warmWrong: wrong }; next(stage.at) }} /> + } + if (step === 'game') { + return ( + { + run.current = { ...run.current, errors: run.current.errors + r.errors, pairWrong: [...new Set([...run.current.pairWrong, ...r.wrong])], seconds: r.seconds } + next(stage.at) + }} + /> + ) + } + return { run.current = { ...run.current, checkErrors: errors }; next(stage.at) }} /> + } + + case 'saving': + case 'save-failed': + return ( + + +
+ {stage.kind === 'saving' ? : ( + Связь пропала, итог не отправился. Он не потерян: нажми «Отправить ещё раз». + )} +
+ {stage.kind === 'save-failed' &&
} +
+ ) + + case 'minute': + return task.offer?.kind === 'check' + ? { setDaily(t); setTask(t); setStage({ kind: 'finale' }) }} onExit={home} /> + : null + + case 'finale': + return + } +} + +// ── Итог ───────────────────────────────────────────────────────────────────── + +function Finale({ task, onOffer, onHome }: { task: DailyTaskDto; onOffer: (o: DailyNew) => void; onHome: () => void }) { + const result = task.result + const errors = result?.errors ?? 0 + const offer = task.offer && !task.offerTaken ? task.offer : null + const say = offer ? offer.say + : task.offer && task.offerTaken ? 'На сегодня всё. Завтра будет новое задание.' + : task.mode === 'review' ? 'Знакомое закреплено. Завтра, если игра пройдёт чисто, возьмём новое.' + : errors > 1 ? `Нового сегодня нет: в игре ${errors} ${plural(errors, 'ошибка', 'ошибки', 'ошибок')}. Завтра повторим эти формы ещё раз.` + : 'На сегодня всё. Завтра будет новое задание.' + + return ( + + + {finaleTitle(task.mode, errors)} +
+
+
{result?.streak ?? 0}
+
{streakLine(result?.streak ?? 0)}
+
+
+
+{result?.xpEarned ?? 0}
+
опыта
+
+
+
+ {errors === 0 ? 'Игра без ошибок' : `В игре ${errors} ${plural(errors, 'ошибка', 'ошибки', 'ошибок')}`} +
+
+ {offer && ( +
+
+
Новое
+
{offer.title}
+
{offer.line}
+
+
+ )} + {say} +
+ {offer ? ( + <> + + На главную + + ) : ( + + )} +
+ + ) +} + +// ── Минутная проверка модуля ───────────────────────────────────────────────── + +/** По вопросу из каждого пропущенного урока; модуль закрыт, только если все ответы верные. */ +function MinuteCheck({ task, offer, onDone, onExit }: { + task: DailyTaskDto; offer: DailyNew; onDone: (t: DailyTaskDto) => void; onExit: () => void +}) { + const [questions, setQuestions] = useState(null) + const [failed, setFailed] = useState(false) + const [i, setI] = useState(0) + const [picked, setPicked] = useState(null) + const [errors, setErrors] = useState(0) + const [outcome, setOutcome] = useState<'passed' | 'failed' | null>(null) + const [sending, setSending] = useState(false) + const [updated, setUpdated] = useState(null) + + useEffect(() => { + const lessons = offer.checkLessons ?? [] + Promise.all(lessons.map(lessonId => + api.lessonQuestions(offer.moduleId!, lessonId).then(qs => ({ lessonId, questions: qs as any[] })).catch(() => ({ lessonId, questions: [] })))) + .then(byLesson => setQuestions(minuteQuestions(byLesson, task.day))) + .catch(() => setFailed(true)) + }, []) // eslint-disable-line react-hooks/exhaustive-deps + + async function finish(result: 'passed' | 'failed') { + setOutcome(result) + setSending(true) + try { + const r = await reportDailyOffer({ day: task.day, outcome: result }) + setUpdated(r.task) + } catch { + // Не отправилось — проверку предложат снова; человек ничего не теряет. + } finally { + setSending(false) + } + } + + if (failed || (questions && questions.length === 0)) { + return ( + + +
Не получилось загрузить вопросы. Попробуй позже.
+
+
+ ) + } + if (!questions) { + return
+ } + + if (outcome) { + const passed = outcome === 'passed' + return ( + + + {passed ? 'Модуль закрыт' : 'Есть пробелы'} +
+ + {passed + ? `Все ${questions.length} ${plural(questions.length, 'ответ', 'ответа', 'ответов')} верные: пропущенные уроки модуля «${offer.title}» тебе не нужны. Дальше пойдём по курсу.` + : `${errors} ${plural(errors, 'ошибка', 'ошибки', 'ошибок')} из ${questions.length}. Пропущенные уроки пригодятся: со следующего дня будем проходить их по одному.`} + +
+
+ +
+
+ ) + } + + const q = questions[i] + const words = georgianWords(q.question) + function pick(at: number, el: Element) { + if (picked !== null) return + setPicked(at) + if (at === q.answerIndex) good(el) + else { bad(); setErrors(e => e + 1) } + } + function onward() { + if (i + 1 < questions!.length) { setI(i + 1); setPicked(null) } + else finish(errors === 0 ? 'passed' : 'failed') + } + + return ( + + + {q.question} + {words.length > 0 && ( +
+ {words.map(w => `${w} — ${cyr(w)}`).join(' · ')} +
+ )} +
+
+ {q.options.map((o, at) => { + const tone = picked === null ? 'bg-cream-tile' + : at === q.answerIndex ? 'bg-navy-wash' + : at === picked ? 'bg-ruby-wash anim-shake' : 'bg-cream-tile opacity-50' + return ( + + ) + })} +
+
+ +
+ + ) +} + diff --git a/src/Trale/miniapp-src/src/daily/logic.ts b/src/Trale/miniapp-src/src/daily/logic.ts new file mode 100644 index 00000000..808a8ede --- /dev/null +++ b/src/Trale/miniapp-src/src/daily/logic.ts @@ -0,0 +1,241 @@ +import type { ProgressState } from '../types' +import type { DailyItem, DailyReportDto, DailyTaskDto } from './types' + +// Правила «Задания дня» без экрана: порядок шагов, игра в пары, итог для сервера, вопросы минутной проверки. +// Что именно повторять и насколько сложно — решает сервер; здесь только то, как это проводится. + +export function plural(n: number, one: string, few: string, many: string): string { + const mod100 = n % 100 + const mod10 = n % 10 + if (mod100 >= 11 && mod100 <= 14) return many + if (mod10 === 1) return one + if (mod10 >= 2 && mod10 <= 4) return few + return many +} + +export const days = (n: number) => `${n} ${plural(n, 'день', 'дня', 'дней')}` + +/** «4 формы и 1 слово» — из чего собрана игра. */ +export function formsAndWords(items: DailyItem[]): string { + const forms = items.filter(i => i.kind === 'verb').length + const words = items.length - forms + const parts: string[] = [] + if (forms) parts.push(`${forms} ${plural(forms, 'форма', 'формы', 'форм')}`) + if (words) parts.push(`${words} ${plural(words, 'слово', 'слова', 'слов')}`) + return parts.join(' и ') +} + +/** Строка карточки на главной: последняя реплика тренера, а без неё — из чего собрана игра. */ +export function cardLine(task: DailyTaskDto): string { + const said = [...task.chat].reverse().find(line => line.trim()) + if (said) return said.trim() + return `${formsAndWords(task.pairs)} · ${task.mode === 'comeback' ? 'одна минута' : 'две минуты'}` +} + +export type DailyStep = 'warm' | 'game' | 'check' + +/** Шаги занятия по порядку; разминки может не быть. */ +export const flowOf = (task: DailyTaskDto): DailyStep[] => [...(task.warm.length ? ['warm' as const] : []), 'game', 'check'] + +/** Строка с выделением: «важное и обычное» → куски для отрисовки без вставки разметки. */ +export function boldParts(line: string): { text: string; bold: boolean }[] { + const parts: { text: string; bold: boolean }[] = [] + const tag = /(.*?)<\/b>/gs + let at = 0 + for (const m of line.matchAll(tag)) { + if (m.index! > at) parts.push({ text: line.slice(at, m.index), bold: false }) + if (m[1]) parts.push({ text: m[1], bold: true }) + at = m.index! + m[0].length + } + if (at < line.length) parts.push({ text: line.slice(at), bold: false }) + // Любую другую разметку показываем как текст без угловых скобок тегов. + return parts.map(p => ({ ...p, text: p.text.replace(/<\/?[a-z][^>]*>/gi, '') })).filter(p => p.text) +} + +export function clock(ms: number): string { + const s = Math.ceil(ms / 1000) + return `${Math.floor(s / 60)}:${s % 60 < 10 ? '0' : ''}${s % 60}` +} + +export function shuffle(xs: readonly T[], rng: () => number = Math.random): T[] { + const out = [...xs] + for (let i = out.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)) + ;[out[i], out[j]] = [out[j], out[i]] + } + return out +} + +/** Есть ли в строке грузинские буквы — такой вариант показываем с транскрипцией. */ +export const hasGeorgian = (s: string) => /[ა-ჿ]/.test(s) + +/** Грузинские слова строки — чтобы подписать под вопросом, как они читаются. */ +export const georgianWords = (s: string) => s.match(/[ა-ჿ]+(?:[ -][ა-ჿ]+)*/g) ?? [] + +// ── Игра «Собери пары» ─────────────────────────────────────────────────────── + +export type Side = 'l' | 'r' + +export interface PairsState { + /** Порядок плиток в столбцах: слева грузинское, справа перевод. В ячейках — номера пар. */ + left: number[] + right: number[] + sel: { side: Side; i: number } | null + /** Только что нажатая неверная пара — трясётся. */ + bad: { l: number; r: number } | null + matchedL: number[] + matchedR: number[] + /** Время идёт с первого нажатия. */ + started: boolean + /** Время вышло. */ + over: boolean + /** Неверные попытки этой партии. */ + errors: number + /** Ключи форм, на которых ошиблись. */ + wrong: string[] +} + +export type PairsEvent = 'select' | 'match' | 'miss' | 'done' | null + +export function newPairs(count: number, rng: () => number = Math.random): PairsState { + const idx = Array.from({ length: count }, (_, i) => i) + return { left: shuffle(idx, rng), right: shuffle(idx, rng), sel: null, bad: null, matchedL: [], matchedR: [], started: false, over: false, errors: 0, wrong: [] } +} + +/** Одинаковый перевод у двух форм — обе плитки верные: человека не наказываем за то, чего не различить. */ +const fits = (pairs: DailyItem[], l: number, r: number) => l === r || pairs[l].ru === pairs[r].ru + +export const allMatched = (s: PairsState, pairs: DailyItem[]) => s.matchedL.length === pairs.length + +/** Нажатие на плитку: сначала выбор, потом пара к выбранному. */ +export function tapPair(s: PairsState, side: Side, i: number, pairs: DailyItem[]): { state: PairsState; event: PairsEvent } { + const taken = side === 'l' ? s.matchedL : s.matchedR + if (s.over || taken.includes(i) || allMatched(s, pairs)) return { state: s, event: null } + const base = { ...s, started: true, bad: null } + if (!s.sel || s.sel.side === side) { + const same = s.sel?.side === side && s.sel.i === i + return { state: { ...base, sel: same ? null : { side, i } }, event: 'select' } + } + const l = side === 'l' ? i : s.sel.i + const r = side === 'r' ? i : s.sel.i + if (fits(pairs, l, r)) { + const next = { ...base, sel: null, matchedL: [...s.matchedL, l], matchedR: [...s.matchedR, r] } + return { state: next, event: allMatched(next, pairs) ? 'done' : 'match' } + } + const wrong = [...new Set([...s.wrong, pairs[l].key, pairs[r].key])] + return { state: { ...base, sel: null, bad: { l, r }, errors: s.errors + 1, wrong }, event: 'miss' } +} + +/** Время вышло: несобранные пары считаются ошибками — сервер иначе решит, что эти формы получились. */ +export function timeOut(s: PairsState, pairs: DailyItem[]): PairsState { + if (s.over || allMatched(s, pairs)) return s + const missed = pairs.filter((_, i) => !s.matchedL.includes(i)).map(p => p.key) + return { ...s, over: true, sel: null, bad: null, errors: s.errors + missed.length, wrong: [...new Set([...s.wrong, ...missed])] } +} + +/** Что сказать под игрой прямо сейчас. */ +export function pairsHint(s: PairsState, pairs: DailyItem[]): string { + if (allMatched(s, pairs)) return 'Все пары собраны.' + if (!s.started) return 'Нажми форму, потом её перевод. Время пойдёт с первого нажатия.' + if (s.sel?.side === 'l') return 'Теперь нажми её перевод.' + if (s.sel) return `Теперь нажми грузинскую форму для «${pairs[s.sel.i].ru}».` + return 'Нажми форму, потом её перевод.' +} + +// ── Итог ───────────────────────────────────────────────────────────────────── + +/** Что накопилось за занятие. */ +export interface DailyRun { + warmWrong: string[] + pairWrong: string[] + /** Все неверные попытки в парах, включая несобранные из-за времени, по всем партиям. */ + errors: number + checkErrors: number + /** За сколько секунд собрана игра (последняя партия). */ + seconds: number +} + +export const emptyRun = (): DailyRun => ({ warmWrong: [], pairWrong: [], errors: 0, checkErrors: 0, seconds: 0 }) + +/** Партия закончилась (собрана или вышло время) — её ошибки добавляются к занятию. */ +export function addGame(run: DailyRun, game: PairsState, seconds: number): DailyRun { + return { ...run, errors: run.errors + game.errors, pairWrong: [...new Set([...run.pairWrong, ...game.wrong])], seconds } +} + +export const buildReport = (task: DailyTaskDto, run: DailyRun): DailyReportDto => ({ + day: task.day, warmWrong: run.warmWrong, pairWrong: run.pairWrong, errors: run.errors, checkErrors: run.checkErrors, seconds: run.seconds +}) + +/** Все ошибки занятия — для строки итога. */ +export const totalErrors = (run: DailyRun) => run.errors + run.checkErrors + run.warmWrong.length + +/** «4 пары за 31 секунду, без ошибок». */ +export function statLine(pairs: number, run: DailyRun): string { + const errors = totalErrors(run) + const time = run.seconds > 0 ? ` за ${run.seconds} ${plural(run.seconds, 'секунду', 'секунды', 'секунд')}` : '' + return `${pairs} ${plural(pairs, 'пара', 'пары', 'пар')}${time}, ${errors === 0 ? 'без ошибок' : `${errors} ${plural(errors, 'ошибка', 'ошибки', 'ошибок')}`}` +} + +/** Заголовок итога — по тому, какой был день и как он прошёл. */ +export function finaleTitle(mode: DailyTaskDto['mode'], errors: number): string { + if (mode === 'review') return errors <= 1 ? 'Знакомое помнишь' : 'День закрыт' + if (mode === 'comeback') return 'С возвращением' + return errors === 0 ? 'Всё помнишь' : 'Готово, день закрыт' +} + +export const streakLine = (streak: number) => (streak <= 1 ? 'Серия началась' : `${days(streak)} подряд`) + +/** Прогресс в ответе сервера: в виде мини-аппа или в виде API (lastPlayedAtUtc) — принимаем оба. */ +export function progressPatch(progress: unknown): Partial | null { + if (!progress || typeof progress !== 'object') return null + const p = progress as Record + const patch: Partial = {} + if (typeof p.xp === 'number') patch.xp = p.xp + if (typeof p.streak === 'number') patch.streak = p.streak + if (p.completedLessons && typeof p.completedLessons === 'object') patch.completedLessons = p.completedLessons + if (typeof p.lastPlayedDate === 'string') patch.lastPlayedDate = p.lastPlayedDate + else if (typeof p.lastPlayedAtUtc === 'string') patch.lastPlayedDate = p.lastPlayedAtUtc.slice(0, 10) + if (typeof p.xpSpent === 'number') patch.xpSpent = p.xpSpent + if (typeof p.totalTreatsGiven === 'number') patch.totalTreatsGiven = p.totalTreatsGiven + if ('lastFedAtUtc' in p) patch.lastFedAtUtc = p.lastFedAtUtc ?? null + if ('lastTreatIndex' in p) patch.lastTreatIndex = p.lastTreatIndex ?? null + return patch +} + +// ── Минутная проверка ──────────────────────────────────────────────────────── + +export const MINUTE_MAX = 6 + +export interface LessonQuestion { + id: string + question: string + options: string[] + answerIndex: number + questionType?: string +} + +export interface MinuteQuestion extends LessonQuestion { lessonId: number } + +/** Какие уроки спросить: не больше шести, равномерно по списку пропущенных. */ +export function minuteLessons(lessons: number[], max = MINUTE_MAX): number[] { + if (lessons.length <= max) return [...lessons] + return Array.from({ length: max }, (_, i) => lessons[Math.round((i * (lessons.length - 1)) / (max - 1))]) +} + +const isChoice = (q: LessonQuestion) => + (!q.questionType || q.questionType === 'choice') && Array.isArray(q.options) && q.options.length >= 2 && + Number.isInteger(q.answerIndex) && q.answerIndex >= 0 && q.answerIndex < q.options.length + +/** По одному вопросу с выбором ответа из каждого урока; какой именно — зависит от дня, а не от случая. */ +export function minuteQuestions(byLesson: { lessonId: number; questions: LessonQuestion[] }[], day: string, max = MINUTE_MAX): MinuteQuestion[] { + const out: MinuteQuestion[] = [] + for (const { lessonId, questions } of byLesson) { + const fit = questions.filter(isChoice) + if (!fit.length) continue + let seed = lessonId + for (const c of day) seed = (seed * 31 + c.charCodeAt(0)) >>> 0 + out.push({ ...fit[seed % fit.length], lessonId }) + if (out.length === max) break + } + return out +} diff --git a/src/Trale/miniapp-src/src/daily/steps.tsx b/src/Trale/miniapp-src/src/daily/steps.tsx new file mode 100644 index 00000000..15ae8222 --- /dev/null +++ b/src/Trale/miniapp-src/src/daily/steps.tsx @@ -0,0 +1,286 @@ +import React, { useEffect, useRef, useState } from 'react' +import Mascot from '../components/Mascot' +import Button from '../components/Button' +import { bad, good, haptic } from '../verbs/ui/juice' +import { allMatched, clock, newPairs, pairsHint, plural, tapPair, timeOut, type PairsState, type Side } from './logic' +import { DailyHeader, Dots, Geo, LinkButton, Page, Rich, Say, Sheet, StepTitle } from './ui' +import type { DailyItem, DailyTaskDto, DailyWarmRound } from './types' + +// Шаги занятия: вступление, разминка, игра «Собери пары» и проверка. Каждый шаг — один экран без прокрутки. + +interface StepProps { steps: number; at: number; onExit: () => void } + +// ── Вступление ─────────────────────────────────────────────────────────────── + +export function Intro({ task, onStart, onExit }: { task: DailyTaskDto; onStart: () => void; onExit: () => void }) { + const [why, setWhy] = useState(false) + return ( + + +
+
+ {task.chat.map((line, i) => ( +
+ {line} +
+ ))} +
+
+ + {task.why.length > 0 && setWhy(true)} testId="daily-why-link">Почему так} +
+ {why && ( + setWhy(false)} testId="daily-why"> +
    + {task.why.map((line, i) => ( +
  • + + +
  • + ))} +
+
+ )} +
+ ) +} + +// ── Разминка ───────────────────────────────────────────────────────────────── + +/** По одному раунду: грузинская форма и варианты перевода. Ошибся — показываем верный и идём дальше. */ +export function Warm({ rounds, onDone, ...head }: StepProps & { rounds: DailyWarmRound[]; onDone: (wrong: string[]) => void }) { + const [i, setI] = useState(0) + const [picked, setPicked] = useState(null) + const wrong = useRef([]) + const timer = useRef>() + useEffect(() => () => clearTimeout(timer.current), []) + + const round = rounds[i] + const right = round.options.find(o => o.ok) + const pickedOk = picked !== null && round.options[picked].ok + + function pick(at: number, el: Element) { + if (picked !== null) return + const ok = round.options[at].ok + setPicked(at) + if (ok) good(el) + else { bad(); wrong.current = [...wrong.current, round.item.key] } + timer.current = setTimeout(() => { + if (i === rounds.length - 1) return onDone(wrong.current) + setI(i + 1); setPicked(null) + }, ok ? 700 : 1500) + } + + return ( + + + Выбери перевод +
+
+ 12 ? 'text-[26px]' : 'text-[34px]'} cyrClassName="mt-1 text-[14px]" /> +
+ +
+ {picked !== null && (pickedOk + ? Верно + : Правильно: «{right?.ru}»)} +
+
+
+ {round.options.map((o, at) => { + const tone = picked === null ? 'bg-cream-tile' + : o.ok ? 'bg-navy-wash' + : at === picked ? 'bg-ruby-wash anim-shake' : 'bg-cream-tile opacity-50' + return ( + + ) + })} +
+
+ ) +} + +// ── Игра «Собери пары» ─────────────────────────────────────────────────────── + +export interface PairsResult { errors: number; wrong: string[]; seconds: number } + +/** После скольких «время вышло» можно идти дальше без игры: тупика быть не должно. */ +const SKIP_AFTER = 2 + +/** + * Слева грузинские формы, справа переводы: нажми форму, потом её перевод. Время идёт с первого нажатия. + * Вышло время — несобранное считается ошибкой, партия начинается заново; в итог идут ошибки всех партий. + */ +export function PairsGame({ pairs, seconds, onDone, ...head }: StepProps & { pairs: DailyItem[]; seconds: number; onDone: (r: PairsResult) => void }) { + const total = seconds * 1000 + const [game, setGame] = useState(() => newPairs(pairs.length)) + const [left, setLeft] = useState(total) + const [timeouts, setTimeouts] = useState(0) + const latest = useRef(game) + latest.current = game + const t0 = useRef(0) + /** Ошибки прошлых партий, в которых вышло время. */ + const before = useRef<{ errors: number; wrong: string[] }>({ errors: 0, wrong: [] }) + const pending = useRef[]>([]) + useEffect(() => () => pending.current.forEach(clearTimeout), []) + + const done = allMatched(game, pairs) + const running = game.started && !game.over && !done + + useEffect(() => { + if (!running) return + const id = setInterval(() => { + const rest = Math.max(0, total - (Date.now() - t0.current)) + setLeft(rest) + if (rest > 0) return + clearInterval(id) + const over = timeOut(latest.current, pairs) + before.current = { errors: before.current.errors + over.errors, wrong: [...new Set([...before.current.wrong, ...over.wrong])] } + setGame(over); setTimeouts(n => n + 1); bad() + }, 100) + return () => clearInterval(id) + }, [running]) // eslint-disable-line react-hooks/exhaustive-deps + + const finish = (last: PairsState | null, spent: number) => onDone({ + errors: before.current.errors + (last?.errors ?? 0), + wrong: [...new Set([...before.current.wrong, ...(last?.wrong ?? [])])], + seconds: spent + }) + + function tap(side: Side, i: number, el: Element) { + if (!game.started) t0.current = Date.now() + const { state, event } = tapPair(game, side, i, pairs) + if (!event) return + setGame(state) + if (event === 'select') haptic('tap') + if (event === 'miss') { + bad() + pending.current.push(setTimeout(() => setGame(g => (g.bad === state.bad ? { ...g, bad: null } : g)), 420)) + } + if (event === 'match') good(el) + if (event === 'done') { + const spent = Math.max(1, Math.round((Date.now() - t0.current) / 1000)) + good(el, 'big') + pending.current.push(setTimeout(() => finish(state, spent), 900)) + } + } + + function again() { + setGame(newPairs(pairs.length)); setLeft(total) + } + + const tile = (side: Side, i: number) => { + const p = pairs[i] + const matched = (side === 'l' ? game.matchedL : game.matchedR).includes(i) + const selected = game.sel?.side === side && game.sel.i === i + const wrong = game.bad !== null && (side === 'l' ? game.bad.l === i : game.bad.r === i) + const tone = matched ? 'bg-navy-wash opacity-30' : wrong ? 'bg-ruby-wash anim-shake' : selected ? 'bg-gold-wash ring-4 ring-gold' : 'bg-cream-tile' + return ( + + ) + } + + const count = pairs.length + return ( + + + {game.matchedL.length} из {count}
} + > + {game.over ? 'Время вышло' : 'Собери пары'} + +
+ {count} {plural(count, 'пара', 'пары', 'пар')} за {seconds} {plural(seconds, 'секунду', 'секунды', 'секунд')} +
+
+
+
+
+
{clock(left)}
+
+
+ {Array.from({ length: count }, (_, row) => [tile('l', game.left[row]), tile('r', game.right[row])])} +
+
+ {game.over ? ( + <> + + Время вышло. Собрано {game.matchedL.length} из {count} — сыграй ещё раз, получится быстрее. + +
+ + {timeouts >= SKIP_AFTER && finish(null, seconds)} testId="daily-game-skip">Идти дальше без игры} +
+ + ) : ( + {pairsHint(game, pairs)} + )} + + ) +} + +// ── Проверка ───────────────────────────────────────────────────────────────── + +/** Одна форма из игры среди похожих. Ошибся — Бомбора объясняет, выбираешь снова. */ +export function Check({ check, onDone, ...head }: StepProps & { check: DailyTaskDto['check']; onDone: (errors: number) => void }) { + const [wrong, setWrong] = useState([]) + const [last, setLast] = useState(null) + const [ok, setOk] = useState(false) + const said = last !== null ? check.picks[last].message : check.intro + + function pick(i: number, el: Element) { + if (ok || wrong.includes(i)) return + setLast(i) + if (check.picks[i].ok) { setOk(true); good(el, 'big') } + else { setWrong([...wrong, i]); bad() } + } + + const cols = check.picks.length > 3 ? 'grid-cols-2' : 'grid-cols-1' + return ( + + + {check.prompt} +
+ {check.picks.map((p, i) => { + const tone = ok && p.ok ? 'bg-navy-wash' : wrong.includes(i) ? `bg-ruby-wash opacity-60 ${last === i ? 'anim-shake' : ''}` : ok ? 'bg-cream-tile opacity-50' : 'bg-cream-tile' + return ( + + ) + })} +
+
+ {said} +
+ +
+ + ) +} diff --git a/src/Trale/miniapp-src/src/daily/store.ts b/src/Trale/miniapp-src/src/daily/store.ts new file mode 100644 index 00000000..65e3d82a --- /dev/null +++ b/src/Trale/miniapp-src/src/daily/store.ts @@ -0,0 +1,38 @@ +import { ApiError, fetchDailyTask } from '../api' +import type { DailyTaskDto } from './types' + +// Последнее занятие с сервера — чтобы карточка на главной и экран задания не ждали друг друга +// и видели одно и то же: закрыл день на экране — карточка уже «Сделано». + +let cached: DailyTaskDto | null = null +const listeners = new Set<(task: DailyTaskDto | null) => void>() + +export const cachedDaily = () => cached + +/** Свежий ответ сервера (итог дня, «новое» открыто, стенд перемотал день). */ +export function setDaily(task: DailyTaskDto | null) { + cached = task + listeners.forEach(l => l(task)) +} + +/** Занятие на сегодня. null — задания нет: нет доступа (402), оно пока открыто не всем (404) или сервер его не предлагает. */ +export async function loadDaily(): Promise { + try { + const task = await fetchDailyTask() + setDaily(task.available ? task : null) + } catch (e) { + if (e instanceof ApiError && (e.status === 402 || e.status === 404)) setDaily(null) + else throw e + } + return cached +} + +export function onDaily(listener: (task: DailyTaskDto | null) => void): () => void { + listeners.add(listener) + return () => { listeners.delete(listener) } +} + +/** Только для тестов. */ +export function resetDailyCache() { + cached = null +} diff --git a/src/Trale/miniapp-src/src/daily/types.ts b/src/Trale/miniapp-src/src/daily/types.ts new file mode 100644 index 00000000..13065cd5 --- /dev/null +++ b/src/Trale/miniapp-src/src/daily/types.ts @@ -0,0 +1,116 @@ +// «Задание дня»: сервер собирает занятие на сегодня из того, что человек уже учил +// (GET /api/miniapp/daily-task), мини-апп его проводит и сообщает итог. +// Все тексты приходят с сервера готовыми; транскрипцию грузинского (cyr) мини-апп ставит сам. + +/** Форма глагола или слово из словаря. */ +export interface DailyItem { + /** Глагол: «v:<лемма>:<время>:<лицо>», слово словаря: «w:». */ + key: string + kind: 'verb' | 'word' + ka: string + ru: string + /** Только у форм глагола. */ + lemma?: string + verbRu?: string + tense?: string + person?: number +} + +/** Раунд разминки: грузинская форма и варианты перевода. */ +export interface DailyWarmRound { + item: DailyItem + options: { ru: string; ok: boolean }[] +} + +/** Вариант проверки: одна форма из игры среди похожих. */ +export interface DailyPick { + item: DailyItem + ok: boolean + /** Что сказать после нажатия: «Верно: …» или «… — это «…». Нажми другую форму.» */ + message: string +} + +/** Новое в конце: формы глагола, урок курса или минутная проверка модуля. */ +export interface DailyNew { + kind: 'forms' | 'lesson' | 'check' + /** «Новые формы глагола «иметь»» · «Падежи» · «Знакомство». */ + title: string + /** «урок 8 из 10 · Итоговое повторение» · «проверка на минуту» · «прошедшее: сделал». */ + line: string + /** Реплика Бомборы: почему именно это. */ + say: string + /** Подпись кнопки: «Открыть новые формы» · «Пройти урок» · «Пройти проверку». */ + button: string + /** forms: лемма глагола — открыть его сессию. */ + verbId?: string + /** lesson и check: модуль; lesson: урок. */ + moduleId?: string + lessonId?: number + /** check: уроки, из которых брать вопросы (по одному вопросу из урока, всего шесть). */ + checkLessons?: number[] +} + +export interface DailyResult { + errors: number + xpEarned: number + streak: number +} + +export interface DailyTaskDto { + /** false — собирать не из чего (нет ни форм, ни слов): карточку не показываем. */ + available: boolean + /** День задания, «2026-11-16» (UTC, как серия). */ + day: string + done: boolean + mode: 'comeback' | 'review' | 'mix' + level: 1 | 2 | 3 + /** «Обычный день» · «Закрепляем» · «Возвращение». */ + title: string + /** Реплики Бомборы перед началом (те же, что в сообщении бота) и подпись кнопки. */ + chat: string[] + button: string + /** Почему задание собрано так — для шторки «Почему так». */ + why: string[] + /** Секунд на игру в пары. */ + seconds: number + /** Разминка; пустой список — разминки нет. */ + warm: DailyWarmRound[] + /** Пары для игры: грузинское — русское. */ + pairs: DailyItem[] + check: { prompt: string; intro: string; picks: DailyPick[] } + /** Что будет предложено в конце, если игра пройдёт чисто (не больше одной ошибки). */ + next: DailyNew | null + /** После итога: что предложено на самом деле; null — нового сегодня нет. */ + offer: DailyNew | null + /** Предложение уже открывали или проверку уже прошли — повторно не зовём. */ + offerTaken: boolean + result: DailyResult | null + /** Только на стенде: показать кнопки «следующий день». */ + dev: boolean +} + +/** POST /api/miniapp/daily-task/result */ +export interface DailyReportDto { + day: string + /** Ключи форм разминки, на которых была ошибка. */ + warmWrong: string[] + /** Ключи пар, на которых была хотя бы одна ошибка. */ + pairWrong: string[] + /** Сколько всего неверных попыток в игре в пары (включая несобранные из-за времени). */ + errors: number + checkErrors: number + seconds: number +} + +export interface DailySavedDto { + task: DailyTaskDto + xpEarned: number + /** Прогресс мини-аппа после зачёта (опыт, серия) — как после урока. */ + progress: import('../types').ProgressState | null +} + +/** POST /api/miniapp/daily-task/offer: предложение открыли, либо итог минутной проверки. */ +export interface DailyOfferReportDto { + day: string + outcome: 'opened' | 'passed' | 'failed' +} diff --git a/src/Trale/miniapp-src/src/daily/ui.tsx b/src/Trale/miniapp-src/src/daily/ui.tsx new file mode 100644 index 00000000..1c0c3711 --- /dev/null +++ b/src/Trale/miniapp-src/src/daily/ui.tsx @@ -0,0 +1,138 @@ +import React from 'react' +import Mascot from '../components/Mascot' +import Button from '../components/Button' +import { CloseIcon } from '../verbs/ui/icons' +import { SAFE_TOP } from '../verbs/ui/GameShell' +import { OVERLAY, useOverlay } from '../verbs/ui/overlayStack' +import { cyr } from '../verbs/types' +import { boldParts } from './logic' +import '../verbs/ui/juice.css' + +// Общие части экранов «Задания дня»: шапка с шагами, реплика Бомборы, грузинское слово с транскрипцией. + +/** Экран занятия: всё помещается без прокрутки, кнопки внизу — над безопасной зоной. */ +export function Page({ testId, children }: { testId: string; children: React.ReactNode }) { + return ( +
+ {children} +
+ ) +} + +/** Шапка: крестик и полоска из шагов занятия (или подпись, когда шагов ещё нет). */ +export function DailyHeader({ steps, at, label, onExit }: { steps?: number; at?: number; label?: string; onExit: () => void }) { + return ( +
+ + {steps ? ( + <> +
+ {Array.from({ length: steps }, (_, i) => ( +
+ ))} +
+
{at} из {steps}
+ + ) : ( +
{label}
+ )} +
+ ) +} + +/** Заголовок шага: надпись над ним и сам заголовок. */ +export function StepTitle({ eyebrow, children, right }: { eyebrow?: string; children: React.ReactNode; right?: React.ReactNode }) { + return ( +
+
+ {eyebrow &&
{eyebrow}
} +

{children}

+
+ {right} +
+ ) +} + +/** Реплика Бомборы: что делать сейчас или что получилось. */ +export function Say({ mood = 'happy', size = 72, children, testId }: { + mood?: 'happy' | 'cheer' | 'think' | 'guide'; size?: number; children: React.ReactNode; testId?: string +}) { + return ( +
+ +
+ {children} +
+
+ ) +} + +/** Грузинское слово и под ним — как оно читается, кириллицей. */ +export function Geo({ ka, className = 'text-[18px]', cyrClassName = 'text-[11px]' }: { ka: string; className?: string; cyrClassName?: string }) { + return ( + <> + {ka} + {cyr(ka)} + + ) +} + +/** Строка с выделением … — без вставки разметки в страницу. */ +export function Rich({ line }: { line: string }) { + return <>{boldParts(line).map((p, i) => (p.bold ? {p.text} : {p.text}))} +} + +/** Шторка снизу: «Почему так». Закрывается крестиком, кнопкой, нажатием мимо и кнопкой «Назад». */ +export function Sheet({ title, onClose, children, testId }: { title: string; onClose: () => void; children: React.ReactNode; testId?: string }) { + useOverlay(onClose, OVERLAY.help) + return ( +
+
e.stopPropagation()} data-testid={testId} role="dialog" aria-label={title} + > +
+
{title}
+ +
+
{children}
+
+
+
+ ) +} + +/** Ссылка-кнопка под главной кнопкой: второе, необязательное действие. */ +export function LinkButton({ onClick, children, testId }: { onClick: () => void; children: React.ReactNode; testId?: string }) { + return ( + + ) +} + +export const CheckIcon = ({ size = 16, className = '' }: { size?: number; className?: string }) => ( + +) + +/** Точки раундов: пройденные, текущий, впереди. */ +export function Dots({ count, at }: { count: number; at: number }) { + return ( + + {/* «Задание дня» — первым: короткое занятие из своего, потом «новое». */} + {suggestion && (