nomadro/scripts/check-admin-editing.py
Eric 499f2d3e26 Ship coffeechat scheduling, notify PB access, and social/admin UI polish for .com.
Document the 2026-11-05 UI/UX upgrade and keep roster/live gates aligned with face-check and presence.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 18:19:37 +08:00

197 lines
11 KiB
Python

"""Browser regression checks with mocked APIs; never writes production data."""
import copy
import json
import sys
from pathlib import Path
from urllib.parse import urlparse
from playwright.sync_api import sync_playwright, expect
sys.stdout.reconfigure(encoding='utf-8')
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'artifacts/uiux-upgrade'
OUT.mkdir(parents=True, exist_ok=True)
BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://localhost:5174'
report = {'base': BASE, 'checks': [], 'pageErrors': []}
class Backend:
def __init__(self):
self.config = {'version': 10, 'modules': {}, 'flags': {'payEnabled': True, 'socialTrialEnabled': True},
'copy': {'vipPriceFen': 8800, 'vipCta': '立即加入 · ¥88', 'homeBrand': 'Nomadro', 'homeTagline': 'Original tagline', 'homeLead': 'Original lead', 'xHandle': 'nomadro', 'socialTrial': {'enabled': True, 'chatMessages': 1, 'dateViews': 5, 'coffeeBookings': 0, 'mapOpens': 3}}, 'vipEntries': {}}
self.audience = {'defaultLane': 'intl', 'cn': {'payEnabled': True, 'socialFollow': True, 'followChannel': 'wechat', 'vipCta': '原始 CTA', 'homeLead': '原始导语'}, 'intl': {'payEnabled': True, 'socialFollow': True, 'followChannel': 'x', 'vipCta': 'Join VIP', 'homeLead': 'Original lead'}}
self.blog = {'moduleEnabled': True, 'adsenseEnabled': False, 'adsenseClientId': '', 'adsensePublisherId': '', 'adsenseSlotBlogMid': '', 'adsenseSlotBlogEnd': '', 'ops': {'note': '', 'heroLead': ''}, 'counts': {'posts': 0}}
self.mutations = []
self.failure = None
def route(self, route):
request = route.request
path = urlparse(request.url).path
if not path.startswith('/api/'): return route.continue_()
if path == '/api/config/stream':
return route.fulfill(status=200, content_type='text/event-stream', body=': mock\n\n')
body = request.post_data_json if request.method in ['POST', 'PUT', 'PATCH'] and request.post_data else {}
if request.method in ['PUT', 'PATCH', 'DELETE']:
self.mutations.append({'path': path, 'body': body})
if self.failure:
failure, self.failure = self.failure, None
if failure == 'malformed': return route.fulfill(status=200, content_type='application/json', body='{broken')
return route.fulfill(status=409, json={'detail': '配置已更新,请加载最新配置后重试;当前草稿尚未保存'})
if body.get('expectedVersion') != self.config['version']:
return route.fulfill(status=409, json={'detail': 'stale config'})
self.config['version'] += 1
if path.endswith('/weapp/switches'):
for key in ['copy', 'flags', 'modules', 'vipEntries']:
self.config.setdefault(key, {}).update(body.get(key, {}))
elif path.endswith('/audience'):
for lane in ['cn', 'intl']: self.audience[lane].update(body.get(lane, {}))
elif path.endswith('/blog/ops'):
for key, value in body.items():
if key in ['note', 'heroLead']: self.blog['ops'][key] = value
elif key != 'expectedVersion': self.blog[key] = value
if path.endswith('/weapp/switches'): data = self.config
elif path.endswith('/audience'): data = {**self.audience, 'version': self.config['version']}
elif path.endswith('/config/meta'): data = {'version': self.config['version']}
elif path.endswith('/blog/overview') or path.endswith('/blog/ops'): data = {**self.blog, 'version': self.config['version']}
elif path.endswith('/orders') or path.endswith('/users'): data = []
else: data = {'ok': True, 'items': [], 'messages': [], 'counts': {}, 'total': 0}
route.fulfill(json=copy.deepcopy(data))
def run_check(name, function):
try:
function()
report['checks'].append({'name': name, 'passed': True})
except Exception as error:
report['checks'].append({'name': name, 'passed': False, 'error': str(error)[:1800]})
print(json.dumps(report['checks'][-1], ensure_ascii=False), flush=True)
with sync_playwright() as p:
browser = p.chromium.launch()
def scenario(path, callback):
backend = Backend()
context = browser.new_context(viewport={'width': 1440, 'height': 1000})
context.add_init_script("localStorage.setItem('nomadro_admin_com_token', 'mock-admin-token')")
context.route('**/api/**', backend.route)
page = context.new_page()
page.set_default_timeout(10000)
page.set_default_navigation_timeout(45000)
page.on('pageerror', lambda error: report['pageErrors'].append(str(error)))
page.on('dialog', lambda dialog: dialog.accept())
try:
page.goto(BASE + path, wait_until='domcontentloaded')
page.locator('.com-page').wait_for()
callback(page, backend)
finally: context.close()
def price(page, backend):
amount = page.locator('.com-pricing-form input[type=number]')
chat = page.get_by_label('群聊可发句数')
expect(amount).to_have_value('88')
chat.fill('7')
amount.fill('99')
page.get_by_role('button', name='保存动态价格', exact=True).click()
expect(page.get_by_role('status').filter(has_text='动态价格已更新')).to_be_visible()
expect(chat).to_have_value('7')
amount.fill('108')
page.get_by_role('button', name='保存体验次数', exact=True).click()
expect(page.get_by_role('status').filter(has_text='体验已保存')).to_be_visible()
expect(amount).to_have_value('108')
expect(chat).to_have_value('7')
page.get_by_role('button', name='重置草稿', exact=True).click()
expect(amount).to_have_value('99')
amount.fill('')
expect(page.get_by_role('button', name='保存动态价格', exact=True)).to_be_disabled()
expect(amount).to_have_attribute('aria-invalid', 'true')
page.get_by_role('button', name='重置草稿', exact=True).click()
chat.fill('9')
backend.config['version'] += 1
expect(page.get_by_text('配置已在其他页面更新。请刷新后再保存,避免覆盖。')).to_be_visible(timeout=7000)
expect(chat).to_have_value('9')
expect(page.get_by_role('button', name='保存体验次数', exact=True)).to_be_disabled()
page.screenshot(path=str(OUT / 'admin-draft-conflict-desktop.png'), full_page=True)
run_check('Pricing: independent drafts, numeric validation and live conflict retention', lambda: scenario('/intl/pricing', price))
def navigation(page, backend):
field = page.locator('.com-pricing-form input[type=number]')
expect(field).to_have_value('88')
field.fill('99')
page.locator('.com-nav a[href="/intl/orders"]').click()
expect(page.get_by_role('dialog')).to_be_visible()
page.get_by_role('button', name='继续编辑', exact=True).click()
expect(field).to_have_value('99')
page.get_by_role('button', name='退出', exact=True).click()
expect(page.get_by_role('dialog')).to_be_visible()
page.keyboard.press('Escape')
assert page.evaluate("localStorage.getItem('nomadro_admin_com_token')") == 'mock-admin-token'
page.locator('.com-nav a[href="/intl/orders"]').click()
page.get_by_role('button', name='放弃修改并离开', exact=True).click()
expect(page).to_have_url(BASE + '/intl/orders')
run_check('Navigation: cancel, Escape, discard and logout keep the correct session', lambda: scenario('/intl/pricing', navigation))
def switches(page, backend):
page.get_by_role('button', name='文案', exact=True).click()
lead = page.get_by_label('导语', exact=True)
expect(lead).to_have_value('Original lead')
lead.fill('Unpublished draft')
page.get_by_role('button', name='功能', exact=True).click()
page.get_by_label('支付总开关', exact=True).click()
expect(page.get_by_role('status').filter(has_text='支付总开关已关闭')).to_be_visible()
page.get_by_role('button', name='文案', exact=True).click()
expect(lead).to_have_value('Unpublished draft')
backend.failure = 'malformed'
page.get_by_role('button', name='保存文案', exact=True).click()
expect(page.get_by_role('alert')).to_contain_text('服务返回异常')
expect(lead).to_have_value('Unpublished draft')
page.get_by_role('button', name='保存文案', exact=True).click()
expect(page.get_by_role('status').filter(has_text='文案已保存')).to_be_visible()
run_check('Switches: partial save preserves copy, malformed response fails visibly, retry works', lambda: scenario('/intl/switches', switches))
def audience(page, backend):
field = page.get_by_label('首页导语', exact=True)
expect(field).to_have_value('Original lead')
field.fill('Keep this audience draft')
page.get_by_label('pay', exact=True).click()
expect(page.get_by_role('status').filter(has_text='支付已关')).to_be_visible()
expect(field).to_have_value('Keep this audience draft')
backend.failure = 'conflict'
page.get_by_role('button', name='保存文案', exact=True).click()
expect(page.get_by_role('alert')).to_contain_text('配置已更新')
expect(field).to_have_value('Keep this audience draft')
run_check('Audience: toggle and failed save preserve copy, sends expected version', lambda: scenario('/intl/audience', audience))
def blog(page, backend):
page.get_by_role('button', name='模块 / 文案', exact=True).click()
note = page.get_by_label('运营备注(仅后台)', exact=True)
expect(note).to_have_value('')
note.fill('Unpublished blog note')
page.get_by_label('博客模块开关', exact=True).click()
expect(page.get_by_role('status').filter(has_text='Blog 模块已关')).to_be_visible()
expect(note).to_have_value('Unpublished blog note')
page.get_by_role('button', name='AdSense', exact=True).click()
page.get_by_label('clientId (ca-pub-…)', exact=True).fill('invalid')
before = len(backend.mutations)
page.get_by_role('button', name='保存 AdSense', exact=True).click()
expect(page.get_by_role('alert')).to_contain_text('clientId 应为')
assert len(backend.mutations) == before
page.set_viewport_size({'width': 390, 'height': 844})
page.locator('.com-topbar-menu').click()
page.locator('.com-nav a[href="/intl/orders"]').click()
expect(page.get_by_role('dialog')).to_be_visible()
assert page.evaluate('document.documentElement.scrollWidth <= innerWidth + 1')
page.screenshot(path=str(OUT / 'admin-unsaved-mobile.png'), full_page=True)
run_check('Blog: partial draft retention, client validation, mobile exit dialog', lambda: scenario('/intl/blog', blog))
browser.close()
(OUT / 'admin-editing.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(report, ensure_ascii=False))
raise SystemExit(0 if all(row['passed'] for row in report['checks']) and not report['pageErrors'] else 1)