Конфликты сведены: таблицы topups рядом с админскими, старая таблица платежей сохраняет CSV и получает колонки пополнений, окно остатка — ссылка на цены и кнопка пополнения; тесты 404 и админской таблицы приведены к текущим ответам с request_id. Co-Authored-By: Claude Code <noreply@anthropic.com>
127 lines
6.6 KiB
Python
127 lines
6.6 KiB
Python
"""Пополнение счёта онлайн — страницы (план, шаг 5): статика, как test_chat_page_shows_account.
|
|
|
|
Глазами (Playwright) страницы смотрятся отдельно — шаг 8 плана. Здесь — что кнопка, окно
|
|
суммы, тексты и вызовы ручек на месте, а внутренних слов нет.
|
|
"""
|
|
|
|
import os
|
|
import re
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
|
|
def _read(name):
|
|
return open(os.path.join(ROOT, "static", name), encoding="utf-8").read()
|
|
|
|
|
|
def test_chat_has_topup_button_modal_and_flow():
|
|
"""Кнопка в окне остатка, окно суммы с пресетами с сервера и своей суммой, строка про
|
|
чек и физлицо, уход на оплату с запоминанием номера. Порча: убрать окно."""
|
|
html = _read("chat.html")
|
|
pop = html[html.index('id="balance-popover"'):]
|
|
pop = pop[:pop.index("</div>\n </div>") + 20]
|
|
assert "Пополнить счёт" in pop
|
|
modal = html[html.index('id="topup-modal"'):]
|
|
for text in ("Чек придёт на", "Оплата от физического лица", "Перейти к оплате",
|
|
'id="topup-amount"', "info@infosmeta.ru"):
|
|
assert text in modal, text
|
|
fn = html[html.index("function openTopupModal"):]
|
|
assert "topup.presets" in fn and "topup.min" in fn and "topup.max" in fn
|
|
go = html[html.index("async function goTopup"):]
|
|
go = go[:go.index("\n}\n")]
|
|
assert "'/api/topups'" in go
|
|
assert go.index("last_topup_id") < go.index("location.href")
|
|
assert "reasonOrText" in go # отказ — словами сервера
|
|
|
|
|
|
def test_chat_offers_topup_on_refusal_and_after_return():
|
|
"""Отказ 402 при включённом пополнении предлагает кнопку; «Попробовать снова» со страницы
|
|
результата открывает окно суммы. Порча: не звать предложение после 402."""
|
|
html = _read("chat.html")
|
|
chat402 = html[html.index("if (r.status === 402) {\n // Вопрос не ушёл"):]
|
|
chat402 = chat402[:chat402.index("return;")]
|
|
assert "offerTopup(" in chat402
|
|
assert "get('topup')" in html
|
|
# Ручной режим — решение оператора: пополнение ему не предлагаем (сервер блок не шлёт),
|
|
# а текст окна остатка при пополнении не зовёт писать на почту.
|
|
assert "b.topup" in html[html.index("function openBalancePopover"):]
|
|
|
|
|
|
def test_stats_has_topup_link():
|
|
html = _read("stats.html")
|
|
link = html[html.index("function topupLink"):]
|
|
link = link[:link.index("\n}\n")]
|
|
assert "Пополнить счёт" in link and "/?topup=1" in link
|
|
fn = html[html.index("function renderAccount"):]
|
|
fn = fn[:fn.index("\n}\n")]
|
|
assert "if (topup) box.append(topupLink())" in fn and "!acc && topup" in fn
|
|
assert "(res.body.limits || {}).topup" in html
|
|
|
|
|
|
def test_admin_payments_columns_refund_and_settings():
|
|
"""«Платежи»: колонки платёжки, зачислено/возвращено/можно вернуть, кнопка «Возврат
|
|
проведён»; настройки пределов пополнения. Порча: убрать кнопку."""
|
|
html = _read("admin.html")
|
|
fn = html[html.index("async function loadPayments"):]
|
|
fn = fn[:fn.index("\nloadPayments();")]
|
|
for text in ("Платёжка", "Зачислено", "Возвращено", "Можно вернуть"):
|
|
assert text in html, text
|
|
for text in ("Возврат проведён", "/api/admin/topups/", "refundable_rub", "Аннулир"):
|
|
assert text in fn, text
|
|
assert "topup_presets" in html and "topup_min_rub" in html and "topup_max_rub" in html
|
|
|
|
|
|
def test_pages_have_no_kitchen_words():
|
|
"""Человеку — ни имени платёжки, ни комиссий. Порча: написать «Robokassa» в окне."""
|
|
for name in ("chat.html", "stats.html", "payment_result.html"):
|
|
text = _read(name).lower()
|
|
assert "robokassa" not in text and "комисси" not in text, name
|
|
assert not re.search(r"webhook|вебхук", _read("payment_result.html").lower())
|
|
|
|
|
|
def _run_stats_balance(limits):
|
|
"""Run the real renderBalance/el from stats.html in node with a minimal DOM stub."""
|
|
import json
|
|
import shutil
|
|
import subprocess
|
|
import pytest
|
|
if not shutil.which("node"):
|
|
pytest.skip("нет node")
|
|
html = _read("stats.html")
|
|
def fn(name):
|
|
body = html[html.index(f"function {name}("):]
|
|
return body[:body.index("\n}\n") + 3]
|
|
js = """
|
|
const nodes = {};
|
|
function mk() { return {textContent: '', className: '', children: [],
|
|
append(...xs) { this.children.push(...xs); }, set hidden(v) {}}; }
|
|
const document = {createElement: () => mk(),
|
|
getElementById: id => (nodes[id] = nodes[id] || mk())};
|
|
""" + fn("el") + fn("renderBalance") + f"""
|
|
renderBalance({json.dumps(limits)});
|
|
console.log(nodes.balance.children.map(c => c.textContent).join(' '));
|
|
"""
|
|
out = subprocess.run(["node", "-e", js], capture_output=True, text=True, timeout=20)
|
|
assert out.returncode == 0, out.stderr
|
|
return out.stdout
|
|
|
|
|
|
def test_stats_exhausted_with_topup_does_not_send_to_mail():
|
|
"""«Баланс исчерпан» на /stats при доступном пополнении зовёт пополнить, а не писать на
|
|
почту (как в чате); без пополнения — почта. Порча: оставить почту при topup."""
|
|
with_topup = _run_stats_balance({"read_only": True, "topup": {"enabled": True}})
|
|
assert "Пополнить" in with_topup and "info@infosmeta.ru" not in with_topup
|
|
without = _run_stats_balance({"read_only": True})
|
|
assert "info@infosmeta.ru" in without
|
|
|
|
|
|
def test_admin_payments_table_scrolls_instead_of_clipping():
|
|
"""28.10.2026 глазами: на 1280 точках таблица «Платежей» шире области, а у .main
|
|
overflow-x: hidden — кнопка «Возврат проведён» обрезалась и не нажималась.
|
|
Таблица обязана жить в .table-wrap, как другие широкие таблицы."""
|
|
html = _read("admin.html")
|
|
page = html[html.index('id="page-payments"'):]
|
|
page = page[:page.index('<p class="note">')]
|
|
wrap = page.index('class="table-wrap"')
|
|
assert wrap < page.index('<table id="payments">')
|