From 8b263642f78e7fc22ffebf2a04601b1a4b61832e Mon Sep 17 00:00:00 2001 From: Dmitry Afonchenko Date: Tue, 10 Nov 2026 15:02:23 +0400 Subject: [PATCH] feat(admin): send a broadcast at a set day, hour and time zone MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The owner picks a day, an hour and a time zone on the sending step (or gives them in a pasted broadcast as "когда:" / "пояс:") and the server sends the campaign by itself at that moment to whoever is in the group then. A scheduled campaign is shown as such in the list and can be called off with one button. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01TAcLBj2Fn8nAKE4qWyn5es --- FEATURES.md | 15 +- .../Admin/BroadcastCampaignService.cs | 151 +- src/Application/Common/ITraleDbContext.cs | 8 + src/Domain/Entities/BroadcastCampaign.cs | 9 + .../BroadcastCampaignConfiguration.cs | 1 + ...1110105200_AddCampaignSchedule.Designer.cs | 1823 +++++++++++++++++ .../20261110105200_AddCampaignSchedule.cs | 40 + .../Migrations/TraleDbContextModelSnapshot.cs | 7 + src/Persistence/TraleDbContext.cs | 20 + src/Trale/Controllers/AdminController.cs | 16 +- .../HostedServices/CampaignSendWorker.cs | 16 +- src/Trale/miniapp-src/e2e/admin.spec.ts | 77 +- .../src/admin/pastedBroadcast.test.ts | 18 +- .../miniapp-src/src/admin/pastedBroadcast.ts | 31 +- .../miniapp-src/src/admin/schedule.test.ts | 31 + src/Trale/miniapp-src/src/admin/schedule.ts | 60 + src/Trale/miniapp-src/src/api.ts | 19 +- .../src/screens/AdminBroadcastScreen.tsx | 99 +- .../src/screens/AdminBroadcastsScreen.tsx | 14 +- .../__tests__/AdminBroadcastScreen.test.tsx | 108 + .../screens/__tests__/AdminSections.test.tsx | 10 + .../Admin/BroadcastCampaignTests.cs | 185 ++ 22 files changed, 2691 insertions(+), 67 deletions(-) create mode 100644 src/Persistence/Migrations/20261110105200_AddCampaignSchedule.Designer.cs create mode 100644 src/Persistence/Migrations/20261110105200_AddCampaignSchedule.cs create mode 100644 src/Trale/miniapp-src/src/admin/schedule.test.ts create mode 100644 src/Trale/miniapp-src/src/admin/schedule.ts diff --git a/FEATURES.md b/FEATURES.md index 3de19752..b284151f 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -105,12 +105,12 @@ Location: `src/Trale/miniapp-src/src/`. The test greps the base file name (e.g. | `AdminScreen.tsx` | `admin` (owner only; `?screen=admin`) | «Статистика» — the admin's start screen, the same as it always was: tiles «Пользователи» (всего, активных, Pro, на триале, Free, конверсия), «Выручка» (всего ⭐, за неделю ⭐, покупок, возвратов + оплат за 30 дней, подписок действует), «Активность» (слов в словарях, слов на юзера, новых сегодня, за неделю + занимались сегодня / за неделю) and the chart «Новые юзеры» for 7 / 30 / 90 days (`components/admin/statTiles.tsx`). The admin is navigated by a bottom tab bar (`components/admin/AdminTabBar.tsx`): «Статистика», «Люди», «Связь» (badge: unanswered messages + unfinished surveys), «Рассылки» (badge: unfinished), «Ещё» (badge: verbs to review). Each tab keeps its own stack of screens, filters, search and scroll position (`admin/adminNav.ts`, `admin/useKept.ts`); a second tap on the active tab returns to its root and top; «Назад» in the header and Telegram's back button go one screen back inside the tab, from a tab's root — to the profile. Every screen has its own address (`?screen=admin-…`); a direct link opens the right tab with its root underneath. The bar hides while a text field has focus (keyboard) and in step-by-step flows. All screens share one header and the same loading (skeleton) / no access / error / empty states (`components/admin/AdminPage.tsx`). | | `AdminMoreScreen.tsx` | `admin-more` (owner only) | The root of the «Ещё» tab: «Глаголы» (with how many wait), «Оплаты», «Система». | | `AdminUsersScreen.tsx` | `admin-users` (owner only) | «Люди» tab: search by Telegram id on top (no names are stored), filters «все / платят / пробный период / доступ закончился / заблокировали бота» with counts and the order (recent study / registration / dictionary size) as horizontally scrolling chip ribbons, pages of 30 with «Показать ещё». The filter, the search, the loaded list and the scroll position are kept while the owner opens a card or another tab. | -| `AdminBroadcastsScreen.tsx` | `admin-broadcasts` (owner only) | «Рассылки» tab: «Новая рассылка» on top; a card «Черновик на этом устройстве» with «Продолжить черновик» / «Удалить» when a new broadcast was closed unfinished; every ordinary campaign sent to people, newest first: «черновик / идёт / завершена», sent N of M, opened by the button, gifts given. | +| `AdminBroadcastsScreen.tsx` | `admin-broadcasts` (owner only) | «Рассылки» tab: «Новая рассылка» on top; a card «Черновик на этом устройстве» with «Продолжить черновик» / «Удалить» when a new broadcast was closed unfinished; every ordinary campaign sent to people, newest first: «запланирована / черновик / идёт / завершена», sent N of M, opened by the button, gifts given. A scheduled one says «уйдёт сама 28.11.2026 12:00 (Тбилиси)» — by the clock of the zone it was set in. | | `AdminPaymentsScreen.tsx` | `admin-payments` (owner only) | Payments newest first (who, when, plan, stars, refunds marked), totals, and the subscriptions that end within 14 days or ended within the last 30. A row opens the person's card. | | `AdminSystemScreen.tsx` | `admin-system` (owner only) | Under «Ещё»: the background job queue and translations of the last day, test pushes to oneself, the older one-off broadcast by segment. | | `VerbReviewScreen.tsx` | `verb-review` (owner only; `?screen=verb-review[&verb=]`) | Review of the verbs a model wrote. Anyone the server refuses sees «Нет доступа.» and nothing else. Queue: what needs attention first (unverified tenses → tenses verified but the verb not approved → approved), counts, filters «ждут / непроверенные времена / проверены / все», search in Russian or Georgian. One verb per screen: Russian meaning, lemma with Cyrillic, who asked and when, «Заметки моделей» folded; every tense a block — verified ones folded to a line, unverified ones open with six forms, transcription, the Russian phrase and «есть / нет в текстах» — with «Подтвердить», «Исправить» (inline, six fields) and «Убрать время»; the block updates in place and the result stays at the bottom of the screen. «← Предыдущий / N из M / Следующий глагол →» walk the batch. «Вставить исправление» (`components/admin/VerbFixPaste.tsx`, `verbFix.ts`): the whole review of the verb as one pasted text — lines «глагол: », «: six forms» («—» for an empty cell), «подтвердить: », «глагол проверен»; it shows what changes (old → new form) and refuses a fix for another verb, an unknown tense, a wrong number of forms or an approval with tenses left unverified; «Применить» sends the edits, then the confirmations, then the approval, by the same requests as the buttons, and stops at the first refusal. «Глагол проверен» (or «Подтвердить всё и отметить проверенным» with a confirmation), «Снять отметку», «Пересобрать» (asks first for an approved verb). `components/admin/TenseBlock.tsx`, `components/admin/verbReview.ts`. | | `AdminUserScreen.tsx` | `admin-user` (owner only; `?screen=admin-user&id=`) | A person's card: when and where from they came (`AcquisitionSource` in words), access and until when, last study, whether the bot reaches them; lessons, words, quizzes, verb sessions; payments; answers in surveys; «Написать» → the conversation (the owner may write first); grant / revoke a subscription with a confirmation. | -| `AdminBroadcastScreen.tsx` | `admin-broadcast` (owner only; `&key=` opens an existing one) | One broadcast. A new one goes by steps, each on its own screen: text → button and where it leads (chosen by the name of a mini-app screen, or an own address) → gift of access days → audience, test group or everyone, optional own name → sending: «Отправить себе» (a trial to the owner only), pick recipients (asks first), «Отправить следующие 25» (closed until recipients are picked; asks first, names the gift). The server names the campaign (`broadcast--`). An opened one starts on its sending: the rest of the group, or «Дослать ещё одной группе» — the same campaign, so nobody gets the message or the gift twice, and the screen says so. The flow is a focused mode: no tab bar, «шаг N из 5» and «Закрыть» in the header (asks before closing something unfinished), «Назад / Дальше» pinned to the bottom. Until recipients are picked the unfinished broadcast is saved on the device (`localStorage`, `admin/useKept.ts`) and offered again from the list. | +| `AdminBroadcastScreen.tsx` | `admin-broadcast` (owner only; `&key=` opens an existing one) | One broadcast. A new one goes by steps, each on its own screen: text → button and where it leads (chosen by the name of a mini-app screen, or an own address) → gift of access days → audience, test group or everyone, optional own name → sending: «Отправить себе» (a trial to the owner only), pick recipients (asks first), «Отправить следующие 25» (closed until recipients are picked; asks first, names the gift). The server names the campaign (`broadcast--`). An opened one starts on its sending: the rest of the group, or «Дослать ещё одной группе» — the same campaign, so nobody gets the message or the gift twice, and the screen says so. The flow is a focused mode: no tab bar, «шаг N из 5» and «Закрыть» in the header (asks before closing something unfinished), «Назад / Дальше» pinned to the bottom. Until recipients are picked the unfinished broadcast is saved on the device (`localStorage`, `admin/useKept.ts`) and offered again from the list. The sending step also has «Или назначь время — уйдёт само»: a day, an hour and a time zone (Тбилиси by default; Москва, Берлин, Лондон, UTC) and «Запланировать» — no recipients are picked, the server sends it at that moment to whoever is in the group then (`admin/schedule.ts` turns the wall clock of the zone into UTC). A scheduled broadcast shows «Запланирована на …» with «Отменить расписание» and nothing to pick or send by hand. A pasted broadcast takes the lines `когда: 28.11.2026 12:00` and `пояс: Тбилиси`. | | `SurveyBuilderScreen.tsx` | `admin-survey` (owner only) | Survey builder, four steps on separate screens with «Назад / Дальше». A survey is a form: the first question goes to the bot as buttons, the rest are answered in the mini-app. A survey may carry a gift of access days for answering: then the message has one button, every question — the first too — is in the mini-app, and the gift is given after the last question to whoever answered at least one. 1 «Выбери опрос» — ready-made forms (`SurveyPresets`: «Тем, кто пользуется», «Тем, кто перестал», «Тем, кто платил») and «Собрать свой»; a survey left half sent waits here under «Не дослано» («отправлено N из M», «Продолжить»). «Тем, кто платил» is a thank-you with four questions and a month of access for answering them («Ответить на вопросы», 30 days). 2 «Вопросы» — the bot message as a preview, «Поменять вступление» («Поменять сообщение» for a gift survey), the tile «Подарок» (days of full access, 0 — no gift; the button's caption; that the gift comes after the last question for at least one answer and how the days are added to the access a person has; a reminder to fix the promise when the days differ from the ready form's), a card per question with «Изменить», up / down, remove; «Добавить вопрос» (ready ones from the bank or one's own, 6 at most); «Посмотреть как пользователь» walks the form without recording anything. A question opens on its own screen (`components/admin/SurveyQuestionEditor.tsx`): text, «Выбор варианта» / «Свободный ответ», options by taps (rename, remove, add, ready ones), the switch «Другое — свой ответ». The first question must have options, 4 at most — the builder says why and does not go on (not for a gift survey: nothing of it goes to the chat). «Посмотреть как пользователь» of a gift survey can be walked as «Подписка закончилась», «Подписка действует» or «Пожизненный» — the line about the gift above the questions and the last screen follow. «Отправить себе» of a gift survey is a trial: the owner walks the screens a person with their access would get, marked «Пробная отправка», and no days are given. A question with a headline number says so; renaming its buttons keeps the number, removing one of its two key options or the question itself is said in red (`components/admin/surveyHeadline.ts`). 3 «Кому отправить» — an audience with its size (by access, or by whether people studied in the last 30 days), «Сначала пробной группе» / «Сразу всем». 4 «Отправка» — «Отправить себе» (a trial to the owner only, the whole form can be walked), pick recipients (asks first, sends nothing), «Отправить следующие 25» (closed until recipients are picked; asks first), status, «Смотреть ответы»; after a test group the rest of the audience is picked here too, also after coming back (`resume`). The campaign's name is made by the server; once recipients are picked the questions are fixed. The builder is a focused mode too: no tab bar, «шаг N из 4» and «Закрыть», «Назад / Дальше» pinned to the bottom; an unfinished survey is saved on the device and offered on the first step as «Продолжить черновик». | | `AdminFeedbackScreen.tsx` | `admin-feedback` (owner only) | «Связь» tab. Its root is three sections under a segmented switch — «Сообщения» (opens first), «Опросы» («Новый опрос» on top, the list with what is unfinished), «Экран покупки» — each with its own address (`admin-messages`, `admin-surveys`, `admin-paywall`); a survey's results and a conversation open on top. A conversation the owner started first is listed too («отвечено», «ты: …»). Earlier wording of the same content follows. List: «Что смутило? — экран покупки», «Написали автору», and every survey sent to people — by its first question, with the date, the audience, received / answered / reached the end, «не дослано» when recipients still wait. A survey's own screen: the funnel «получили → ответили на первый вопрос → открыли форму в мини-аппе → дошли до конца», then every question with counts per option, shares and what was written («Другое», free answers); a question with a headline number shows it first (the share of «Очень расстроюсь» without «Уже не пользуюсь»); chips narrow the answers to those who chose one option of the first question; «Продолжить отправку». A survey with a gift has its own funnel — «получили → открыли → ответили хотя бы на один вопрос → дошли до конца → получили подарок» — and the same line in the list; a form without a headline question simply shows no headline number. A tap on an id opens the user. `components/admin/feedbackView.tsx`. Every text has «Ответить» → the conversation with its author (`components/admin/FeedbackThread.tsx`): who it is, their texts with where each came from, the owner's answers with what Telegram said («человек заблокировал бота — ответ не доставлен»), a field with a preview of the bot message, «Отправить», «Не требует ответа». «Сообщения от людей» lists everyone who wrote something with the status — «новое» / «человек ответил» / «отвечено» / «не требует ответа» — and the filter «Без ответа»; the count of the unanswered is on the admin's «Отзывы» tile. | | `FeedbackScreen.tsx` | `feedback` (`?screen=feedback[&fc=][&thread=1]`) | «Написать автору»: a text field (2000 characters), «Отправить», thanks. Entries: the tile in `Profile.tsx` settings, «Написать подробнее» under an answer to a one-question survey (then the message is tied to that campaign) and «Ответить» under the author's answer in the bot. Once the author has answered, the latest messages of the conversation are shown above the field («Наша переписка»). Says «Отвечу сюда же, в чат с ботом.» and when the daily limit is reached. | @@ -284,7 +284,7 @@ Location: `src/Trale/Controllers/`. Routes relative to controller base. Test gre | GET | `/api/admin/overview` | The admin's first screen: new people in 7 days, studied today / in 7 days, payments and stars in 30 days, active subscriptions, trials; what waits — unanswered messages, unfinished surveys and broadcasts, verbs to review. | | GET | `/api/admin/users` | People page by page: `search` (a part of the Telegram id), `filter` (`all` / `paying` / `trial` / `accessEnded` / `blocked`), `sort` (`activity` / `registered` / `words`), `skip` / `take`; counts per filter. | | GET | `/api/admin/payments` | Payments newest first (`skip` / `take`), totals, subscriptions ending within 14 days and ended within the last 30. | -| GET | `/api/admin/campaigns` | Every campaign sent to people with picked / pending / sent / opened / gifted and `state` (`draft` / `running` / `done`); `?surveys=true\|false`. | +| GET | `/api/admin/campaigns` | Every campaign sent to people with picked / pending / sent / opened / gifted and `state` (`scheduled` / `draft` / `running` / `done`), `scheduledAtUtc`, `scheduledTimeZone`; `?surveys=true\|false`. | | GET | `/api/admin/signups` | Signups timeseries. | | GET | `/api/admin/recent-users` | Recent users with filters. | | GET | `/api/admin/users/{telegramId}` | User detail. | @@ -303,11 +303,11 @@ Location: `src/Trale/Controllers/`. Routes relative to controller base. Test gre | GET | `/api/admin/broadcast/preview` | Preview broadcast target. | | POST | `/api/admin/broadcast` | Send broadcast (one shot: the whole segment inside one request, no pauses, no record of who got it — for small segments only). | | GET | `/api/admin/campaigns/audiences` | How many reachable people each campaign audience has now: `accessEnded`, `onTrial`, `paying`, `proLapsed`, `owner`, and by activity — `activeLately` / `inactiveLong`: whether the person studied in the last 30 days (a lesson answer, a word added, a quiz or a verb session started; someone with no such trace counts from the day they registered); `paid` / `neverPaid` — has a payment that was not refunded (a gift of access is not paying). Reachable = has not blocked the bot and has not turned notifications off. | -| POST | `/api/admin/campaigns/prepare` | Pick recipients of a campaign — a random sample of `sampleSize`, or everyone not picked yet — and record them. Sends nothing. `giftDays` (0–30, needs a button) makes the campaign give that many days of access to a recipient who opens its button; `giftOfferDays` (default 14) — for how long after the campaign's creation. `dryRun` (default true) only counts. Repeating never picks a person twice. `survey` (`{intro, questions: [{text, kind: choice | text, options, allowOther}]}`, 1–6 questions, 2–6 options each; the first question has options, 4 at most, because it goes under the message as buttons) makes it a survey: the message is the intro and the first question, a survey without a gift has no mini-app button, and its form cannot change once the campaign exists. A survey with `giftDays` > 0 goes out as its intro (required) with one web-app button `buttonText` (required) that opens the form (`screen=survey&s=`, set by the server — `buttonQuery` is refused); its first question may be of any kind; its gift is given at the end of the form for at least one answer (opening the button gives nothing) and is added on top of the access a person has (`User.ExtendAccessDays`, the referral reward's rule: a running subscription, trial or bonus period is extended from its own end; with no access the days count from the open; lifetime gets nothing) — unlike an ordinary campaign's gift (`User.GiftAccessDays`: days from the open, nothing for access that already runs longer). A gift survey sent to the `owner` audience gives no days. With an empty `key` and `newSurveySlug` the server names a new survey itself — `survey---`, with a number when taken — and returns the key; such a campaign is always a new one. With an empty `key` and `newBroadcast` the server names an ordinary campaign itself (`broadcast--`, `-test` for a trial to oneself). `anotherAudience` adds one more audience to an existing campaign — people already in it are skipped, so the message and the gift reach a person once. | +| POST | `/api/admin/campaigns/prepare` | Pick recipients of a campaign — a random sample of `sampleSize`, or everyone not picked yet — and record them. Sends nothing. `giftDays` (0–30, needs a button) makes the campaign give that many days of access to a recipient who opens its button; `giftOfferDays` (default 14) — for how long after the campaign's creation. `dryRun` (default true) only counts. Repeating never picks a person twice. `sendAtUtc` (+ `sendAtTimeZone`, an IANA name) schedules the campaign instead: it is saved with its time and no recipients, and goes out by itself to whoever is in the audience when the time comes (future, at most 365 days ahead, no `sampleSize`); repeating moves the time; a gift's offer is counted from that time. `survey` (`{intro, questions: [{text, kind: choice | text, options, allowOther}]}`, 1–6 questions, 2–6 options each; the first question has options, 4 at most, because it goes under the message as buttons) makes it a survey: the message is the intro and the first question, a survey without a gift has no mini-app button, and its form cannot change once the campaign exists. A survey with `giftDays` > 0 goes out as its intro (required) with one web-app button `buttonText` (required) that opens the form (`screen=survey&s=`, set by the server — `buttonQuery` is refused); its first question may be of any kind; its gift is given at the end of the form for at least one answer (opening the button gives nothing) and is added on top of the access a person has (`User.ExtendAccessDays`, the referral reward's rule: a running subscription, trial or bonus period is extended from its own end; with no access the days count from the open; lifetime gets nothing) — unlike an ordinary campaign's gift (`User.GiftAccessDays`: days from the open, nothing for access that already runs longer). A gift survey sent to the `owner` audience gives no days. With an empty `key` and `newSurveySlug` the server names a new survey itself — `survey---`, with a number when taken — and returns the key; such a campaign is always a new one. With an empty `key` and `newBroadcast` the server names an ordinary campaign itself (`broadcast--`, `-test` for a trial to oneself). `anotherAudience` adds one more audience to an existing campaign — people already in it are skipped, so the message and the gift reach a person once. | | POST | `/api/admin/campaigns/{key}/send` | Send the next batch (≤100) of picked recipients, 10 messages per second; one of the two things that make a campaign message leave. Blocked users are flagged inactive; on Telegram's 429 the batch stops and says how long to wait. | | POST | `/api/admin/campaigns/{key}/send-all` | The other one: marks the campaign to be sent to everyone picked (`BroadcastCampaigns.SendAllRequestedAtUtc`) — `CampaignSendWorker` sends it batch by batch whether or not the admin page stays open, and the owner gets a bot message when no one is left waiting. Sends nothing itself. The status has `sendingAll`. | -| POST | `/api/admin/campaigns/{key}/stop` | Stops that background sending; whoever has not got the message stays waiting. | -| GET | `/api/admin/campaigns/{key}` | Campaign status: picked, waiting, delivered, blocked, rejected, unanswered, opened by the button; `giftDays`, `giftOfferEndsAtUtc`, `gifted`; of those who opened — `playedVerbSession`, `finishedVerbSession`, `paidAfterOpen`. For a survey — `survey` (the form) and `surveyAnswers`: the buttons of its first question with how many people chose each. | +| POST | `/api/admin/campaigns/{key}/stop` | Stops that background sending; whoever has not got the message stays waiting. Also takes the campaign off its schedule (`ScheduledAtUtc`) — nothing goes out. | +| GET | `/api/admin/campaigns/{key}` | Campaign status: picked, waiting, delivered, blocked, rejected, unanswered, opened by the button; `giftDays`, `giftOfferEndsAtUtc`, `gifted`; `scheduledAtUtc`, `scheduledTimeZone`; of those who opened — `playedVerbSession`, `finishedVerbSession`, `paidAfterOpen`. For a survey — `survey` (the form) and `surveyAnswers`: the buttons of its first question with how many people chose each. | | GET | `/api/admin/feedback` | What people said. `recent` — the latest answers that carry an option or a text (`take` ≤200), optionally only one `kind` (`paywall` / `survey` / `message`) and / or one `campaign`. Always whole: `paywall` (`shown` + counts per option), `messages` (how many free messages), `surveys` — every survey sent to people, newest first: title (the first question), number of questions, date, audience, `picked`, `pending`, `funnel` (a trial sent only to the owner is not listed). | | GET | `/api/admin/feedback/surveys/{key}` | One survey: `summary` with `giftDays` and the funnel (sent → answered the first question → opened the form → finished; also `gifted` and `answered` — people who answered at least one question), `questions` — per question the counts per option, how many answered, the texts and the headline number when the question has one; `written` — messages by «Написать подробнее». `segment` (an option of the first question) counts the questions only for those who chose it. | | GET | `/api/admin/feedback/threads` | Everyone who wrote something (a letter, own words in a survey, a comment at the paywall), those waiting for an answer first: `status` (`new` / `repliedBack` / `answered` / `closed`), the latest text; `unanswered` — how many wait. `?unanswered=true` — only them. | @@ -339,7 +339,7 @@ Location: `src/Trale/HostedServices/`. | `FinishTranslationsOnShutdown` | `StopAsync` | Lets the translations running in this instance (`TranslationJobs`) finish and answer for 15 s on shutdown, then stops the rest: one that is on record (`QueuedTranslations`) is left for the job queue to do again on another instance or after the restart; one too young to be on record tells the person to send the word again. | | Hangfire server (`JobQueueSetup.AddJobQueue`, registered in Infrastructure, not a class in this folder) | Continuous | The durable job queue's workers (4 per instance) over the `hangfire` schema of the application database, which Hangfire creates itself on first start. Runs `TranslationQueueJob` → `TranslationJobs.ResumeAsync`. A job whose worker died is delivered again after `JobQueueSetup.InvisibilityTimeout` (1 min, sliding). | | `ReturnPushWorker` | Daily at 10:00 UTC | Dispatch D1+ return push to users who started a lesson but didn't return (#940). | -| `CampaignSendWorker` | Every 5s (1s between batches while sending) | Sends the campaigns the owner asked to send to everyone (`send-all`), 25 at a time per campaign, 10 messages per second, waiting out Telegram's 429; touches no other campaign. When one has no one left waiting, its request is cleared atomically (`TryFinishCampaignSendAllAsync`, so with two replicas the owner hears once) and the owner gets a bot message with how many got it. Carries on after a restart. | +| `CampaignSendWorker` | Every 5s (1s between batches while sending) | Sends the campaigns the owner asked to send to everyone (`send-all`), 25 at a time per campaign, 10 messages per second, waiting out Telegram's 429; touches no other campaign. When one has no one left waiting, its request is cleared atomically (`TryFinishCampaignSendAllAsync`, so with two replicas the owner hears once) and the owner gets a bot message with how many got it. Carries on after a restart. Before each round it starts the campaigns whose scheduled time has come (`BroadcastCampaignService.StartScheduledAsync`): the time is cleared and the send-all request set in one atomic update (`TryStartScheduledCampaignAsync`, so two replicas start a campaign once), and everyone who is in the campaign's audience at that moment and not yet in the campaign is recorded as waiting. | | `HourlyNotificationWorker` | Every top-of-hour UTC | Fan-out tick for contextual pushes — calls `IHolidayNotificationService` / `ICoinsNotificationService` / `IStreakNotificationService` / `IFirstOpenReminderService` / `IFirstWeekNudgeService` with fault-isolation. Holiday push uses `TbilisiMorningWindow` to fire only at 09:xx Tbilisi (#997, epic #894). | --- @@ -418,6 +418,7 @@ Location: `src/Persistence/Migrations/`. Test greps the migration class name (af | `RemapNumbersLessonProgress` | Data only: «Числа» went from 5 lessons to 11, so `CompletedLessonsJson.numbers` is remapped — old 1 (1–10) → 1–4, old 2 (11–20) → 5–6, old 3 (21–100) → 7–10, old 4 (100+, ordinals, days) → 11; old 5 (listening 1–20) has no counterpart. | | `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. | --- diff --git a/src/Application/Admin/BroadcastCampaignService.cs b/src/Application/Admin/BroadcastCampaignService.cs index be98a748..16b6f372 100644 --- a/src/Application/Admin/BroadcastCampaignService.cs +++ b/src/Application/Admin/BroadcastCampaignService.cs @@ -42,6 +42,8 @@ public partial class BroadcastCampaignService( public const int MaxGiftOfferDays = 90; /// "Active" and "inactive" audiences: whether the person did anything in this many days. public const int ActivityWindowDays = 30; + /// How far ahead a campaign may be scheduled. + public const int MaxScheduleDays = 365; /// Pause between messages: 10 per second, three times under Telegram's bulk limit (~30/s), /// so the bot's own pushes and replies still fit. public static readonly TimeSpan SendDelay = TimeSpan.FromMilliseconds(100); @@ -55,6 +57,9 @@ public partial class BroadcastCampaignService( [GeneratedRegex("^[A-Za-z0-9_.~%=&-]{0,256}$")] private static partial Regex ButtonQueryPattern(); + [GeneratedRegex(@"^[A-Za-z][A-Za-z0-9_+\-/]{1,63}$")] + private static partial Regex TimeZonePattern(); + /// How many people each audience has right now. Read-only. public async Task> CountAudiencesAsync( long ownerTelegramId, CancellationToken ct) @@ -91,7 +96,8 @@ public async Task PrepareNewSurveyAsync( new CampaignDraft { Key = key, MustBeNew = true, Audience = draft.Audience, Survey = draft.Survey, - ButtonText = draft.ButtonText, GiftDays = draft.GiftDays, GiftOfferDays = draft.GiftOfferDays + ButtonText = draft.ButtonText, GiftDays = draft.GiftDays, GiftOfferDays = draft.GiftOfferDays, + SendAtUtc = draft.SendAtUtc, SendAtTimeZone = draft.SendAtTimeZone }, sampleSize, dryRun, ownerTelegramId, ct); } @@ -119,7 +125,8 @@ public async Task PrepareNewBroadcastAsync( new CampaignDraft { Key = key, MustBeNew = true, Audience = draft.Audience, Message = draft.Message, ButtonText = draft.ButtonText, - ButtonQuery = draft.ButtonQuery, GiftDays = draft.GiftDays, GiftOfferDays = draft.GiftOfferDays + ButtonQuery = draft.ButtonQuery, GiftDays = draft.GiftDays, GiftOfferDays = draft.GiftOfferDays, + SendAtUtc = draft.SendAtUtc, SendAtTimeZone = draft.SendAtTimeZone }, sampleSize, dryRun, ownerTelegramId, ct); } @@ -154,7 +161,8 @@ public async Task> ListAsync(CancellationToken c deliveries.TryGetValue(c.Id, out var d); return new CampaignListItem( c.Key, c.IsSurvey, c.Message, c.Audience, c.CreatedAtUtc, c.ButtonText, c.GiftDays, - d?.Picked ?? 0, d?.Pending ?? 0, d?.Sent ?? 0, d?.Opened ?? 0, d?.Gifted ?? 0); + d?.Picked ?? 0, d?.Pending ?? 0, d?.Sent ?? 0, d?.Opened ?? 0, d?.Gifted ?? 0, + c.ScheduledAtUtc, c.ScheduledTimeZone); }).ToList(); } @@ -163,6 +171,8 @@ public async Task> ListAsync(CancellationToken c /// — take that many at random from those not picked yet; /// null — take everyone not picked yet (the "rest"). With only counts. /// Safe to repeat: people already in the campaign are never picked again. + /// With the campaign is scheduled instead: it is saved with its + /// time and nobody is picked — picks the audience when the time comes. /// public async Task PrepareAsync( CampaignDraft draft, int? sampleSize, bool dryRun, long ownerTelegramId, CancellationToken ct) @@ -190,6 +200,22 @@ public async Task PrepareAsync( if (giftOfferDays is < 1 or > MaxGiftOfferDays) return CampaignPrepareResult.Fail($"Срок, пока подарок можно получить, — от 1 до {MaxGiftOfferDays} дней."); + var now = DateTime.UtcNow; + // A moment without a zone is taken as UTC — never as the server's local time. + DateTime? sendAt = draft.SendAtUtc is { } at + ? at.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(at, DateTimeKind.Utc) : at.ToUniversalTime() + : null; + var timeZone = string.IsNullOrWhiteSpace(draft.SendAtTimeZone) ? null : draft.SendAtTimeZone.Trim(); + if (sendAt != null) + { + if (sampleSize != null) + return CampaignPrepareResult.Fail("По расписанию рассылка уходит всей группе. Пробной группе отправь сейчас, а остальным назначь время."); + if (sendAt <= now) return CampaignPrepareResult.Fail("Время отправки уже прошло. Назначь время в будущем."); + if (sendAt > now.AddDays(MaxScheduleDays)) + return CampaignPrepareResult.Fail($"Назначить отправку можно не дальше чем на {MaxScheduleDays} дней вперёд."); + if (timeZone != null && !TimeZonePattern().IsMatch(timeZone)) return CampaignPrepareResult.Fail("Неизвестный часовой пояс."); + } + string? surveyJson = null; if (draft.Survey != null) { @@ -222,6 +248,9 @@ public async Task PrepareAsync( // campaign, so nobody gets the message or the gift twice — which is the reason to add, not to start anew. if (campaign != null && campaign.Audience != draft.Audience && !draft.AnotherAudience) return CampaignPrepareResult.Fail($"Кампания «{key}» уже заведена для другой аудитории ({campaign.Audience}). Возьми другое имя."); + // A scheduled campaign goes to the audience it was made for — that is whom the sender picks when the time comes. + if (campaign != null && campaign.Audience != draft.Audience && sendAt != null) + return CampaignPrepareResult.Fail($"Кампания «{key}» заведена для другой группы ({campaign.Audience}). Для этой группы назначь время отдельной рассылке."); // A button carries the number of its option, and answers are counted by the question's id and the // option's text: all would point at something else if the form changed under messages already picked. if (campaign != null && campaign.Survey?.ToJson() != surveyJson) @@ -240,21 +269,14 @@ public async Task PrepareAsync( return CampaignPrepareResult.Fail($"У кампании «{key}» {waiting} получателей ждут отправки со старым текстом. Сначала отправь их."); } - var now = DateTime.UtcNow; - var users = await LoadReachableUsersAsync(ct); - var lastActive = await LoadLastActivityAsync(ct); - var payers = await LoadPayersAsync(ct); - var audience = users.Where(u => IsIn(u, draft.Audience, now, ownerTelegramId, lastActive, payers)).ToList(); - - var alreadyPicked = campaign == null - ? new HashSet() - : (await db.BroadcastDeliveries.Where(d => d.CampaignId == campaign.Id).Select(d => d.UserId).ToListAsync(ct)).ToHashSet(); - var candidates = audience.Where(u => !alreadyPicked.Contains(u.Id)).ToList(); + var (audience, candidates) = await LoadCandidatesAsync(campaign?.Id, draft.Audience, now, ownerTelegramId, ct); // Random order, so the sample is not "the oldest accounts" or "the newest". var shuffled = candidates.ToArray(); Random.Shared.Shuffle(shuffled); - var picked = sampleSize.HasValue ? shuffled.Take(sampleSize.Value).ToArray() : shuffled; + // A scheduled campaign picks nobody now: who is in the audience is decided when its time comes. + var picked = sendAt != null && !dryRun ? Array.Empty() + : sampleSize.HasValue ? shuffled.Take(sampleSize.Value).ToArray() : shuffled; var result = new CampaignPrepareResult { @@ -263,7 +285,8 @@ public async Task PrepareAsync( AudienceTotal = audience.Count, AlreadyInCampaign = audience.Count - candidates.Count, Picked = picked.Length, - LeftForLater = candidates.Count - picked.Length + LeftForLater = candidates.Count - picked.Length, + ScheduledAtUtc = sendAt }; if (dryRun) return result; @@ -277,8 +300,16 @@ public async Task PrepareAsync( campaign.ButtonQuery = buttonQuery; campaign.GiftDays = draft.GiftDays; campaign.SurveyJson = surveyJson; - // The offer runs from the day the campaign was created, whichever part a person is in. - campaign.GiftOfferEndsAtUtc = draft.GiftDays > 0 ? campaign.CreatedAtUtc.AddDays(giftOfferDays) : null; + // The offer runs from the day the campaign was created, whichever part a person is in; of a scheduled + // one — from the day it goes out. A later part never shortens what the earlier ones were promised. + var offerEnds = (sendAt ?? campaign.CreatedAtUtc).AddDays(giftOfferDays); + if (sendAt == null && campaign.GiftOfferEndsAtUtc > offerEnds) offerEnds = campaign.GiftOfferEndsAtUtc.Value; + campaign.GiftOfferEndsAtUtc = draft.GiftDays > 0 ? offerEnds : null; + if (sendAt != null) + { + campaign.ScheduledAtUtc = sendAt; + campaign.ScheduledTimeZone = timeZone; + } foreach (var user in picked) { @@ -305,11 +336,74 @@ public async Task PrepareAsync( return CampaignPrepareResult.Fail("Получателей этой кампании только что выбрал параллельный запрос. Обнови статус."); } - _logger.LogInformation("Campaign {Key}: picked {Picked} of {AudienceTotal} ({Audience}), sample={Sample}", - key, picked.Length, audience.Count, draft.Audience, sampleSize.HasValue); + if (sendAt != null) + _logger.LogInformation("Campaign {Key}: scheduled for {SendAt:u} ({Audience}, {AudienceTotal} people now)", + key, sendAt, draft.Audience, audience.Count); + else + _logger.LogInformation("Campaign {Key}: picked {Picked} of {AudienceTotal} ({Audience}), sample={Sample}", + key, picked.Length, audience.Count, draft.Audience, sampleSize.HasValue); return result; } + /// Who is in the audience right now, and who of them is not in the campaign yet. + private async Task<(List Audience, List Candidates)> LoadCandidatesAsync( + Guid? campaignId, BroadcastAudience audience, DateTime now, long ownerTelegramId, CancellationToken ct) + { + var users = await LoadReachableUsersAsync(ct); + var lastActive = await LoadLastActivityAsync(ct); + var payers = await LoadPayersAsync(ct); + var inAudience = users.Where(u => IsIn(u, audience, now, ownerTelegramId, lastActive, payers)).ToList(); + + var alreadyPicked = campaignId == null + ? new HashSet() + : (await db.BroadcastDeliveries.Where(d => d.CampaignId == campaignId).Select(d => d.UserId).ToListAsync(ct)).ToHashSet(); + return (inAudience, inAudience.Where(u => !alreadyPicked.Contains(u.Id)).ToList()); + } + + /// + /// Starts the campaigns whose scheduled time has come: picks everyone who is in the audience now and not + /// in the campaign yet, and hands the campaign over to . The recipients and + /// the "send to everyone" request are written in one transaction, so nobody sees a started campaign + /// without its recipients, and of several replicas exactly one starts it. Sends nothing itself. + /// Returns the keys of the campaigns started. + /// + public async Task> StartScheduledAsync(DateTime now, long ownerTelegramId, CancellationToken ct) + { + var due = await db.BroadcastCampaigns.AsNoTracking() + .Where(c => c.ScheduledAtUtc != null && c.ScheduledAtUtc <= now) + .OrderBy(c => c.ScheduledAtUtc) + .Select(c => new { c.Id, c.Key, c.Audience }) + .ToListAsync(ct); + + var started = new List(); + foreach (var campaign in due) + { + await using var transaction = await db.BeginTransactionAsync(ct); + if (!await db.TryStartScheduledCampaignAsync(campaign.Id, now, ct)) continue; + + var (audience, candidates) = await LoadCandidatesAsync(campaign.Id, campaign.Audience, now, ownerTelegramId, ct); + foreach (var user in candidates) + { + db.BroadcastDeliveries.Add(new BroadcastDelivery + { + Id = Guid.NewGuid(), + CampaignId = campaign.Id, + UserId = user.Id, + TelegramId = user.TelegramId, + Status = BroadcastDeliveryStatus.Pending, + CreatedAtUtc = now + }); + } + await db.SaveChangesAsync(ct); + await transaction.CommitAsync(ct); + + _logger.LogInformation("Campaign {Key}: its time has come, picked {Picked} of {AudienceTotal} ({Audience})", + campaign.Key, candidates.Count, audience.Count, campaign.Audience); + started.Add(campaign.Key); + } + return started; + } + /// /// Sends up to Pending messages of the campaign and stops. Call again /// for the next part. Stops early when Telegram asks to slow down (429) — the message it @@ -405,12 +499,15 @@ public async Task SendBatchAsync(string key, int limit, Canc return await GetStatusAsync(key, ct); } - /// Stops the background sending of the campaign; what is left stays Pending. Null — no such campaign. + /// Stops the background sending of the campaign and takes it off the schedule; what is left stays + /// Pending. Null — no such campaign. public async Task StopSendAllAsync(string key, CancellationToken ct) { var campaign = await db.BroadcastCampaigns.FirstOrDefaultAsync(c => c.Key == key, ct); if (campaign == null) return null; campaign.SendAllRequestedAtUtc = null; + campaign.ScheduledAtUtc = null; + campaign.ScheduledTimeZone = null; await db.SaveChangesAsync(ct); _logger.LogInformation("Campaign {Key}: sending to everyone stopped", key); return await GetStatusAsync(key, ct); @@ -481,6 +578,8 @@ public async Task SendRequestedAsync(CancellationToken ct) ButtonQuery = campaign.ButtonQuery, CreatedAtUtc = campaign.CreatedAtUtc, SendingAll = campaign.SendAllRequestedAtUtc != null, + ScheduledAtUtc = campaign.ScheduledAtUtc, + ScheduledTimeZone = campaign.ScheduledTimeZone, Total = rows.Count, Sample = rows.Count(r => r.IsSample), Pending = rows.Count(r => r.Status == BroadcastDeliveryStatus.Pending), @@ -721,6 +820,10 @@ public class CampaignDraft public bool AnotherAudience { get; init; } /// Refuse when a campaign with this key already exists (see ). public bool MustBeNew { get; init; } + /// Schedule the campaign for this moment instead of picking recipients now; null — pick now. + public DateTime? SendAtUtc { get; init; } + /// The time zone the owner named in ("Asia/Tbilisi") — kept to show it back. + public string? SendAtTimeZone { get; init; } } /// A gift of access given by a campaign: how many days and until when the person now has access. @@ -772,6 +875,8 @@ public class CampaignPrepareResult public int Picked { get; init; } /// In the audience, not picked yet. public int LeftForLater { get; init; } + /// The campaign was scheduled for this moment: nobody is picked until then. + public DateTime? ScheduledAtUtc { get; init; } public string? Error { get; init; } public static CampaignPrepareResult Fail(string error) => new() { Error = error }; @@ -780,7 +885,8 @@ public class CampaignPrepareResult /// Picked and not sent yet — above zero means the sending is unfinished. public record CampaignListItem( string Key, bool IsSurvey, string Message, BroadcastAudience Audience, DateTime CreatedAtUtc, string? ButtonText, int GiftDays, - int Picked, int Pending, int Sent, int Opened, int Gifted); + int Picked, int Pending, int Sent, int Opened, int Gifted, + DateTime? ScheduledAtUtc = null, string? ScheduledTimeZone = null); public class CampaignSendResult { @@ -809,6 +915,9 @@ public class CampaignStatus { /// The server is sending it to everyone picked by itself (). public bool SendingAll { get; init; } + /// When the campaign goes out by itself; null — it is not scheduled. + public DateTime? ScheduledAtUtc { get; init; } + public string? ScheduledTimeZone { get; init; } public string Key { get; init; } = ""; public BroadcastAudience Audience { get; init; } public string Message { get; init; } = ""; diff --git a/src/Application/Common/ITraleDbContext.cs b/src/Application/Common/ITraleDbContext.cs index cfcaffc4..f18920ed 100644 --- a/src/Application/Common/ITraleDbContext.cs +++ b/src/Application/Common/ITraleDbContext.cs @@ -68,6 +68,14 @@ Task TryClaimNotificationTriggerAsync( /// Task TryFinishCampaignSendAllAsync(Guid campaignId, CancellationToken cancellationToken); + /// + /// Atomically turns a campaign whose scheduled time has come into one being sent to everyone: clears the + /// schedule and sets the "send to everyone" request. Returns true only for the one caller that made + /// the move — only that caller picks the recipients. Inside a transaction the row stays locked until the + /// commit, so a second replica waits and then finds nothing to start. + /// + Task TryStartScheduledCampaignAsync(Guid campaignId, DateTime now, CancellationToken cancellationToken); + /// /// Atomically marks a campaign's gift as given to this recipient. Returns true only for /// the one caller that made the mark — only that caller may change the user's access. This is diff --git a/src/Domain/Entities/BroadcastCampaign.cs b/src/Domain/Entities/BroadcastCampaign.cs index f6b691c2..df8dac58 100644 --- a/src/Domain/Entities/BroadcastCampaign.cs +++ b/src/Domain/Entities/BroadcastCampaign.cs @@ -43,6 +43,15 @@ public class BroadcastCampaign /// "stop". The background sender works through such campaigns whether or not the admin page stays open. public DateTime? SendAllRequestedAtUtc { get; set; } + /// When the campaign goes out by itself; null — it is not scheduled. At that moment the background + /// sender picks everyone in who is not in the campaign yet and sends to all picked. + /// The recipients are decided then, not when the owner set the time: whoever left the audience in between + /// (paid, for one) gets nothing, whoever joined it does. Cleared when the sending starts or by "stop". + public DateTime? ScheduledAtUtc { get; set; } + + /// The time zone the owner named the moment in ("Asia/Tbilisi") — only to show it back the same way. + public string? ScheduledTimeZone { get; set; } + public bool IsSurvey => SurveyJson != null; public SurveyForm? Survey => SurveyForm.FromJson(SurveyJson); diff --git a/src/Persistence/Configurations/BroadcastCampaignConfiguration.cs b/src/Persistence/Configurations/BroadcastCampaignConfiguration.cs index 5a013b3a..f343f06a 100644 --- a/src/Persistence/Configurations/BroadcastCampaignConfiguration.cs +++ b/src/Persistence/Configurations/BroadcastCampaignConfiguration.cs @@ -15,6 +15,7 @@ public void Configure(EntityTypeBuilder builder) builder.Property(c => c.ButtonText).HasMaxLength(64); builder.Property(c => c.ButtonQuery).HasMaxLength(256); builder.Property(c => c.SurveyJson).HasColumnType("jsonb"); + builder.Property(c => c.ScheduledTimeZone).HasMaxLength(64); builder.Ignore(c => c.IsSurvey); builder.Ignore(c => c.Survey); } diff --git a/src/Persistence/Migrations/20261110105200_AddCampaignSchedule.Designer.cs b/src/Persistence/Migrations/20261110105200_AddCampaignSchedule.Designer.cs new file mode 100644 index 00000000..e4e63e11 --- /dev/null +++ b/src/Persistence/Migrations/20261110105200_AddCampaignSchedule.Designer.cs @@ -0,0 +1,1823 @@ +// +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("20261110105200_AddCampaignSchedule")] + partial class AddCampaignSchedule + { + /// + 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.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.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/20261110105200_AddCampaignSchedule.cs b/src/Persistence/Migrations/20261110105200_AddCampaignSchedule.cs new file mode 100644 index 00000000..6dda2500 --- /dev/null +++ b/src/Persistence/Migrations/20261110105200_AddCampaignSchedule.cs @@ -0,0 +1,40 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Persistence.Migrations +{ + /// + public partial class AddCampaignSchedule : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ScheduledAtUtc", + table: "BroadcastCampaigns", + type: "timestamp with time zone", + nullable: true); + + migrationBuilder.AddColumn( + name: "ScheduledTimeZone", + table: "BroadcastCampaigns", + type: "character varying(64)", + maxLength: 64, + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "ScheduledAtUtc", + table: "BroadcastCampaigns"); + + migrationBuilder.DropColumn( + name: "ScheduledTimeZone", + table: "BroadcastCampaigns"); + } + } +} diff --git a/src/Persistence/Migrations/TraleDbContextModelSnapshot.cs b/src/Persistence/Migrations/TraleDbContextModelSnapshot.cs index d0f3f91a..944954d1 100644 --- a/src/Persistence/Migrations/TraleDbContextModelSnapshot.cs +++ b/src/Persistence/Migrations/TraleDbContextModelSnapshot.cs @@ -136,6 +136,13 @@ protected override void BuildModel(ModelBuilder modelBuilder) .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"); diff --git a/src/Persistence/TraleDbContext.cs b/src/Persistence/TraleDbContext.cs index b1176713..d463e3a8 100644 --- a/src/Persistence/TraleDbContext.cs +++ b/src/Persistence/TraleDbContext.cs @@ -109,6 +109,26 @@ public async Task TryFinishCampaignSendAllAsync(Guid campaignId, Cancellat return true; } + public async Task TryStartScheduledCampaignAsync(Guid campaignId, DateTime now, CancellationToken cancellationToken) + { + if (Database.IsNpgsql()) + { + var affected = await Database.ExecuteSqlInterpolatedAsync($""" + UPDATE "BroadcastCampaigns" SET "ScheduledAtUtc" = NULL, "SendAllRequestedAtUtc" = {now} + WHERE "Id" = {campaignId} AND "ScheduledAtUtc" IS NOT NULL AND "ScheduledAtUtc" <= {now} + """, cancellationToken); + return affected == 1; + } + + // Non-relational providers (EF in-memory unit tests): single-threaded, no atomicity needed. + var campaign = await BroadcastCampaigns.FirstOrDefaultAsync(c => c.Id == campaignId, cancellationToken); + if (campaign?.ScheduledAtUtc == null || campaign.ScheduledAtUtc > now) return false; + campaign.ScheduledAtUtc = null; + campaign.SendAllRequestedAtUtc = now; + await SaveChangesAsync(cancellationToken); + return true; + } + public async Task TryClaimBroadcastDeliveryAsync(Guid deliveryId, CancellationToken cancellationToken) { if (Database.IsNpgsql()) diff --git a/src/Trale/Controllers/AdminController.cs b/src/Trale/Controllers/AdminController.cs index e08eca56..e0d3c807 100644 --- a/src/Trale/Controllers/AdminController.cs +++ b/src/Trale/Controllers/AdminController.cs @@ -121,9 +121,10 @@ public async Task Campaigns( campaigns = all.Where(c => surveys == null || c.IsSurvey == surveys).Select(c => new { c.Key, c.IsSurvey, c.Message, audience = AudienceName(c.Audience), c.CreatedAtUtc, c.ButtonText, c.GiftDays, - c.Picked, c.Pending, c.Sent, c.Opened, c.Gifted, - // draft — nobody picked yet; running — picked people still wait; done — everyone picked was handled. - state = c.Picked == 0 ? "draft" : c.Pending > 0 ? "running" : "done" + c.Picked, c.Pending, c.Sent, c.Opened, c.Gifted, c.ScheduledAtUtc, c.ScheduledTimeZone, + // scheduled — goes out by itself at its time; draft — nobody picked yet; running — picked people + // still wait; done — everyone picked was handled. + state = c.ScheduledAtUtc != null ? "scheduled" : c.Picked == 0 ? "draft" : c.Pending > 0 ? "running" : "done" }) }); } @@ -733,6 +734,11 @@ public class CampaignPrepareRequest /// The survey builder starting a new survey: with an empty the server names the /// campaign itself — survey-2026-10-<slug>, with a number when taken — and returns the key. public string? NewSurveySlug { get; set; } + /// Send by itself at this moment (UTC) instead of picking recipients now: the campaign is saved with + /// its time, and the server picks everyone in the audience and sends when the time comes. Null — as before. + public DateTime? SendAtUtc { get; set; } + /// The time zone the owner chose the moment in ("Asia/Tbilisi") — to show it back the same way. + public string? SendAtTimeZone { get; set; } } /// Ready-made surveys for the survey builder and the answer buttons it offers by one tap. @@ -772,7 +778,8 @@ public async Task CampaignPrepare( Key = req.Key, Audience = audience, Message = req.Message, ButtonText = req.ButtonText, ButtonQuery = req.ButtonQuery, GiftDays = req.GiftDays, GiftOfferDays = req.GiftOfferDays, Survey = req.Survey, - AnotherAudience = req.AnotherAudience + AnotherAudience = req.AnotherAudience, + SendAtUtc = req.SendAtUtc, SendAtTimeZone = req.SendAtTimeZone }; var unnamed = string.IsNullOrWhiteSpace(req.Key); var result = unnamed && req.NewSurveySlug != null @@ -835,6 +842,7 @@ public async Task CampaignStatus( private static object? MapCampaignStatus(CampaignStatus? s) => s == null ? null : new { s.Key, audience = AudienceName(s.Audience), s.Message, s.ButtonText, s.ButtonQuery, s.CreatedAtUtc, s.SendingAll, + s.ScheduledAtUtc, s.ScheduledTimeZone, s.Total, s.Sample, s.Pending, s.Sent, s.Blocked, s.Rejected, s.Unknown, s.Opened, s.GiftDays, s.GiftOfferEndsAtUtc, s.Gifted, s.PlayedVerbSession, s.FinishedVerbSession, s.PaidAfterOpen, // In the order of the buttons, also before anyone has answered — this is how the survey builder gets a survey back. diff --git a/src/Trale/HostedServices/CampaignSendWorker.cs b/src/Trale/HostedServices/CampaignSendWorker.cs index e200615b..5a7f9682 100644 --- a/src/Trale/HostedServices/CampaignSendWorker.cs +++ b/src/Trale/HostedServices/CampaignSendWorker.cs @@ -11,8 +11,8 @@ namespace Trale.HostedServices; /// /// Sends the campaigns the owner asked to send to everyone picked ("send to everyone" in the admin), -/// batch by batch, so the admin page does not have to stay open. Sends nothing else: a campaign -/// without that request is never touched. When a campaign has no one left waiting, the owner gets +/// batch by batch, so the admin page does not have to stay open, and starts the campaigns whose +/// scheduled time has come. Sends nothing else: a campaign without that request or a due time is never touched. When a campaign has no one left waiting, the owner gets /// a bot message with how it went. After a restart it carries on where it stopped — the request /// and every recipient's state are in the database. /// @@ -36,6 +36,14 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) var wait = IdleInterval; try { + // Scheduled campaigns whose time has come get their recipients and join the ones being sent. + // Its own scope: it loads every reachable user, which the sending below has no use for. + await using (var startScope = scopeFactory.CreateAsyncScope()) + { + await startScope.ServiceProvider.GetRequiredService() + .StartScheduledAsync(DateTime.UtcNow, OwnerTelegramId, stoppingToken); + } + await using var scope = scopeFactory.CreateAsyncScope(); var campaigns = scope.ServiceProvider.GetRequiredService(); var round = await campaigns.SendRequestedAsync(stoppingToken); @@ -62,9 +70,11 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) logger.LogInformation("CampaignSendWorker stopped"); } + private long OwnerTelegramId => botConfig.OwnerTelegramId != 0 ? botConfig.OwnerTelegramId : DefaultOwnerTelegramId; + private Task TellOwnerAsync(ICampaignMessageSender sender, CampaignStatus s) { - var owner = botConfig.OwnerTelegramId != 0 ? botConfig.OwnerTelegramId : DefaultOwnerTelegramId; + var owner = OwnerTelegramId; var text = $"Рассылка «{s.Key}» разослана.\nДошло: {s.Sent} из {s.Total}" + (s.Blocked > 0 ? $"\nЗаблокировали бота: {s.Blocked}" : "") + (s.Rejected > 0 ? $"\nTelegram не принял: {s.Rejected}" : "") diff --git a/src/Trale/miniapp-src/e2e/admin.spec.ts b/src/Trale/miniapp-src/e2e/admin.spec.ts index a97f4dda..b4f0e595 100644 --- a/src/Trale/miniapp-src/e2e/admin.spec.ts +++ b/src/Trale/miniapp-src/e2e/admin.spec.ts @@ -163,6 +163,8 @@ interface Calls { prepared: any[]; sent: string[]; userQueries: URLSearchParams[ async function setup(page: Page, opts: { owner?: boolean; fail?: string; slow?: string } = {}): Promise { const calls: Calls = { prepared: [], sent: [], userQueries: [], back: 0, verbs: [] } + // Рассылка, которую назначили на время в этом тесте: сервер помнит её, пока расписание не отменят. + let scheduled: Record | null = null const owner = opts.owner ?? true await page.addInitScript(() => { ;(window as any).Telegram = { @@ -207,15 +209,26 @@ async function setup(page: Page, opts: { owner?: boolean; fail?: string; slow?: } if (/^users\/\d+$/.test(path)) return ok({ ...userCard, telegramId: Number(path.split('/')[1]) }) if (path === 'payments') return ok(payments) - if (path === 'campaigns') return ok({ campaigns: campaignList }) + if (path === 'campaigns') return ok({ campaigns: scheduled ? [{ ...campaignList[2], ...scheduled, createdAtUtc: at(9, '08:00'), picked: 0, pending: 0, state: 'scheduled' }, ...campaignList] : campaignList }) if (path === 'campaigns/audiences') return ok({ accessEnded: 553, onTrial: 17, paying: 3, proLapsed: 0, owner: 1, activeLately: 61, inactiveLong: 512 }) if (path === 'campaigns/prepare') { const body = route.request().postDataJSON() calls.prepared.push(body) const key = body.key || (body.newBroadcastSuffix ? `${BROADCAST}-${body.newBroadcastSuffix}` : `${BROADCAST}-2`) + // По расписанию: кампания записана со временем, получателей никто не выбирал. + if (body.sendAtUtc && !body.dryRun) { + scheduled = { key, audience: body.audience, message: body.message, buttonText: body.buttonText, giftDays: body.giftDays, scheduledAtUtc: body.sendAtUtc, scheduledTimeZone: body.sendAtTimeZone } + return ok({ key, dryRun: false, audienceTotal: 61, alreadyInCampaign: 0, picked: 0, leftForLater: 61, scheduledAtUtc: body.sendAtUtc }) + } return ok({ key, dryRun: body.dryRun, audienceTotal: 61, alreadyInCampaign: body.anotherAudience ? 21 : 0, picked: body.audience === 'owner' ? 1 : 40, leftForLater: 0 }) } if (path.endsWith('/send')) { calls.sent.push(path.replace('campaigns/', '').replace('/send', '')); return ok({ sent: 1, blocked: 0, rejected: 0, unknown: 0, retryAfterSeconds: 0, status: campaignStatus }) } + if (scheduled && path === `campaigns/${scheduled.key}/stop`) { + const stopped = { ...campaignStatus, ...scheduled, total: 0, sample: 0, pending: 0, sent: 0, blocked: 0, opened: 0, gifted: 0, scheduledAtUtc: null, scheduledTimeZone: null } + scheduled = null + return ok(stopped) + } + if (scheduled && path === `campaigns/${scheduled.key}`) return ok({ ...campaignStatus, ...scheduled, total: 0, sample: 0, pending: 0, sent: 0, blocked: 0, opened: 0, gifted: 0 }) if (path.startsWith('campaigns/')) return ok(campaignStatus) if (path === 'surveys/presets') return ok(kit) if (path.startsWith('feedback/surveys/')) return ok(surveyResults) @@ -553,6 +566,68 @@ test('a new broadcast is a focused flow: no tab bar, steps, the main button pinn await expect(title(page)).toHaveText('Рассылки') }) +test('a broadcast is scheduled for a day, an hour and a time zone, shows up as scheduled and can be called off', async ({ page }) => { + const calls = await setup(page) + await openAdmin(page) + await tab(page, 'broadcasts').click() + await page.getByTestId('broadcast-new').click() + await page.getByLabel('Текст сообщения').fill('До повышения цен осталось 3 дня.') + for (let i = 0; i < 3; i++) await page.getByTestId('broadcast-next').click() + await page.getByTestId('broadcast-audience-activeLately').click() + await page.getByRole('radio', { name: /Сразу всем/ }).click() + await page.getByTestId('broadcast-next').click() + await expect(page.getByTestId('broadcast-step-title')).toHaveText('Отправка') + + // Сначала стоит завтра, полдень по Тбилиси; назначаем день, час и пояс — по часам Берлина. + const plan = page.getByTestId('broadcast-schedule') + await plan.scrollIntoViewIfNeeded() + await expect(page.getByTestId('broadcast-schedule-date')).not.toHaveValue('') + await expect(page.getByTestId('broadcast-schedule-time')).toHaveValue('12:00') + await expect(page.getByTestId('broadcast-schedule-zone')).toHaveValue('Asia/Tbilisi') + await page.getByTestId('broadcast-schedule-date').fill('2099-07-01') + await page.getByTestId('broadcast-schedule-time').fill('12:30') + await page.getByTestId('broadcast-schedule-zone').selectOption('Europe/Berlin') + await fits(page) + await shot(page, 'admin-19-broadcast-schedule') + + let asked = '' + page.once('dialog', d => { asked = d.message(); void d.accept() }) + await plan.click() + const state = page.getByTestId('broadcast-scheduled') + await expect(state).toContainText('Запланирована на 01.07.2099 12:30 (Берлин)') + expect(asked).toContain('ЗАПЛАНИРОВАТЬ на 01.07.2099 12:30 (Берлин)?') + expect(asked).toContain('До повышения цен осталось 3 дня.') + await expect(state).toContainText('Мини-апп можно закрыть') + await expect(page.getByTestId('broadcast-note')).toHaveCount(0) + // Пока она ждёт своего часа, на экране нет ни выбора получателей, ни отправки руками. + for (const gone of ['broadcast-schedule', 'broadcast-pick', 'broadcast-send-all', 'broadcast-another']) await expect(page.getByTestId(gone)).toHaveCount(0) + const sent = calls.prepared.at(-1) as Record + expect(sent).toMatchObject({ audience: 'activeLately', sampleSize: null, dryRun: false, sendAtUtc: '2099-07-01T10:30:00.000Z', sendAtTimeZone: 'Europe/Berlin' }) + expect(calls.sent).toEqual([]) + await fits(page) + await shot(page, 'admin-20-broadcast-scheduled') + + // В списке она «запланирована», со временем по тому же поясу. + await page.getByTestId('admin-close').click() + const row = page.getByTestId(`broadcast-${BROADCAST}-2`) + await expect(row).toContainText('запланирована') + await expect(row).toContainText('занимались за последние 30 дней · уйдёт сама 01.07.2099 12:30 (Берлин)') + await expect(row).toContainText('с кнопкой «Открыть TraleBot»') + await shot(page, 'admin-21-broadcasts-scheduled') + + // Открыть и отменить: расписания больше нет, время можно назначить заново. + await row.click() + await expect(state).toContainText('01.07.2099 12:30 (Берлин)') + page.once('dialog', d => void d.accept()) + await page.getByTestId('broadcast-schedule-cancel').click() + await expect(page.getByTestId('broadcast-note')).toHaveText('Расписание отменил. Сообщения не ушли.') + await expect(state).toHaveCount(0) + await expect(page.getByTestId('broadcast-schedule')).toBeVisible() + await expect(page.getByTestId('broadcast-pick')).toBeVisible() + await page.getByTestId('admin-close').click() + await expect(page.getByTestId(`broadcast-${BROADCAST}-2`)).toHaveCount(0) +}) + test('the survey builder is a focused flow too, and keeps its draft', async ({ page }) => { await setup(page) await page.goto('/?playwright=1&screen=admin-surveys') diff --git a/src/Trale/miniapp-src/src/admin/pastedBroadcast.test.ts b/src/Trale/miniapp-src/src/admin/pastedBroadcast.test.ts index 201f5f57..923b9a1e 100644 --- a/src/Trale/miniapp-src/src/admin/pastedBroadcast.test.ts +++ b/src/Trale/miniapp-src/src/admin/pastedBroadcast.test.ts @@ -17,10 +17,19 @@ describe('готовая рассылка одним куском', () => { expect(parsePastedBroadcast(READY)).toEqual({ name: 'myday-back', audience: 'inactiveLong', sample: 50, giftDays: 7, button: 'Посмотреть первую серию', query: 'moduleId=my-day&lessonId=1', - message: READY.slice(READY.indexOf('---') + 4) + message: READY.slice(READY.indexOf('---') + 4), when: null }) }) + it('takes the day, the hour and the zone to send it by itself; Tbilisi when no zone is named', () => { + expect(parsePastedBroadcast('кому: neverPaid\nкогда: 28.11.2026 12:00\nпояс: Берлин\n---\nПривет')) + .toMatchObject({ when: { date: '2026-11-28', time: '12:00', zone: 'Europe/Berlin' }, sample: null }) + expect(parsePastedBroadcast('кому: neverPaid\nкогда: 1.12.2026 9:30\n---\nПривет')) + .toMatchObject({ when: { date: '2026-12-01', time: '09:30', zone: 'Asia/Tbilisi' } }) + expect(parsePastedBroadcast('кому: neverPaid\nкогда: 28.11.2026 12:00\nпояс: Europe/Paris\n---\nПривет')) + .toMatchObject({ when: { zone: 'Europe/Paris' } }) + }) + it('takes the group by its Russian name, and without a sample sends to everyone', () => { const r = parsePastedBroadcast('кому: не занимались больше 30 дней\n---\nПривет') expect(r).toMatchObject({ audience: 'inactiveLong', sample: null, button: null, giftDays: 0, name: '' }) @@ -35,7 +44,12 @@ describe('готовая рассылка одним куском', () => { ['кому: inactiveLong\nподарок: 7\n---\nПривет', 'по кнопке'], ['кому: inactiveLong\nкнопка: Открыть\nадрес: screen=verbs lesson\n---\nПривет', 'Адрес'], ['кому: inactiveLong\nимя: Мой День\n---\nПривет', 'Имя'], - ['кому: inactiveLong\nпроба: много\n---\nПривет', 'Проба'] + ['кому: inactiveLong\nпроба: много\n---\nПривет', 'Проба'], + ['кому: inactiveLong\nкогда: завтра в полдень\n---\nПривет', 'Когда'], + ['кому: inactiveLong\nкогда: 31.11.2026 12:00\n---\nПривет', 'Когда'], + ['кому: inactiveLong\nпояс: Тбилиси\n---\nПривет', 'времени нет'], + ['кому: inactiveLong\nкогда: 28.11.2026 12:00\nпояс: Марс\n---\nПривет', 'Пояс'], + ['кому: inactiveLong\nпроба: 50\nкогда: 28.11.2026 12:00\n---\nПривет', 'всей группе'] ])('rejects a broken paste with a reason: %s', (raw, reason) => { expect(parsePastedBroadcast(raw)).toContain(reason) }) diff --git a/src/Trale/miniapp-src/src/admin/pastedBroadcast.ts b/src/Trale/miniapp-src/src/admin/pastedBroadcast.ts index 809d976d..544c639c 100644 --- a/src/Trale/miniapp-src/src/admin/pastedBroadcast.ts +++ b/src/Trale/miniapp-src/src/admin/pastedBroadcast.ts @@ -1,5 +1,6 @@ import type { CampaignAudience } from '../api' import { AUDIENCES } from './words' +import { findZone, wallToUtc, ZONES } from './schedule' // Готовая рассылка одним куском текста — чтобы не набирать её по шагам. Сверху параметры «ключ: значение», // после строки «---» — само сообщение: @@ -10,10 +11,14 @@ import { AUDIENCES } from './words' // подарок: 7 // кнопка: Посмотреть первую серию // адрес: moduleId=my-day&lessonId=1 +// когда: 28.11.2026 12:00 +// пояс: Тбилиси // --- // Текст сообщения, сколько угодно абзацев. // // Обязательны «кому» и текст. Без «кнопки» — сообщение без кнопки; без «пробы» — сразу всем. +// «когда» — день и час, в который рассылка уйдёт сама (на экране отправки останется нажать «Запланировать»); +// без «пояса» время считается по Тбилиси. export interface PastedBroadcast { name: string @@ -25,10 +30,15 @@ export interface PastedBroadcast { button: string | null query: string message: string + /** Когда отправить саму: день (ГГГГ-ММ-ДД), время (ЧЧ:ММ) и пояс; null — время не задано. */ + when: { date: string; time: string; zone: string } | null } -const KEYS: Record = { - 'имя': 'name', 'кому': 'audience', 'проба': 'sample', 'подарок': 'giftDays', 'кнопка': 'button', 'адрес': 'query' +type Field = keyof PastedBroadcast | 'zone' + +const KEYS: Record = { + 'имя': 'name', 'кому': 'audience', 'проба': 'sample', 'подарок': 'giftDays', 'кнопка': 'button', 'адрес': 'query', + 'когда': 'when', 'пояс': 'zone' } /** Текст из буфера обмена; '' — если клиент Telegram читать буфер не даёт (тогда вставляют долгим нажатием в поле). */ @@ -42,7 +52,7 @@ export function parsePastedBroadcast(raw: string): PastedBroadcast | string { const cut = lines.findIndex(l => l.trim() === '---') if (cut < 0) return 'Нет строки «---» между параметрами и текстом сообщения.' - const fields: Partial> = {} + const fields: Partial> = {} for (const line of lines.slice(0, cut)) { if (!line.trim()) continue const m = /^\s*([^:]+?)\s*:\s*(.*?)\s*$/.exec(line) @@ -75,5 +85,18 @@ export function parsePastedBroadcast(raw: string): PastedBroadcast | string { if (!(Number.isInteger(giftDays) && giftDays >= 0 && giftDays <= 30)) return 'Подарок — число дней от 0 до 30.' if (giftDays > 0 && !button) return 'Подарок получают по кнопке — добавь строку «кнопка: …».' - return { name, audience, sample, giftDays, button, query, message } + let when: PastedBroadcast['when'] = null + if (fields.zone && !fields.when) return 'Пояс есть, а времени нет — добавь строку «когда: 28.11.2026 12:00».' + if (fields.when) { + const m = /^(\d{1,2})\.(\d{1,2})\.(\d{4})\s+(\d{1,2}):(\d{2})$/.exec(fields.when) + const zone = fields.zone ? findZone(fields.zone) : ZONES[0].id + if (!zone) return `Пояс — один из: ${ZONES.map(z => z.name).join(', ')} — или имя вида Europe/Paris.` + const date = m ? `${m[3]}-${m[2].padStart(2, '0')}-${m[1].padStart(2, '0')}` : '' + const time = m ? `${m[4].padStart(2, '0')}:${m[5]}` : '' + if (!m || !wallToUtc(date, time, zone)) return 'Когда — день и время вида 28.11.2026 12:00.' + if (sample !== null) return 'По расписанию рассылка уходит всей группе — убери строку «проба».' + when = { date, time, zone } + } + + return { name, audience, sample, giftDays, button, query, message, when } } diff --git a/src/Trale/miniapp-src/src/admin/schedule.test.ts b/src/Trale/miniapp-src/src/admin/schedule.test.ts new file mode 100644 index 00000000..15ddea6e --- /dev/null +++ b/src/Trale/miniapp-src/src/admin/schedule.test.ts @@ -0,0 +1,31 @@ +import { describe, it, expect } from 'vitest' +import { findZone, scheduledText, wallToUtc } from './schedule' + +describe('время отправки рассылки', () => { + it.each([ + ['2026-11-28', '12:00', 'Asia/Tbilisi', '2026-11-28T08:00:00.000Z'], + ['2026-11-28', '12:00', 'Europe/Moscow', '2026-11-28T09:00:00.000Z'], + ['2026-11-28', '12:00', 'Europe/Berlin', '2026-11-28T11:00:00.000Z'], + ['2026-07-01', '12:00', 'Europe/Berlin', '2026-07-01T10:00:00.000Z'], + ['2026-12-01', '00:30', 'Asia/Tbilisi', '2026-11-30T20:30:00.000Z'], + ['2026-11-28', '9:05', 'UTC', '2026-11-28T09:05:00.000Z'] + ])('%s %s by the clock of %s is %s', (date, time, zone, utc) => { + expect(wallToUtc(date, time, zone)!.toISOString()).toBe(utc) + }) + + it.each([['2026-11-31', '12:00'], ['2026-11-28', '24:00'], ['', '12:00'], ['2026-11-28', '']])('there is no such day or time: %s %s', (date, time) => { + expect(wallToUtc(date, time, 'Asia/Tbilisi')).toBeNull() + }) + + it('shows the moment back by the clock of the zone it was set in', () => { + expect(scheduledText('2026-11-28T08:00:00Z', 'Asia/Tbilisi')).toBe('28.11.2026 12:00 (Тбилиси)') + expect(scheduledText('2026-11-28T08:00:00Z', 'Europe/Berlin')).toBe('28.11.2026 09:00 (Берлин)') + expect(scheduledText('2026-11-28T08:00:00Z', null)).toBe('28.11.2026 08:00 (UTC)') + }) + + it('finds a zone by its Russian name or its id', () => { + expect(findZone('тбилиси')).toBe('Asia/Tbilisi') + expect(findZone('Europe/Paris')).toBe('Europe/Paris') + expect(findZone('Марс')).toBeNull() + }) +}) diff --git a/src/Trale/miniapp-src/src/admin/schedule.ts b/src/Trale/miniapp-src/src/admin/schedule.ts new file mode 100644 index 00000000..33a34cbc --- /dev/null +++ b/src/Trale/miniapp-src/src/admin/schedule.ts @@ -0,0 +1,60 @@ +// Время отправки рассылки: владелец называет день и час «по часам» выбранного пояса, сервер хранит момент в UTC. + +/** Пояса, которые предлагает экран; первый — по умолчанию. */ +export const ZONES = [ + { id: 'Asia/Tbilisi', name: 'Тбилиси' }, + { id: 'Europe/Moscow', name: 'Москва' }, + { id: 'Europe/Berlin', name: 'Берлин' }, + { id: 'Europe/London', name: 'Лондон' }, + { id: 'UTC', name: 'UTC' } +] + +export const zoneName = (id: string | null | undefined) => ZONES.find(z => z.id === id)?.name ?? id ?? 'UTC' + +/** Пояс по названию из списка или по имени вида Asia/Tbilisi; null — такого нет. */ +export function findZone(text: string): string | null { + const t = text.trim().toLowerCase() + const known = ZONES.find(z => z.name.toLowerCase() === t || z.id.toLowerCase() === t) + if (known) return known.id + try { return new Intl.DateTimeFormat('en-US', { timeZone: text.trim() }).resolvedOptions().timeZone } catch { return null } +} + +/** Что показывают часы в этом поясе в данный момент — как число миллисекунд «будто это UTC». */ +function wallMs(at: number, zone: string): number { + const parts = new Intl.DateTimeFormat('en-US', { + timeZone: zone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' + }).formatToParts(new Date(at)) + const n = (type: string) => Number(parts.find(p => p.type === type)!.value) + return Date.UTC(n('year'), n('month') - 1, n('day'), n('hour'), n('minute'), n('second')) +} + +/** Момент, когда часы в поясе покажут этот день (ГГГГ-ММ-ДД) и это время (ЧЧ:ММ); null — такой даты или времени нет. */ +export function wallToUtc(date: string, time: string, zone: string): Date | null { + const d = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date) + const t = /^(\d{1,2}):(\d{2})$/.exec(time) + if (!d || !t) return null + const [year, month, dayOf, hour, minute] = [+d[1], +d[2], +d[3], +t[1], +t[2]] + if (hour > 23 || minute > 59) return null + const wall = Date.UTC(year, month - 1, dayOf, hour, minute) + const check = new Date(wall) + if (check.getUTCMonth() !== month - 1 || check.getUTCDate() !== dayOf) return null // 31 ноября + try { + // Сдвиг пояса берём в искомый момент: два шага хватает и на переводе часов. + let at = wall - (wallMs(wall, zone) - wall) + at = wall - (wallMs(at, zone) - at) + return new Date(at) + } catch { return null } +} + +/** «28.11.2026 12:00 (Тбилиси)» — момент по часам пояса, в котором его назначали. */ +export function scheduledText(iso: string, zone: string | null | undefined): string { + const id = zone && findZone(zone) ? zone : 'UTC' + const text = new Date(iso).toLocaleString('ru-RU', { timeZone: id, day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }).replace(',', '') + return `${text} (${zoneName(id)})` +} + +/** Завтрашний день по часам устройства, «2026-11-28» — с него начинается выбор дня отправки. */ +export function tomorrow(): string { + const d = new Date(Date.now() + 24 * 3600 * 1000) + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` +} diff --git a/src/Trale/miniapp-src/src/api.ts b/src/Trale/miniapp-src/src/api.ts index d15043b6..e09dbbe6 100644 --- a/src/Trale/miniapp-src/src/api.ts +++ b/src/Trale/miniapp-src/src/api.ts @@ -582,6 +582,10 @@ export interface CampaignStatusDto { buttonQuery: string | null /** Сервер сейчас сам рассылает её всем выбранным. */ sendingAll?: boolean + /** Когда уйдёт сама (UTC); null — время не назначено. Получателей сервер выбирает в этот момент. */ + scheduledAtUtc?: string | null + /** Пояс, в котором владелец назначал время (Asia/Tbilisi). */ + scheduledTimeZone?: string | null total: number sample: number pending: number @@ -611,6 +615,8 @@ export interface CampaignPrepareDto { alreadyInCampaign: number picked: number leftForLater: number + /** Рассылка записана на это время (UTC): получатели пока не выбраны. */ + scheduledAtUtc?: string | null } export const adminCampaigns = { @@ -637,6 +643,10 @@ export const adminCampaigns = { anotherAudience?: boolean /** Конструктор начинает новый опрос: при пустом key сервер сам называет кампанию и возвращает имя в ответе. */ newSurveySlug?: string | null + /** Отправить саму в этот момент (UTC, ISO с «Z») вместо выбора получателей сейчас: сервер выберет всю группу, когда время придёт. */ + sendAtUtc?: string | null + /** Пояс, в котором назначено время, — чтобы показать его так же. */ + sendAtTimeZone?: string | null }) => request('/api/admin/campaigns/prepare', { method: 'POST', body: JSON.stringify(body) }), /** Отправить следующую порцию уже выбранных получателей. */ send: (key: string, limit: number) => @@ -647,7 +657,7 @@ export const adminCampaigns = { /** Сервер сам рассылает всем выбранным, порциями; мини-апп можно закрыть — бот напишет, когда закончит. */ sendAll: (key: string) => request(`/api/admin/campaigns/${encodeURIComponent(key)}/send-all`, { method: 'POST' }), - /** Остановить рассылку сервером; кто не получил — остаются ждать. */ + /** Остановить рассылку сервером и снять её с расписания; кто не получил — остаются ждать. */ stop: (key: string) => request(`/api/admin/campaigns/${encodeURIComponent(key)}/stop`, { method: 'POST' }), status: (key: string) => request(`/api/admin/campaigns/${encodeURIComponent(key)}`), @@ -669,8 +679,11 @@ export interface CampaignListItemDto { sent: number opened: number gifted: number - /** draft — получателей ещё не выбирали; running — выбранные ждут отправки; done — все выбранные обработаны. */ - state: 'draft' | 'running' | 'done' + scheduledAtUtc?: string | null + scheduledTimeZone?: string | null + /** scheduled — уйдёт сама в назначенное время; draft — получателей ещё не выбирали; running — выбранные ждут отправки; + * done — все выбранные обработаны. */ + state: 'scheduled' | 'draft' | 'running' | 'done' } // ── Админка: обзор, люди, оплаты ── diff --git a/src/Trale/miniapp-src/src/screens/AdminBroadcastScreen.tsx b/src/Trale/miniapp-src/src/screens/AdminBroadcastScreen.tsx index ca6b577c..f59e2d76 100644 --- a/src/Trale/miniapp-src/src/screens/AdminBroadcastScreen.tsx +++ b/src/Trale/miniapp-src/src/screens/AdminBroadcastScreen.tsx @@ -4,6 +4,7 @@ import { AUDIENCES, audienceName } from '../admin/words' import { adminBack, setInnerBack } from '../admin/adminNav' import { draft as drafts, useDraft, useFocusMode } from '../admin/useKept' import { parsePastedBroadcast, readClipboard } from '../admin/pastedBroadcast' +import { scheduledText, tomorrow, wallToUtc, zoneName, ZONES } from '../admin/schedule' import { adminCampaigns, ApiError, type CampaignAudience, type CampaignStatusDto } from '../api' import type { Screen } from '../types' @@ -11,7 +12,8 @@ import type { Screen } from '../types' // подарок → кому → отправка (сначала себе, потом людям порциями по 25). Имя кампании даёт сервер; // своё можно задать на шаге «Кому». Открытая по имени — сразу на отправке: дослать выбранным, выбрать // остальных или ещё одну группу. Группа добавляется в ту же кампанию, поэтому сообщение и подарок -// человек получает один раз, в какой бы группе он ни оказался. Готовую рассылку можно вставить одним куском +// человек получает один раз, в какой бы группе он ни оказался. Вместо отправки руками рассылке можно назначить +// день, час и пояс: тогда сервер сам выберет всю группу и разошлёт в этот момент. Готовую рассылку можно вставить одним куском // текста (формат — в admin/pastedBroadcast.ts): все шаги заполнятся, и откроется отправка. interface Props { @@ -94,6 +96,10 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft, const [status, setStatus] = useState(null) /** Ещё одна группа для той же кампании. */ const [another, setAnother] = useState(null) + /** Когда отправить саму: день и время по часам выбранного пояса. */ + const [sendDate, setSendDate] = useState(tomorrow) + const [sendTime, setSendTime] = useState('12:00') + const [sendZone, setSendZone] = useState(ZONES[0].id) const [busy, setBusy] = useState(false) const [note, setNote] = useState(null) /** Поле «Вставить готовую рассылку» открыто. */ @@ -164,6 +170,7 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft, setSampleFirst(r.sample !== null) if (r.sample !== null) setSampleSize(r.sample) setOwnName(r.name) + if (r.when) { setSendDate(r.when.date); setSendTime(r.when.time); setSendZone(r.when.zone) } setPasting(false) setPasted('') setPasteProblem(null) @@ -233,19 +240,44 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft, return `Остановил. Дошло ${s.sent}, ждут ${s.pending} — можно продолжить позже.` }) - // Пока сервер рассылает — обновлять счётчики; закончил — сказать итог. + // По расписанию: получателей сейчас никто не выбирает — сервер выберет всю группу, когда придёт время, и разошлёт сам. + const schedule = () => run(async () => { + const at = wallToUtc(sendDate, sendTime, sendZone) + if (!at) return 'Выбери день и время отправки.' + if (at.getTime() <= Date.now()) return 'Это время уже прошло. Назначь время в будущем.' + const time = { sendAtUtc: at.toISOString(), sendAtTimeZone: sendZone } + const plan = await adminCampaigns.prepare(draft(audience, null, true, time)) + const text = scheduledText(time.sendAtUtc, sendZone) + const gift = giftDays > 0 && button ? `\n\nС подарком: ${giftDays} дн. доступа тому, кто откроет кнопку.` : '' + if (!confirm(`ЗАПЛАНИРОВАТЬ на ${text}?\n\n${message.trim()}${gift}\n\nУйдёт само всем, кто в этот момент будет в группе «${audienceName(audience)}» — сейчас это ${plan.picked} чел.`)) return null + const done = await adminCampaigns.prepare(draft(audience, null, false, time)) + setKey(done.key) + drafts.clear('broadcast') + setStatus(await adminCampaigns.status(done.key)) + return null + }) + + const cancelSchedule = () => run(async () => { + if (!key) return null + if (!confirm('Отменить отправку по расписанию? Сообщения не уйдут.')) return null + setStatus(await adminCampaigns.stop(key)) + return 'Расписание отменил. Сообщения не ушли.' + }) + + // Пока сервер рассылает или рассылка ждёт своего часа — обновлять счётчики; закончил — сказать итог. const sending = status?.sendingAll === true + const scheduledAt = status?.scheduledAtUtc ?? null useEffect(() => { - if (!key || !sending) return + if (!key || !(sending || scheduledAt)) return const timer = setInterval(() => { adminCampaigns.status(key).then(s => { setStatus(s) - if (!s.sendingAll && s.pending === 0) + if (!s.sendingAll && !s.scheduledAtUtc && s.pending === 0) setNote(`Готово. Дошло ${s.sent}, заблокировали бота ${s.blocked}, отказ ${s.rejected}, без ответа ${s.unknown}.`) }).catch(() => {}) - }, 3000) + }, sending ? 3000 : 15000) return () => clearInterval(timer) - }, [key, sending]) + }, [key, sending, scheduledAt]) const close = () => { if (unsaved && !confirm('Закрыть рассылку? Черновик останется на этом устройстве — к нему можно вернуться из списка рассылок.')) return @@ -399,14 +431,18 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft,
1. Посмотри сам
-
2. Выбери получателей — сообщения не уходят
- + {!scheduledAt && ( + <> +
2. Выбери получателей — сообщения не уходят
+ -
3. Отправь
- {sending ? ( +
3. Отправь
+ + )} + {scheduledAt ? null : sending ? ( <>
Рассылается: дошло {status!.sent}, ждут {status!.pending}. Мини-апп можно закрыть — бот напишет, когда закончит. @@ -423,14 +459,43 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft, )} - {!waiting && ( + {!waiting && !scheduledAt && (
{frozen ? 'Все выбранные уже получили сообщение. Можно выбрать остальных или ещё одну группу.' : 'Отправка откроется, когда выберешь получателей.'}
)} + {!sending && ( + <> +
{scheduledAt ? '2. Уйдёт сама' : 'Или назначь время — уйдёт само'}
+ {scheduledAt ? ( + <> +
+ Запланирована на {scheduledText(scheduledAt, status!.scheduledTimeZone)}. Уйдёт сама всем, кто в этот момент будет в группе «{audienceName(audience)}». + Мини-апп можно закрыть — бот напишет, когда разошлёт. +
+ + + ) : ( + <> +
+ setSendDate(e.target.value)} data-testid="broadcast-schedule-date" /> + setSendTime(e.target.value)} data-testid="broadcast-schedule-time" /> +
+ + +
Выбирать получателей не нужно: в назначенный час сообщение получит вся группа «{audienceName(audience)}» — кто будет в ней в этот момент.
+ + )} + + )} + {note &&
{note}
} - {status && ( + {status && !(scheduledAt && status.total === 0) && (
Выбрано {status.total} · ждут {status.pending} · дошло {status.sent} · заблокировали {status.blocked} · отказ {status.rejected} · без ответа Telegram {status.unknown}{status.buttonText ? ` · открыли по кнопке ${status.opened}` : ''} @@ -438,7 +503,7 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft,
)} - {frozen && ( + {frozen && !scheduledAt && (
Дослать ещё одной группе
@@ -464,7 +529,7 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft,
)} - {frozen &&
Получатели выбраны — текст, кнопку и подарок уже не поменять. Имя рассылки: {key}.
} + {frozen &&
{scheduledAt && status?.total === 0 ? 'Рассылка записана' : 'Получатели выбраны'} — текст, кнопку и подарок уже не поменять. Имя рассылки: {key}.
} )} diff --git a/src/Trale/miniapp-src/src/screens/AdminBroadcastsScreen.tsx b/src/Trale/miniapp-src/src/screens/AdminBroadcastsScreen.tsx index 33bd9c4b..c556e7fd 100644 --- a/src/Trale/miniapp-src/src/screens/AdminBroadcastsScreen.tsx +++ b/src/Trale/miniapp-src/src/screens/AdminBroadcastsScreen.tsx @@ -4,13 +4,14 @@ import { readClipboard } from '../admin/pastedBroadcast' import { adminCampaigns, type CampaignListItemDto } from '../api' import { audienceName, day } from '../admin/words' import { adminBack } from '../admin/adminNav' +import { scheduledText } from '../admin/schedule' import { draft } from '../admin/useKept' import type { Screen } from '../types' // Рассылки: все кампании, отправленные людям, новые сверху — с тем, как далеко каждая дошла. -// Новая собирается по шагам; недосланную можно открыть и продолжить. Опросы живут в «Обратной связи». +// Новая собирается по шагам; недосланную можно открыть и продолжить, запланированную — отменить. Опросы живут в «Обратной связи». -const STATE: Record = { draft: 'черновик', running: 'идёт', done: 'завершена' } +const STATE: Record = { scheduled: 'запланирована', draft: 'черновик', running: 'идёт', done: 'завершена' } export default function AdminBroadcastsScreen({ navigate }: { navigate: (s: Screen) => void }) { const [phase, setPhase] = useState('loading') @@ -60,15 +61,18 @@ export default function AdminBroadcastsScreen({ navigate }: { navigate: (s: Scre className="jewel-tile jewel-pressable w-full text-left px-4 py-3 min-h-[56px]" data-testid={`broadcast-${c.key}`}>
- {STATE[c.state]} + {STATE[c.state]} {day(c.createdAtUtc)}
{c.message.split('\n')[0]}
- {audienceName(c.audience)} · отправлено {c.picked - c.pending} из {c.picked} + {audienceName(c.audience)} · {c.scheduledAtUtc ? `уйдёт сама ${scheduledText(c.scheduledAtUtc, c.scheduledTimeZone)}` : `отправлено ${c.picked - c.pending} из ${c.picked}`}
- {c.buttonText ? `открыли по кнопке ${c.opened}` : 'без кнопки'}{c.giftDays > 0 ? ` · подарков выдано ${c.gifted} (${c.giftDays} дн.)` : ''} + {c.scheduledAtUtc && c.picked === 0 + ? `${c.buttonText ? `с кнопкой «${c.buttonText}»` : 'без кнопки'}${c.giftDays > 0 ? ` · подарок ${c.giftDays} дн.` : ''}` + : `${c.buttonText ? `открыли по кнопке ${c.opened}` : 'без кнопки'}${c.giftDays > 0 ? ` · подарков выдано ${c.gifted} (${c.giftDays} дн.)` : ''}`}
diff --git a/src/Trale/miniapp-src/src/screens/__tests__/AdminBroadcastScreen.test.tsx b/src/Trale/miniapp-src/src/screens/__tests__/AdminBroadcastScreen.test.tsx index 731923cc..d821def3 100644 --- a/src/Trale/miniapp-src/src/screens/__tests__/AdminBroadcastScreen.test.tsx +++ b/src/Trale/miniapp-src/src/screens/__tests__/AdminBroadcastScreen.test.tsx @@ -312,6 +312,114 @@ describe('AdminBroadcastScreen — готовая рассылка одним к }) }) +describe('AdminBroadcastScreen — отправка по расписанию', () => { + const LATER = 'имя: prices-last-days\nкому: neverPaid\nкнопка: Купить по старой цене\nадрес: paywall=1\nкогда: 28.11.2099 12:00\nпояс: Тбилиси\n---\nДо повышения цен осталось 3 дня.' + const AT = '2099-11-28T08:00:00.000Z' + const scheduled = { ...status, key: 'prices-last-days', audience: 'neverPaid', message: 'До повышения цен осталось 3 дня.', giftDays: 0, total: 0, pending: 0, scheduledAtUtc: AT, scheduledTimeZone: 'Asia/Tbilisi' } as CampaignStatusDto + + it('a pasted broadcast with a time is scheduled by one button: nobody is picked, the server gets the moment in UTC', async () => { + api.prepare.mockImplementation(async body => picked('prices-last-days', body.dryRun ? 565 : 0, body.dryRun)) + api.status.mockResolvedValue(scheduled) + render() + + expect(title()).toBe('Отправка') + expect((screen.getByTestId('broadcast-schedule-date') as HTMLInputElement).value).toBe('2099-11-28') + expect((screen.getByTestId('broadcast-schedule-time') as HTMLInputElement).value).toBe('12:00') + expect((screen.getByTestId('broadcast-schedule-zone') as HTMLSelectElement).value).toBe('Asia/Tbilisi') + await userEvent.click(screen.getByTestId('broadcast-schedule')) + + await waitFor(() => expect(api.prepare).toHaveBeenCalledTimes(2)) + expect(confirm.mock.calls[0][0]).toContain('ЗАПЛАНИРОВАТЬ на 28.11.2099 12:00 (Тбилиси)?') + expect(confirm.mock.calls[0][0]).toContain('сейчас это 565 чел.') + expect(api.prepare).toHaveBeenLastCalledWith({ + key: 'prices-last-days', newBroadcast: false, audience: 'neverPaid', message: 'До повышения цен осталось 3 дня.', + buttonText: 'Купить по старой цене', buttonQuery: 'paywall=1', giftDays: 0, sampleSize: null, dryRun: false, + sendAtUtc: AT, sendAtTimeZone: 'Asia/Tbilisi' + }) + const state = await screen.findByTestId('broadcast-scheduled') + expect(state.textContent).toContain('Запланирована на 28.11.2099 12:00 (Тбилиси)') + expect(state.textContent).toContain('Мини-апп можно закрыть') + expect(screen.queryByTestId('broadcast-note')).toBeNull() + // Пока рассылка ждёт своего часа, выбирать и отправлять руками нечего. + for (const gone of ['broadcast-schedule', 'broadcast-pick', 'broadcast-send-all', 'broadcast-send', 'broadcast-another', 'broadcast-status']) + expect(screen.queryByTestId(gone)).toBeNull() + expect(screen.getByTestId('broadcast-send-me')).toBeTruthy() + expect(api.send).not.toHaveBeenCalled() + expect(api.sendAll).not.toHaveBeenCalled() + }) + + it('the day, the hour and the zone are chosen on the sending step: tomorrow at noon by Tbilisi to begin with; without a day there is nothing to schedule', async () => { + api.prepare.mockImplementation(async body => picked(KEY, body.dryRun ? 553 : 0, body.dryRun)) + api.status.mockResolvedValue({ ...status, total: 0, pending: 0, scheduledAtUtc: '2099-07-01T10:30:00.000Z', scheduledTimeZone: 'Europe/Berlin' }) + await toSending() + const day = new Date(Date.now() + 24 * 3600 * 1000) + expect((screen.getByLabelText('День отправки') as HTMLInputElement).value) + .toBe(`${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, '0')}-${String(day.getDate()).padStart(2, '0')}`) + expect((screen.getByLabelText('Время отправки') as HTMLInputElement).value).toBe('12:00') + expect((screen.getByLabelText('Часовой пояс') as HTMLSelectElement).value).toBe('Asia/Tbilisi') + await userEvent.clear(screen.getByLabelText('День отправки')) + expect((screen.getByTestId('broadcast-schedule') as HTMLButtonElement).disabled).toBe(true) + + await userEvent.type(screen.getByLabelText('День отправки'), '2099-07-01') + await userEvent.clear(screen.getByLabelText('Время отправки')) + await userEvent.type(screen.getByLabelText('Время отправки'), '12:30') + await userEvent.selectOptions(screen.getByLabelText('Часовой пояс'), 'Europe/Berlin') + await userEvent.click(screen.getByTestId('broadcast-schedule')) + + await waitFor(() => expect(api.prepare).toHaveBeenCalledTimes(2)) + expect(api.prepare.mock.calls[1][0]).toMatchObject({ sampleSize: null, dryRun: false, sendAtUtc: '2099-07-01T10:30:00.000Z', sendAtTimeZone: 'Europe/Berlin' }) + expect((await screen.findByTestId('broadcast-scheduled')).textContent).toContain('01.07.2099 12:30 (Берлин)') + }) + + it('a time that has passed is not sent to the server; a declined confirmation schedules nothing', async () => { + api.prepare.mockImplementation(async body => picked(KEY, 553, body.dryRun)) + await toSending() + await userEvent.clear(screen.getByLabelText('День отправки')) + await userEvent.type(screen.getByLabelText('День отправки'), '2020-01-01') + await userEvent.click(screen.getByTestId('broadcast-schedule')) + expect(screen.getByTestId('broadcast-note').textContent).toContain('уже прошло') + expect(api.prepare).not.toHaveBeenCalled() + + confirm.mockReturnValue(false) + await userEvent.clear(screen.getByLabelText('День отправки')) + await userEvent.type(screen.getByLabelText('День отправки'), '2099-01-01') + await userEvent.click(screen.getByTestId('broadcast-schedule')) + await waitFor(() => expect(confirm).toHaveBeenCalled()) + expect(api.prepare).toHaveBeenCalledTimes(1) + expect(api.prepare.mock.calls[0][0]).toMatchObject({ dryRun: true }) + expect(screen.queryByTestId('broadcast-scheduled')).toBeNull() + }) + + it('a scheduled broadcast opens with its time and can be called off', async () => { + api.status.mockResolvedValue(scheduled) + api.stop.mockResolvedValue({ ...scheduled, scheduledAtUtc: null, scheduledTimeZone: null }) + render() + + expect((await screen.findByTestId('broadcast-scheduled')).textContent).toContain('28.11.2099 12:00 (Тбилиси)') + expect(screen.queryByTestId('broadcast-send-hint')).toBeNull() + await userEvent.click(screen.getByTestId('broadcast-schedule-cancel')) + + expect(api.stop).toHaveBeenCalledWith('prices-last-days') + expect(screen.getByTestId('broadcast-note').textContent).toBe('Расписание отменил. Сообщения не ушли.') + expect(screen.queryByTestId('broadcast-scheduled')).toBeNull() + expect(screen.getByTestId('broadcast-schedule')).toBeTruthy() + expect(screen.getByTestId('broadcast-pick')).toBeTruthy() + }) + + it('when its hour comes while the screen is open, the screen shows the sending and then the result', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }) + api.status.mockResolvedValueOnce(scheduled) + render() + await screen.findByTestId('broadcast-scheduled') + + api.status.mockResolvedValue({ ...scheduled, scheduledAtUtc: null, total: 565, pending: 0, sent: 565 }) + await vi.advanceTimersByTimeAsync(15000) + await waitFor(() => expect(screen.getByTestId('broadcast-note').textContent).toContain('Готово. Дошло 565')) + expect(screen.queryByTestId('broadcast-scheduled')).toBeNull() + vi.useRealTimers() + }) +}) + describe('AdminBroadcastScreen — вставка из буфера одним нажатием', () => { const READY = 'имя: myday-active\nкому: activeLately\nподарок: 7\nкнопка: Посмотреть первую серию\nадрес: moduleId=my-day&lessonId=1\n---\nНовый модуль — «Мой день»' diff --git a/src/Trale/miniapp-src/src/screens/__tests__/AdminSections.test.tsx b/src/Trale/miniapp-src/src/screens/__tests__/AdminSections.test.tsx index 7b6a90eb..ca4b64b7 100644 --- a/src/Trale/miniapp-src/src/screens/__tests__/AdminSections.test.tsx +++ b/src/Trale/miniapp-src/src/screens/__tests__/AdminSections.test.tsx @@ -288,6 +288,16 @@ describe('AdminBroadcastsScreen', () => { picked: 553, pending: 478, sent: 73, opened: 21, gifted: 14, state: 'running', ...over }) + it('a scheduled campaign says when it goes out by itself, by the clock of its zone', async () => { + campaigns.list.mockResolvedValue({ campaigns: [item('prices-last-days', { state: 'scheduled', audience: 'neverPaid', picked: 0, pending: 0, scheduledAtUtc: '2026-11-28T08:00:00Z', scheduledTimeZone: 'Asia/Tbilisi' })] }) + render() + + const row = await screen.findByTestId('broadcast-prices-last-days') + expect(row.textContent).toContain('запланирована') + expect(row.textContent).toContain('ни разу не платили · уйдёт сама 28.11.2026 12:00 (Тбилиси)с кнопкой «Открыть» · подарок 3 дн.') + expect(row.textContent).not.toContain('открыли по кнопке') + }) + it('lists campaigns with how far each got, and opens one or starts a new one', async () => { campaigns.list.mockResolvedValue({ campaigns: [item('broadcast-2026-10'), item('broadcast-2026-09', { state: 'done', pending: 0, buttonText: null, giftDays: 0 }), item('draft', { state: 'draft', picked: 0, pending: 0 })] }) render() diff --git a/tests/IntegrationTests/Admin/BroadcastCampaignTests.cs b/tests/IntegrationTests/Admin/BroadcastCampaignTests.cs index 5c1daf6f..9c128217 100644 --- a/tests/IntegrationTests/Admin/BroadcastCampaignTests.cs +++ b/tests/IntegrationTests/Admin/BroadcastCampaignTests.cs @@ -635,6 +635,191 @@ public async Task The_worker_sends_everyone_with_the_page_closed_and_tells_the_o .Which.Text.Should().Contain("by-worker").And.Contain("Дошло: 30 из 30"); } + // ── On a schedule ──────────────────────────────────────────────────────── + + private Task<(HttpStatusCode Code, JsonElement Body)> Schedule(string key, string audience, DateTime sendAtUtc, + bool dryRun = false, int? sampleSize = null, int giftDays = 0, int? giftOfferDays = null) => + Call(HttpMethod.Post, "campaigns/prepare", new + { + key, audience, message = "Осталось три дня", buttonText = "Открыть", buttonQuery = "", sampleSize, dryRun, + giftDays, giftOfferDays, sendAtUtc, sendAtTimeZone = "Asia/Tbilisi" + }); + + private Task> StartScheduled(DateTime now) => InScope(sp => + new BroadcastCampaignService(sp.GetRequiredService(), new ScriptedSender(), NullLoggerFactory.Instance) + .StartScheduledAsync(now, Owner, CancellationToken.None)); + + /// The campaign's time has come: as if the owner had scheduled it earlier for a minute ago. + private Task TimeHasCome(string key) => InScope(async sp => + { + var db = sp.GetRequiredService(); + return await db.Database.ExecuteSqlInterpolatedAsync( + $"""UPDATE "BroadcastCampaigns" SET "ScheduledAtUtc" = {DateTime.UtcNow.AddMinutes(-1)} WHERE "Key" = {key}"""); + }); + + [Test] + public async Task Scheduling_saves_the_time_and_picks_nobody_until_it_comes() + { + await AccessEnded(4); + var at = DateTime.UtcNow.AddDays(18); + var mark = _telegram.Requests.Count; + + var (dryCode, dry) = await Schedule("later", "accessEnded", at, dryRun: true); + (await Call(HttpMethod.Get, "campaigns/later")).Code.Should().Be(HttpStatusCode.NotFound, "a dry run saves nothing"); + var (code, body) = await Schedule("later", "accessEnded", at); + + dryCode.Should().Be(HttpStatusCode.OK); + dry.GetProperty("audienceTotal").GetInt32().Should().Be(4, "how many would get it if it went out now"); + code.Should().Be(HttpStatusCode.OK, body.GetRawText()); + body.GetProperty("picked").GetInt32().Should().Be(0); + var status = await Status("later"); + status.GetProperty("scheduledAtUtc").GetDateTime().Should().BeCloseTo(at, TimeSpan.FromSeconds(1)); + status.GetProperty("scheduledTimeZone").GetString().Should().Be("Asia/Tbilisi"); + status.GetProperty("sendingAll").GetBoolean().Should().BeFalse(); + (await Deliveries("later")).Should().BeEmpty(); + var listed = (await Call(HttpMethod.Get, "campaigns")).Body.GetProperty("campaigns").EnumerateArray() + .Single(c => c.GetProperty("key").GetString() == "later"); + listed.GetProperty("state").GetString().Should().Be("scheduled"); + listed.GetProperty("scheduledAtUtc").GetDateTime().Should().BeCloseTo(at, TimeSpan.FromSeconds(1)); + + (await StartScheduled(DateTime.UtcNow)).Should().BeEmpty("its time has not come"); + await RoundWith(new ScriptedSender()); + (await Deliveries("later")).Should().BeEmpty(); + SentSince(mark).Should().BeEmpty(); + } + + [Test] + public async Task When_the_time_comes_it_goes_to_those_in_the_audience_at_that_moment() + { + var people = await AccessEnded(5); + var at = DateTime.UtcNow.AddDays(18); + (await Schedule("last-days", "neverPaid", at)).Code.Should().Be(HttpStatusCode.OK); + + // Between scheduling and sending: one buys, one joins. + var newcomer = await AddUsers(1, registeredDaysAgo: 1); + await InScope(async sp => + { + var db = sp.GetRequiredService(); + db.Payments.Add(new Payment + { + Id = Guid.NewGuid(), UserId = people[0].Id, TelegramPaymentChargeId = Guid.NewGuid().ToString(), PayloadId = "Stars_Pro_Month", + Plan = SubscriptionPlan.Month, Amount = 100, Currency = "XTR", PurchasedAtUtc = DateTime.UtcNow + }); + return await db.SaveChangesAsync(CancellationToken.None); + }); + + var started = await StartScheduled(at.AddSeconds(1)); + var sender = new ScriptedSender(); + for (var i = 0; i < 5 && (await RoundWith(sender)).Finished.Count == 0; i++) { } + + started.Should().Equal("last-days"); + var expected = people.Skip(1).Concat(newcomer).Select(u => u.TelegramId).Append(Owner); + sender.Attempts.Should().BeEquivalentTo(expected, "the one who bought gets nothing, the newcomer does"); + var status = await Status("last-days"); + status.GetProperty("scheduledAtUtc").ValueKind.Should().Be(JsonValueKind.Null); + status.GetProperty("sendingAll").GetBoolean().Should().BeFalse("everyone was sent, the request is closed"); + status.GetProperty("sent").GetInt32().Should().Be(6); + (await StartScheduled(at.AddDays(1))).Should().BeEmpty("a campaign starts once"); + } + + [Test] + public async Task Two_replicas_start_a_scheduled_campaign_once() + { + var people = await AccessEnded(40); + var at = DateTime.UtcNow.AddHours(1); + await Schedule("one-start", "accessEnded", at); + + var starts = await Task.WhenAll(Enumerable.Range(0, 4).Select(_ => StartScheduled(at.AddSeconds(1)))); + + starts.SelectMany(s => s).Should().Equal("one-start"); + (await Deliveries("one-start")).Select(d => d.UserId).Should().BeEquivalentTo(people.Select(p => p.Id)); + (await Status("one-start")).GetProperty("sendingAll").GetBoolean().Should().BeTrue(); + } + + [Test] + public async Task Stop_takes_a_campaign_off_the_schedule() + { + await AccessEnded(3); + var at = DateTime.UtcNow.AddHours(1); + await Schedule("called-off", "accessEnded", at); + + var (code, body) = await Call(HttpMethod.Post, "campaigns/called-off/stop"); + + code.Should().Be(HttpStatusCode.OK); + body.GetProperty("scheduledAtUtc").ValueKind.Should().Be(JsonValueKind.Null); + (await StartScheduled(at.AddSeconds(1))).Should().BeEmpty(); + (await Deliveries("called-off")).Should().BeEmpty(); + } + + [Test] + public async Task The_time_can_be_moved_and_only_the_last_one_counts() + { + await AccessEnded(3); + var first = DateTime.UtcNow.AddHours(1); + var second = DateTime.UtcNow.AddDays(2); + await Schedule("moved", "accessEnded", first); + (await Schedule("moved", "accessEnded", second)).Code.Should().Be(HttpStatusCode.OK); + + (await StartScheduled(first.AddSeconds(1))).Should().BeEmpty(); + (await StartScheduled(second.AddSeconds(1))).Should().Equal("moved"); + } + + [Test] + public async Task A_schedule_needs_a_future_time_and_the_whole_audience() + { + await AccessEnded(3); + + var (past, pastBody) = await Schedule("bad-time", "accessEnded", DateTime.UtcNow.AddMinutes(-1)); + var (far, _) = await Schedule("bad-time", "accessEnded", DateTime.UtcNow.AddDays(BroadcastCampaignService.MaxScheduleDays + 1)); + var (sample, sampleBody) = await Schedule("bad-time", "accessEnded", DateTime.UtcNow.AddHours(1), sampleSize: 2); + + past.Should().Be(HttpStatusCode.BadRequest); + pastBody.GetProperty("error").GetString().Should().Contain("уже прошло"); + far.Should().Be(HttpStatusCode.BadRequest); + sample.Should().Be(HttpStatusCode.BadRequest); + sampleBody.GetProperty("error").GetString().Should().Contain("всей группе"); + (await Call(HttpMethod.Get, "campaigns/bad-time")).Code.Should().Be(HttpStatusCode.NotFound); + } + + [Test] + public async Task The_gift_of_a_scheduled_campaign_is_offered_from_the_day_it_goes_out() + { + await AccessEnded(2); + var at = DateTime.UtcNow.AddDays(10); + + await Schedule("gift-later", "accessEnded", at, giftDays: 7, giftOfferDays: 3); + + (await Status("gift-later")).GetProperty("giftOfferEndsAtUtc").GetDateTime() + .Should().BeCloseTo(at.AddDays(3), TimeSpan.FromSeconds(1)); + } + + [Test] + public async Task The_worker_sends_a_scheduled_campaign_by_itself_and_tells_the_owner() + { + var people = await AccessEnded(6); + await Schedule("by-clock", "accessEnded", DateTime.UtcNow.AddHours(1)); + await TimeHasCome("by-clock"); + var mark = _telegram.Requests.Count; + + var worker = ActivatorUtilities.CreateInstance(_app.Services); + await worker.StartAsync(CancellationToken.None); + try + { + for (var i = 0; i < 300 && !SentSince(mark).Any(m => m.ChatId.Identifier == Owner); i++) + await Task.Delay(100); + } + finally + { + await worker.StopAsync(CancellationToken.None); + } + + var sent = SentSince(mark); + sent.Where(m => m.ChatId.Identifier != Owner).Select(m => m.ChatId.Identifier!.Value) + .Should().BeEquivalentTo(people.Select(p => p.TelegramId)); + sent.Where(m => m.ChatId.Identifier == Owner).Should().ContainSingle() + .Which.Text.Should().Contain("by-clock").And.Contain("Дошло: 6 из 6"); + } + // ── Measuring ──────────────────────────────────────────────────────────── private async Task OpenByButton(User user, string key)