diff --git a/FEATURES.md b/FEATURES.md index b284151f..7a6cfb3b 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -110,7 +110,7 @@ Location: `src/Trale/miniapp-src/src/`. The test greps the base file name (e.g. | `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. 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 `пояс: Тбилиси`. | +| `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), then one choice «Сейчас / Позже» and one main button. «Сейчас»: «Отправить всем — N чел.» (or «Отправить пробной группе — N чел.») asks once with the head count, the text and the gift, writes down the recipients and hands the sending to the server (`send-all`) — the mini-app can be closed, the bot reports when it is done. «Позже»: 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 broadcast pasted as one text opens right on this step with everything filled, so it takes one button; a pasted time selects «Позже». The server names the campaign (`broadcast--`). An opened one starts on its sending: «Отправить — ждут N чел.» if recipients are written down but not sent to (stopped, or the sending did not start), otherwise «Отправить остальным из группы» 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 it is sent or scheduled the unfinished broadcast is saved on the device (`localStorage`, `admin/useKept.ts`) and offered again from the list. 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. | diff --git a/src/Trale/miniapp-src/e2e/admin.spec.ts b/src/Trale/miniapp-src/e2e/admin.spec.ts index b4f0e595..cb5309fb 100644 --- a/src/Trale/miniapp-src/e2e/admin.spec.ts +++ b/src/Trale/miniapp-src/e2e/admin.spec.ts @@ -159,10 +159,10 @@ const kit = { limits: { questions: 6, options: 6, botOptions: 4, optionLength: 64, questionLength: 300 }, } -interface Calls { prepared: any[]; sent: string[]; userQueries: URLSearchParams[]; back: number; verbs: { path: string; body: any }[] } +interface Calls { prepared: any[]; sent: string[]; started: string[]; userQueries: URLSearchParams[]; back: number; verbs: { path: string; body: any }[] } async function setup(page: Page, opts: { owner?: boolean; fail?: string; slow?: string } = {}): Promise { - const calls: Calls = { prepared: [], sent: [], userQueries: [], back: 0, verbs: [] } + const calls: Calls = { prepared: [], sent: [], started: [], userQueries: [], back: 0, verbs: [] } // Рассылка, которую назначили на время в этом тесте: сервер помнит её, пока расписание не отменят. let scheduled: Record | null = null const owner = opts.owner ?? true @@ -210,7 +210,7 @@ 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: 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/audiences') return ok({ accessEnded: 553, onTrial: 17, paying: 3, proLapsed: 0, owner: 1, activeLately: 61, inactiveLong: 512, paid: 8, neverPaid: 565 }) if (path === 'campaigns/prepare') { const body = route.request().postDataJSON() calls.prepared.push(body) @@ -222,6 +222,7 @@ async function setup(page: Page, opts: { owner?: boolean; fail?: string; slow?: } 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-all')) { calls.started.push(path.replace('campaigns/', '').replace('/send-all', '')); return ok({ ...campaignStatus, total: 40, sample: 0, pending: 40, sent: 0, blocked: 0, opened: 0, gifted: 0, sendingAll: true }) } 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 } @@ -538,7 +539,9 @@ test('a new broadcast is a focused flow: no tab bar, steps, the main button pinn await expect(step).toHaveText('Отправка') await expect(page.getByTestId('broadcast-summary')).toHaveText('Кнопка ведёт: Раздел «Глаголы». Подарок: 3 дн. доступа. Кому: занимались за последние 30 дней — 61 чел., сначала пробной группе из 61') - await expect(page.getByTestId('broadcast-send')).toBeDisabled() + // Одна главная кнопка: сколько человек получит сообщение, написано прямо на ней. + await expect(page.getByTestId('broadcast-send-now')).toHaveText('Отправить пробной группе — 61 чел.') + await expect(page.getByTestId('broadcast-schedule')).toHaveCount(0) await page.getByTestId('broadcast-send-me').click() await expect(page.getByTestId('broadcast-note')).toContainText('Отправил тебе в чат с ботом') expect(calls.prepared).toHaveLength(1) @@ -547,19 +550,28 @@ test('a new broadcast is a focused flow: no tab bar, steps, the main button pinn await fits(page) await shot(page, 'admin-17-broadcast-send') - // Получатели выбраны — черновика больше нет. - page.on('dialog', d => void d.accept()) - await page.getByTestId('broadcast-pick').click() + // Одно нажатие и одно подтверждение: получатели записаны, рассылает сервер — черновика больше нет. + let sendAsked = '' + page.on('dialog', d => { sendAsked = d.message(); void d.accept() }) + await page.getByTestId('broadcast-send-now').click() + await expect(page.getByTestId('broadcast-sending')).toContainText('дошло 0, ждут 40') + expect(sendAsked).toContain('ОТПРАВИТЬ пробной группе: 40 чел. (занимались за последние 30 дней)?') + expect(sendAsked).toContain('Это настоящая отправка через бота.') + expect(calls.started).toEqual([`${BROADCAST}-2`]) await expect(page.getByTestId('broadcast-status')).toBeVisible() + for (const gone of ['broadcast-send-now', 'broadcast-when-later', 'broadcast-another']) await expect(page.getByTestId(gone)).toHaveCount(0) + await fits(page) + await shot(page, 'admin-17b-broadcast-sending') await page.getByTestId('admin-close').click() await expect(title(page)).toHaveText('Рассылки') await expect(page.getByTestId('broadcast-draft')).toHaveCount(0) - // Идущая рассылка: та же кампания для ещё одной группы. + // Рассылка, где часть получателей ещё ждёт: одна кнопка — дослать им. await page.getByTestId(`broadcast-${BROADCAST}`).click() await expect(step).toHaveText('Отправка') await expect(tabs(page)).toHaveCount(0) - await expect(page.getByTestId('broadcast-another')).toContainText('Это будет та же рассылка') + await expect(page.getByTestId('broadcast-send-all')).toHaveText('Отправить — ждут 25 чел.') + await expect(page.getByTestId('broadcast-send-now')).toHaveCount(0) await fits(page) await shot(page, 'admin-18-broadcast-running') await telegramBack(page) @@ -578,7 +590,11 @@ test('a broadcast is scheduled for a day, an hour and a time zone, shows up as s await page.getByTestId('broadcast-next').click() await expect(page.getByTestId('broadcast-step-title')).toHaveText('Отправка') - // Сначала стоит завтра, полдень по Тбилиси; назначаем день, час и пояс — по часам Берлина. + // День и час появляются, когда выбрано «Позже»: сначала стоит завтра, полдень по Тбилиси; назначаем по часам Берлина. + await expect(page.getByTestId('broadcast-send-now')).toHaveText('Отправить всем — 61 чел.') + await expect(page.getByTestId('broadcast-schedule-date')).toHaveCount(0) + await page.getByTestId('broadcast-when-later').click() + await expect(page.getByTestId('broadcast-send-now')).toHaveCount(0) const plan = page.getByTestId('broadcast-schedule') await plan.scrollIntoViewIfNeeded() await expect(page.getByTestId('broadcast-schedule-date')).not.toHaveValue('') @@ -587,6 +603,7 @@ test('a broadcast is scheduled for a day, an hour and a time zone, shows up as s 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 expect(plan).toHaveText('Запланировать на 01.07.2099 12:30 (Берлин)') await fits(page) await shot(page, 'admin-19-broadcast-schedule') @@ -600,7 +617,7 @@ test('a broadcast is scheduled for a day, an hour and a time zone, shows up as s 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) + for (const gone of ['broadcast-schedule', 'broadcast-send-now', 'broadcast-send-all', 'broadcast-send-rest', '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([]) @@ -622,12 +639,61 @@ test('a broadcast is scheduled for a day, an hour and a time zone, shows up as s await page.getByTestId('broadcast-schedule-cancel').click() await expect(page.getByTestId('broadcast-note')).toHaveText('Расписание отменил. Сообщения не ушли.') await expect(state).toHaveCount(0) + await expect(page.getByTestId('broadcast-send-now')).toHaveText('Отправить всем — 61 чел.') + await page.getByTestId('broadcast-when-later').click() 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) }) +/** Кладёт текст в буфер обмена страницы — как после кнопки «Скопировать блок». */ +const copied = (page: Page, text: string) => page.evaluate(t => { + Object.defineProperty(navigator, 'clipboard', { value: { readText: async () => t, writeText: async () => {} }, configurable: true }) +}, text) + +test('a ready broadcast is copied, pasted and goes with one button: scheduled if the text names the time, sent right away if it does not', async ({ page }) => { + const calls = await setup(page) + await openAdmin(page) + await tab(page, 'broadcasts').click() + + // С временем в тексте: на экране одна главная кнопка — «Запланировать на …». + await copied(page, 'имя: prices-last-days\nкому: neverPaid\nкнопка: Купить по старой цене\nадрес: paywall=1\nкогда: 28.11.2099 12:00\nпояс: Тбилиси\n---\nДо повышения цен в TraleBot осталось 3 дня.') + await page.getByTestId('broadcast-paste-clipboard').click() + await expect(page.getByTestId('broadcast-step-title')).toHaveText('Отправка') + await expect(page.getByTestId('broadcast-summary')).toHaveText('Кнопка ведёт: Экран покупки. Кому: ни разу не платили — 565 чел.') + const plan = page.getByTestId('broadcast-schedule') + await expect(plan).toHaveText('Запланировать на 28.11.2099 12:00 (Тбилиси)') + for (const gone of ['broadcast-send-now', 'broadcast-send-all', 'broadcast-send-rest', 'broadcast-another', 'broadcast-status']) await expect(page.getByTestId(gone)).toHaveCount(0) + await fits(page) + await shot(page, 'admin-21b-broadcast-pasted-schedule') + let asked = '' + page.once('dialog', d => { asked = d.message(); void d.accept() }) + await plan.click() + await expect(page.getByTestId('broadcast-scheduled')).toContainText('Запланирована на 28.11.2099 12:00 (Тбилиси)') + expect(asked).toContain('ЗАПЛАНИРОВАТЬ на 28.11.2099 12:00 (Тбилиси)?') + expect(calls.prepared.at(-1)).toMatchObject({ key: 'prices-last-days', audience: 'neverPaid', sampleSize: null, dryRun: false, sendAtUtc: '2099-11-28T08:00:00.000Z', sendAtTimeZone: 'Asia/Tbilisi' }) + expect(calls.started).toEqual([]) + await page.getByTestId('admin-close').click() + await expect(page.getByTestId('broadcast-prices-last-days')).toContainText('запланирована') + + // Без времени: одна главная кнопка — «Отправить всем»; одно подтверждение, дальше рассылает сервер. + await copied(page, 'имя: prices-rise\nкому: neverPaid\nкнопка: Купить по старой цене\nадрес: paywall=1\n---\nС 1 декабря цены в TraleBot вырастут примерно на 50%.') + await page.getByTestId('broadcast-paste-clipboard').click() + await expect(page.getByTestId('broadcast-step-title')).toHaveText('Отправка') + const send = page.getByTestId('broadcast-send-now') + await expect(send).toHaveText('Отправить всем — 565 чел.') + await expect(page.getByTestId('broadcast-schedule')).toHaveCount(0) + await fits(page) + await shot(page, 'admin-21c-broadcast-pasted-send') + page.once('dialog', d => { asked = d.message(); void d.accept() }) + await send.click() + await expect(page.getByTestId('broadcast-sending')).toContainText('Мини-апп можно закрыть') + expect(asked).toContain('ОТПРАВИТЬ всем: 40 чел. (ни разу не платили)?') + expect(asked).toContain('С 1 декабря цены в TraleBot вырастут примерно на 50%.') + expect(calls.prepared.at(-1)).toMatchObject({ key: 'prices-rise', audience: 'neverPaid', sampleSize: null, dryRun: false }) + expect(calls.started).toEqual(['prices-rise']) +}) + 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/screens/AdminBroadcastScreen.tsx b/src/Trale/miniapp-src/src/screens/AdminBroadcastScreen.tsx index f59e2d76..06697422 100644 --- a/src/Trale/miniapp-src/src/screens/AdminBroadcastScreen.tsx +++ b/src/Trale/miniapp-src/src/screens/AdminBroadcastScreen.tsx @@ -27,7 +27,6 @@ interface Props { } const STEPS = ['Текст', 'Кнопка', 'Подарок', 'Кому', 'Отправка'] -const BATCH = 25 const PEOPLE = AUDIENCES.filter(a => a.id !== 'owner') /** Куда может вести кнопка — экраны мини-аппа по именам; адрес подставляется сам. */ const DESTINATIONS = [ @@ -100,6 +99,8 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft, const [sendDate, setSendDate] = useState(tomorrow) const [sendTime, setSendTime] = useState('12:00') const [sendZone, setSendZone] = useState(ZONES[0].id) + /** Отправить не сейчас, а в назначенный день и час. */ + const [sendLater, setSendLater] = useState(false) const [busy, setBusy] = useState(false) const [note, setNote] = useState(null) /** Поле «Вставить готовую рассылку» открыто. */ @@ -171,6 +172,7 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft, 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) } + setSendLater(r.when !== null) setPasting(false) setPasted('') setPasteProblem(null) @@ -194,41 +196,30 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft, return sent.sent === 1 ? 'Отправил тебе в чат с ботом — посмотри, как выглядит, и нажми кнопку.' : 'Telegram не принял сообщение. Попробуй ещё раз.' }) - const choose = (to: CampaignAudience, sample: number | null, who: string, extra: object = {}) => run(async () => { + // Одной кнопкой: записать получателей и сразу отдать рассылку серверу — он шлёт порциями, мини-апп можно закрыть. + const sendNow = (to: CampaignAudience, sample: number | null, who: string, extra: object = {}) => run(async () => { const plan = await adminCampaigns.prepare(draft(to, sample, true, extra)) - if (plan.picked === 0) return `Выбирать некого: в группе «${audienceName(to)}» все уже в этой рассылке.` + if (plan.picked === 0) return `Отправлять некому: в группе «${audienceName(to)}» нет никого, кто ещё не получил эту рассылку.` const already = plan.alreadyInCampaign > 0 ? ` Ещё ${plan.alreadyInCampaign} из этой группы уже в рассылке — второй раз они её не получат.` : '' - if (!confirm(`Выбрать ${who}: ${plan.picked} чел. (${audienceName(to)})?${already}\nСообщения пока НЕ уйдут — только список получателей.`)) return null + const gift = giftDays > 0 && button ? `\n\nС подарком: ${giftDays} дн. доступа тому, кто откроет кнопку.` : '' + if (!confirm(`ОТПРАВИТЬ ${who}: ${plan.picked} чел. (${audienceName(to)})?${already}\n\n${text}${gift}\n\nЭто настоящая отправка через бота.`)) return null const done = await adminCampaigns.prepare(draft(to, sample, false, extra)) setKey(done.key) drafts.clear('broadcast') - setStatus(await adminCampaigns.status(done.key)) setAnother(null) - return `Получатели записаны: ${done.picked} чел. Теперь отправляй порциями.` - }) - - const sendBatch = () => run(async () => { - if (!key) return null - const current = await adminCampaigns.status(key) - setStatus(current) - if (current.pending === 0) return 'Отправлять некого: все выбранные уже получили сообщение.' - const n = Math.min(BATCH, current.pending) - const gift = current.giftDays > 0 ? `\n\nС подарком: ${current.giftDays} дн. доступа тому, кто откроет кнопку.` : '' - if (!confirm(`ОТПРАВИТЬ ${n} сообщений?\n\n${current.message}${gift}\n\nЭто настоящая отправка через бота.`)) return null - const r = await adminCampaigns.send(key, BATCH) - setStatus(r.status) - const wait = r.retryAfterSeconds > 0 ? ` Telegram просит подождать ${r.retryAfterSeconds} с.` : '' - return `Отправлено ${r.sent}, заблокировали бота ${r.blocked}, отказ ${r.rejected}, без ответа ${r.unknown}. Осталось ${r.status.pending}.${wait}` + // Получатели уже записаны: не запустилась отправка — на экране останется кнопка «Отправить — ждут N». + try { setStatus(await adminCampaigns.sendAll(done.key)) } catch (e) { setStatus(await adminCampaigns.status(done.key)); throw e } + return null }) - // Всем выбранным — рассылает сервер, порциями: мини-апп можно закрыть, бот напишет, когда закончит. + // Тем, кто уже выбран, но сообщения не получил (отправку остановили или она не запустилась). const sendAll = () => run(async () => { if (!key) return null const current = await adminCampaigns.status(key) setStatus(current) if (current.pending === 0) return 'Отправлять некого: все выбранные уже получили сообщение.' const gift = current.giftDays > 0 ? `\n\nС подарком: ${current.giftDays} дн. доступа тому, кто откроет кнопку.` : '' - if (!confirm(`ОТПРАВИТЬ всем выбранным: ${current.pending} сообщений?\n\n${current.message}${gift}\n\nЭто настоящая отправка через бота.`)) return null + if (!confirm(`ОТПРАВИТЬ ${current.pending} сообщений?\n\n${current.message}${gift}\n\nЭто настоящая отправка через бота.`)) return null setStatus(await adminCampaigns.sendAll(key)) return null }) @@ -284,6 +275,10 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft, navigate(adminBack()) } const total = counts[audience] + // Никому ещё не уходила и не запланирована: одна главная кнопка — отправить сейчас или назначить время. + const fresh = !scheduledAt && (!frozen || status?.total === 0) + const asTrial = !frozen && sampleFirst && !sendLater + const sendAt = wallToUtc(sendDate, sendTime, sendZone) // Главная кнопка шага закреплена внизу экрана. const footer = !frozen && (step > 1 || step < STEPS.length) ? (
@@ -401,7 +396,7 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft, {[true, false].map(first => ( ))}
@@ -425,58 +420,23 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft,
{button ? `Кнопка ведёт: ${destination === 'custom' ? `/?${query}` : DESTINATIONS.find(d => d.id === destination)!.name}. ` : 'Без кнопки. '} {giftDays > 0 && button ? `Подарок: ${giftDays} дн. доступа. ` : ''} - Кому: {audienceName(audience)}{total != null ? ` — ${total} чел.` : ''}{!frozen && sampleFirst ? `, сначала пробной группе из ${Math.min(sampleSize, total ?? sampleSize)}` : ''} + Кому: {audienceName(audience)}{total != null ? ` — ${total} чел.` : ''}{asTrial ? `, сначала пробной группе из ${Math.min(sampleSize, total ?? sampleSize)}` : ''}
-
1. Посмотри сам
- - - {!scheduledAt && ( - <> -
2. Выбери получателей — сообщения не уходят
- + -
3. Отправь
- - )} - {scheduledAt ? null : sending ? ( + {fresh && ( <> -
- Рассылается: дошло {status!.sent}, ждут {status!.pending}. Мини-апп можно закрыть — бот напишет, когда закончит. +
Когда отправить людям
+
+ {[false, true].map(later => ( + + ))}
- - - ) : ( - <> - - - - )} - {!waiting && !scheduledAt && ( -
- {frozen ? 'Все выбранные уже получили сообщение. Можно выбрать остальных или ещё одну группу.' : 'Отправка откроется, когда выберешь получателей.'} -
- )} - - {!sending && ( - <> -
{scheduledAt ? '2. Уйдёт сама' : 'Или назначь время — уйдёт само'}
- {scheduledAt ? ( - <> -
- Запланирована на {scheduledText(scheduledAt, status!.scheduledTimeZone)}. Уйдёт сама всем, кто в этот момент будет в группе «{audienceName(audience)}». - Мини-апп можно закрыть — бот напишет, когда разошлёт. -
- - - ) : ( + {sendLater && ( <>
setSendDate(e.target.value)} data-testid="broadcast-schedule-date" /> @@ -487,23 +447,67 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft, ))} - -
Выбирать получателей не нужно: в назначенный час сообщение получит вся группа «{audienceName(audience)}» — кто будет в ней в этот момент.
)} + {sendLater ? ( + + ) : ( + + )} +
+ {sendLater + ? `В назначенный час сообщение получит вся группа «${audienceName(audience)}» — кто будет в ней в этот момент. Бот напишет, когда разошлёт.` + : 'Покажу, сколько человек получит сообщение, и спрошу подтверждение. Дальше рассылка идёт сама: мини-апп можно закрыть, бот напишет, когда закончит.'} +
+ + )} + + {scheduledAt && ( + <> +
Уйдёт сама
+
+ Запланирована на {scheduledText(scheduledAt, status!.scheduledTimeZone)}. Уйдёт сама всем, кто в этот момент будет в группе «{audienceName(audience)}». + Мини-апп можно закрыть — бот напишет, когда разошлёт. +
+ )} + {!fresh && !scheduledAt && (sending ? ( + <> +
+ Рассылается: дошло {status!.sent}, ждут {status!.pending}. Мини-апп можно закрыть — бот напишет, когда закончит. +
+ + + ) : waiting ? ( + <> + +
Получатели записаны, но сообщения им ещё не ушли.
+ + ) : ( + + ))} + {note &&
{note}
} - {status && !(scheduledAt && status.total === 0) && ( + {status && status.total > 0 && (
- Выбрано {status.total} · ждут {status.pending} · дошло {status.sent} · заблокировали {status.blocked} · отказ {status.rejected} · без + Получателей {status.total} · ждут {status.pending} · дошло {status.sent} · заблокировали {status.blocked} · отказ {status.rejected} · без ответа Telegram {status.unknown}{status.buttonText ? ` · открыли по кнопке ${status.opened}` : ''} {status.giftDays > 0 ? ` · подарков выдано ${status.gifted}` : ''}
)} - {frozen && !scheduledAt && ( + {!fresh && !scheduledAt && !sending && !waiting && (
Дослать ещё одной группе
@@ -520,16 +524,15 @@ export default function AdminBroadcastScreen({ campaignKey, useDraft: withDraft, ))}
{another && ( - )} - {another && waiting &&
Сначала отправь тем, кто уже выбран.
}
)} - {frozen &&
{scheduledAt && status?.total === 0 ? 'Рассылка записана' : 'Получатели выбраны'} — текст, кнопку и подарок уже не поменять. Имя рассылки: {key}.
} + {frozen &&
{status?.total === 0 ? 'Рассылка записана' : 'Получатели выбраны'} — текст, кнопку и подарок уже не поменять. Имя рассылки: {key}.
} )} 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 d821def3..e61d32c6 100644 --- a/src/Trale/miniapp-src/src/screens/__tests__/AdminBroadcastScreen.test.tsx +++ b/src/Trale/miniapp-src/src/screens/__tests__/AdminBroadcastScreen.test.tsx @@ -95,20 +95,21 @@ describe('AdminBroadcastScreen — новая рассылка', () => { expect(navigate).toHaveBeenCalledWith({ kind: 'admin-broadcasts' }) }) - it('opened with a draft, continues from the step where it was left; picking recipients clears the draft', async () => { + it('opened with a draft, continues from the step where it was left; sending clears the draft', async () => { localStorage.setItem('trale_admin_draft_broadcast', JSON.stringify({ step: 4, message: 'Из черновика', hasButton: true, buttonText: 'Открыть', destination: 'verbs', customQuery: '', giftDays: 7, audience: 'activeLately', sampleFirst: false, sampleSize: 100, ownName: '' })) api.prepare.mockResolvedValueOnce(picked(KEY, 61, true)).mockResolvedValueOnce(picked(KEY, 61, false)) - api.status.mockResolvedValue(status) + api.sendAll.mockResolvedValue({ ...status, sendingAll: true }) render() expect(title()).toBe('Кому') expect(screen.getByTestId('broadcast-audience-activeLately').getAttribute('aria-checked')).toBe('true') await next() expect(screen.getByTestId('broadcast-summary').textContent).toBe('Кнопка ведёт: Раздел «Глаголы». Подарок: 7 дн. доступа. Кому: занимались за последние 30 дней — 61 чел.') - await userEvent.click(screen.getByTestId('broadcast-pick')) + expect(screen.getByTestId('broadcast-send-now').textContent).toBe('Отправить всем — 61 чел.') + await userEvent.click(screen.getByTestId('broadcast-send-now')) await waitFor(() => expect(api.prepare).toHaveBeenCalledTimes(2)) await waitFor(() => expect(localStorage.getItem('trale_admin_draft_broadcast')).toBeNull()) }) @@ -126,9 +127,11 @@ describe('AdminBroadcastScreen — новая рассылка', () => { await toSending() expect(screen.getByTestId('broadcast-summary').textContent).toBe('Кнопка ведёт: Раздел «Глаголы». Подарок: 3 дн. доступа. Кому: доступ закончился — 553 чел., сначала пробной группе из 100') expect(screen.getByTestId('broadcast-preview').textContent).toBe('Новые уроки про падежиОткрыть глаголы') - expect((screen.getByTestId('broadcast-send') as HTMLButtonElement).disabled).toBe(true) - expect(screen.getByTestId('broadcast-send-hint').textContent).toBe('Отправка откроется, когда выберешь получателей.') - expect(screen.queryByTestId('broadcast-another')).toBeNull() + // Одна главная кнопка; день и час появляются, только если выбрать «Позже». + expect(screen.getByTestId('broadcast-send-now').textContent).toBe('Отправить пробной группе — 100 чел.') + expect(screen.getByTestId('broadcast-when-now').getAttribute('aria-checked')).toBe('true') + for (const gone of ['broadcast-schedule', 'broadcast-schedule-date', 'broadcast-send-all', 'broadcast-send-rest', 'broadcast-another', 'broadcast-status']) + expect(screen.queryByTestId(gone)).toBeNull() await userEvent.click(screen.getByTestId('broadcast-send-me')) @@ -143,33 +146,51 @@ describe('AdminBroadcastScreen — новая рассылка', () => { expect(screen.getByTestId('broadcast-back')).toBeTruthy() }) - it('recipients are picked after a confirmation; the server names the campaign; a batch asks again and says the gift', async () => { + it('one button sends: it asks once with the head count, the text and the gift, writes down the recipients and hands the sending to the server', async () => { api.prepare.mockResolvedValueOnce(picked(KEY, 100, true)).mockResolvedValueOnce(picked(KEY, 100, false)) - api.status.mockResolvedValue(status) - api.send.mockResolvedValue({ sent: 25, blocked: 0, rejected: 0, unknown: 0, retryAfterSeconds: 0, status: { ...status, pending: 75, sent: 25, opened: 4, gifted: 3 } }) + api.sendAll.mockResolvedValue({ ...status, sendingAll: true }) await toSending() - await userEvent.click(screen.getByTestId('broadcast-pick')) + await userEvent.click(screen.getByTestId('broadcast-send-now')) - await waitFor(() => expect((screen.getByTestId('broadcast-send') as HTMLButtonElement).disabled).toBe(false)) - expect(confirm.mock.calls[0][0]).toContain('Выбрать пробную группу: 100 чел. (доступ закончился)?') - expect(confirm.mock.calls[0][0]).toContain('НЕ уйдут') + expect((await screen.findByTestId('broadcast-sending')).textContent).toContain('дошло 0, ждут 100') + expect(confirm).toHaveBeenCalledTimes(1) + expect(confirm.mock.calls[0][0]).toContain('ОТПРАВИТЬ пробной группе: 100 чел. (доступ закончился)?') + expect(confirm.mock.calls[0][0]).toContain('Новые уроки про падежи') + expect(confirm.mock.calls[0][0]).toContain('С подарком: 3 дн. доступа') + expect(confirm.mock.calls[0][0]).toContain('Это настоящая отправка через бота.') expect(api.prepare.mock.calls.map(c => c[0])).toMatchObject([ { key: '', newBroadcast: true, audience: 'accessEnded', sampleSize: 100, dryRun: true }, { key: '', newBroadcast: true, audience: 'accessEnded', sampleSize: 100, dryRun: false } ]) + expect(api.sendAll).toHaveBeenCalledWith(KEY) expect(api.send).not.toHaveBeenCalled() expect(screen.queryByTestId('broadcast-back')).toBeNull() expect(screen.getByText(/Имя рассылки: broadcast-2026-10\./)).toBeTruthy() + expect(screen.getByTestId('broadcast-status').textContent).toBe('Получателей 100 · ждут 100 · дошло 0 · заблокировали 0 · отказ 0 · без ответа Telegram 0 · открыли по кнопке 0 · подарков выдано 0') + for (const gone of ['broadcast-send-now', 'broadcast-schedule', 'broadcast-when-later', 'broadcast-another']) + expect(screen.queryByTestId(gone)).toBeNull() + }) + + it('if the sending did not start after the recipients were written down, one button is left to start it', async () => { + api.prepare.mockResolvedValueOnce(picked(KEY, 100, true)).mockResolvedValueOnce(picked(KEY, 100, false)) + api.sendAll.mockRejectedValueOnce(new ApiError(500, '')).mockResolvedValue({ ...status, sendingAll: true }) + api.status.mockResolvedValue(status) + await toSending() + + await userEvent.click(screen.getByTestId('broadcast-send-now')) - await userEvent.click(screen.getByTestId('broadcast-send')) - await waitFor(() => expect(api.send).toHaveBeenCalledWith(KEY, 25)) - expect(confirm.mock.calls[1][0]).toContain('ОТПРАВИТЬ 25 сообщений?') - expect(confirm.mock.calls[1][0]).toContain('С подарком: 3 дн. доступа') - expect(screen.getByTestId('broadcast-status').textContent).toBe('Выбрано 100 · ждут 75 · дошло 25 · заблокировали 0 · отказ 0 · без ответа Telegram 0 · открыли по кнопке 4 · подарков выдано 3') + expect((await screen.findByTestId('broadcast-send-all')).textContent).toBe('Отправить — ждут 100 чел.') + expect(screen.getByTestId('broadcast-send-hint').textContent).toBe('Получатели записаны, но сообщения им ещё не ушли.') + expect(screen.getByTestId('broadcast-note')).toBeTruthy() + expect(screen.queryByTestId('broadcast-send-now')).toBeNull() + + await userEvent.click(screen.getByTestId('broadcast-send-all')) + expect(await screen.findByTestId('broadcast-sending')).toBeTruthy() + expect(api.prepare).toHaveBeenCalledTimes(2) }) - it('a declined confirmation picks nobody; an own name and an own address go as typed', async () => { + it('a declined confirmation sends nothing; an own name and an own address go as typed', async () => { confirm.mockReturnValue(false) api.prepare.mockResolvedValue(picked('autumn-news', 553, true)) render() @@ -189,20 +210,24 @@ describe('AdminBroadcastScreen — новая рассылка', () => { await userEvent.type(screen.getByLabelText('Имя кампании'), 'autumn-news') await next() - await userEvent.click(screen.getByTestId('broadcast-pick')) + expect(screen.getByTestId('broadcast-send-now').textContent).toBe('Отправить всем — 553 чел.') + await userEvent.click(screen.getByTestId('broadcast-send-now')) await waitFor(() => expect(api.prepare).toHaveBeenCalledTimes(1)) expect(api.prepare.mock.calls[0][0]).toMatchObject({ key: 'autumn-news', newBroadcast: false, buttonQuery: 'moduleId=cases&lessonId=1', giftDays: 0, sampleSize: null, dryRun: true }) - expect((screen.getByTestId('broadcast-send') as HTMLButtonElement).disabled).toBe(true) + expect(confirm.mock.calls[0][0]).toContain('ОТПРАВИТЬ всем: 553 чел. (доступ закончился)?') + expect(api.sendAll).not.toHaveBeenCalled() + expect(screen.getByTestId('broadcast-send-now')).toBeTruthy() expect(screen.getByTestId('broadcast-back')).toBeTruthy() }) }) describe('AdminBroadcastScreen — открытая рассылка', () => { it('opens on its sending with what is already done, and sends the rest of the group under the same name', async () => { - api.status.mockResolvedValueOnce({ ...status, pending: 0, sent: 100, opened: 30, gifted: 20 }).mockResolvedValue({ ...status, total: 553, pending: 453, sent: 100 }) + api.status.mockResolvedValue({ ...status, pending: 0, sent: 100, opened: 30, gifted: 20 }) + api.sendAll.mockResolvedValue({ ...status, total: 553, pending: 453, sent: 100, sendingAll: true }) api.prepare.mockResolvedValueOnce(picked(KEY, 453, true, 100)).mockResolvedValueOnce(picked(KEY, 453, false, 100)) render() @@ -211,32 +236,36 @@ describe('AdminBroadcastScreen — открытая рассылка', () => { expect(screen.getByTestId('broadcast-preview').textContent).toBe('Новые уроки про падежиОткрыть глаголы') expect(screen.getByTestId('broadcast-summary').textContent).toContain('Кнопка ведёт: Раздел «Глаголы». Подарок: 3 дн. доступа. Кому: доступ закончился — 553 чел.') expect(screen.getByTestId('broadcast-status').textContent).toContain('дошло 100 · заблокировали 0 · отказ 0 · без ответа Telegram 0 · открыли по кнопке 30 · подарков выдано 20') - expect(screen.getByTestId('broadcast-send-hint').textContent).toContain('Можно выбрать остальных или ещё одну группу') + expect(screen.getByTestId('broadcast-send-rest').textContent).toBe('Отправить остальным из группы «доступ закончился»') + for (const gone of ['broadcast-send-now', 'broadcast-send-all', 'broadcast-schedule', 'broadcast-when-later']) expect(screen.queryByTestId(gone)).toBeNull() expect(screen.queryByTestId('broadcast-next')).toBeNull() - await userEvent.click(screen.getByTestId('broadcast-pick')) - await waitFor(() => expect(api.prepare).toHaveBeenCalledTimes(2)) - expect(confirm.mock.calls[0][0]).toContain('Выбрать всех остальных: 453 чел.') + await userEvent.click(screen.getByTestId('broadcast-send-rest')) + await waitFor(() => expect(api.sendAll).toHaveBeenCalledWith(KEY)) + expect(confirm).toHaveBeenCalledTimes(1) + expect(confirm.mock.calls[0][0]).toContain('ОТПРАВИТЬ остальным: 453 чел.') expect(confirm.mock.calls[0][0]).toContain('Ещё 100 из этой группы уже в рассылке — второй раз они её не получат.') expect(api.prepare.mock.calls[1][0]).toMatchObject({ key: KEY, newBroadcast: false, audience: 'accessEnded', sampleSize: null, dryRun: false, buttonQuery: 'screen=verbs', giftDays: 3 }) - await waitFor(() => expect(screen.getByTestId('broadcast-status').textContent).toContain('Выбрано 553 · ждут 453')) + await waitFor(() => expect(screen.getByTestId('broadcast-status').textContent).toContain('Получателей 553 · ждут 453')) }) it('one more group joins the same campaign — the screen says nobody gets the message or the gift twice', async () => { api.status.mockResolvedValue({ ...status, pending: 0, sent: 100 }) api.prepare.mockResolvedValueOnce(picked(KEY, 40, true, 21)).mockResolvedValueOnce(picked(KEY, 40, false, 21)) + api.sendAll.mockResolvedValue({ ...status, total: 140, pending: 40, sent: 100, sendingAll: true }) render() const another = await screen.findByTestId('broadcast-another') expect(another.textContent).toContain('Это будет та же рассылка: кто уже получил сообщение, второй раз его не получит, и подарок достаётся человеку один раз') expect(within(another).queryByRole('radio', { name: /доступ закончился/ })).toBeNull() - expect(screen.queryByTestId('broadcast-pick-another')).toBeNull() + expect(screen.queryByTestId('broadcast-send-another')).toBeNull() await userEvent.click(within(another).getByRole('radio', { name: 'занимались за последние 30 дней · 61' })) - await userEvent.click(screen.getByTestId('broadcast-pick-another')) + expect(screen.getByTestId('broadcast-send-another').textContent).toBe('Отправить группе «занимались за последние 30 дней»') + await userEvent.click(screen.getByTestId('broadcast-send-another')) - await waitFor(() => expect(api.prepare).toHaveBeenCalledTimes(2)) - expect(confirm.mock.calls[0][0]).toContain('Выбрать ещё одну группу: 40 чел. (занимались за последние 30 дней)?') + await waitFor(() => expect(api.sendAll).toHaveBeenCalledWith(KEY)) + expect(confirm.mock.calls[0][0]).toContain('ОТПРАВИТЬ ещё одной группе: 40 чел. (занимались за последние 30 дней)?') expect(confirm.mock.calls[0][0]).toContain('Ещё 21 из этой группы уже в рассылке') expect(api.prepare.mock.calls[1][0]).toMatchObject({ key: KEY, audience: 'activeLately', anotherAudience: true, sampleSize: null, dryRun: false }) expect(api.send).not.toHaveBeenCalled() @@ -253,9 +282,9 @@ describe('AdminBroadcastScreen — открытая рассылка', () => { describe('AdminBroadcastScreen — готовая рассылка одним куском', () => { const READY = 'имя: myday-back\nкому: inactiveLong\nпроба: 50\nподарок: 7\nкнопка: Посмотреть первую серию\nадрес: moduleId=my-day&lessonId=1\n---\nНовый модуль — «Мой день»' - it('fills every step from the pasted text and picks the sample with exactly those parameters', async () => { + it('fills every step from the pasted text and one button sends the sample with exactly those parameters', async () => { api.prepare.mockImplementation(async body => picked('myday-back', 50, body.dryRun)) - api.status.mockResolvedValue({ ...status, key: 'myday-back', pending: 50 }) + api.sendAll.mockResolvedValue({ ...status, key: 'myday-back', total: 50, pending: 50, sendingAll: true }) render() await userEvent.click(screen.getByTestId('broadcast-paste-open')) await userEvent.click(screen.getByLabelText('Готовая рассылка')) @@ -265,8 +294,9 @@ describe('AdminBroadcastScreen — готовая рассылка одним к expect(title()).toBe('Отправка') expect(screen.getByTestId('broadcast-summary').textContent) .toBe('Кнопка ведёт: /?moduleId=my-day&lessonId=1. Подарок: 7 дн. доступа. Кому: не занимались больше 30 дней — 512 чел., сначала пробной группе из 50') - await userEvent.click(screen.getByTestId('broadcast-pick')) - await waitFor(() => expect(api.prepare).toHaveBeenCalledTimes(2)) + expect(screen.getByTestId('broadcast-send-now').textContent).toBe('Отправить пробной группе — 50 чел.') + await userEvent.click(screen.getByTestId('broadcast-send-now')) + await waitFor(() => expect(api.sendAll).toHaveBeenCalledWith('myday-back')) expect(api.prepare).toHaveBeenLastCalledWith({ key: 'myday-back', newBroadcast: false, audience: 'inactiveLong', message: 'Новый модуль — «Мой день»', buttonText: 'Посмотреть первую серию', buttonQuery: 'moduleId=my-day&lessonId=1', giftDays: 7, sampleSize: 50, dryRun: false @@ -326,6 +356,10 @@ describe('AdminBroadcastScreen — отправка по расписанию', 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') + // Время пришло вместе с текстом: главная кнопка уже «Запланировать», отправки «сейчас» на экране нет. + expect(screen.getByTestId('broadcast-when-later').getAttribute('aria-checked')).toBe('true') + expect(screen.getByTestId('broadcast-schedule').textContent).toBe('Запланировать на 28.11.2099 12:00 (Тбилиси)') + expect(screen.queryByTestId('broadcast-send-now')).toBeNull() await userEvent.click(screen.getByTestId('broadcast-schedule')) await waitFor(() => expect(api.prepare).toHaveBeenCalledTimes(2)) @@ -341,7 +375,7 @@ describe('AdminBroadcastScreen — отправка по расписанию', 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']) + for (const gone of ['broadcast-schedule', 'broadcast-when-now', 'broadcast-send-now', 'broadcast-send-all', 'broadcast-send-rest', 'broadcast-another', 'broadcast-status']) expect(screen.queryByTestId(gone)).toBeNull() expect(screen.getByTestId('broadcast-send-me')).toBeTruthy() expect(api.send).not.toHaveBeenCalled() @@ -352,6 +386,9 @@ describe('AdminBroadcastScreen — отправка по расписанию', 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() + expect(screen.queryByLabelText('День отправки')).toBeNull() + await userEvent.click(screen.getByTestId('broadcast-when-later')) + expect(screen.queryByTestId('broadcast-send-now')).toBeNull() 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')}`) @@ -374,6 +411,7 @@ describe('AdminBroadcastScreen — отправка по расписанию', 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.click(screen.getByTestId('broadcast-when-later')) await userEvent.clear(screen.getByLabelText('День отправки')) await userEvent.type(screen.getByLabelText('День отправки'), '2020-01-01') await userEvent.click(screen.getByTestId('broadcast-schedule')) @@ -402,8 +440,10 @@ describe('AdminBroadcastScreen — отправка по расписанию', expect(api.stop).toHaveBeenCalledWith('prices-last-days') expect(screen.getByTestId('broadcast-note').textContent).toBe('Расписание отменил. Сообщения не ушли.') expect(screen.queryByTestId('broadcast-scheduled')).toBeNull() + // Рассылка осталась записанной без получателей: её можно отправить сейчас или назначить другое время. + expect(screen.getByTestId('broadcast-send-now').textContent).toBe('Отправить всем — 565 чел.') + await userEvent.click(screen.getByTestId('broadcast-when-later')) 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 () => {