Spaces:
Running

File size: 7,346 Bytes
fb5a3a0
 
 
 
 
 
889e7bd
 
fb5a3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23a1787
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb5a3a0
 
23a1787
fb5a3a0
23a1787
fb5a3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
889e7bd
fb5a3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
"""LOCAL E2E — admin dashboard playlist controls (mobile viewport).

Verifies the owner's full-playlist-control set in the admin UI:
  A2  Lessons dialog shows ▲/▼ reorder buttons for each lesson
  A3  Clicking ▼ fires admin.moveLesson (POST) and the list re-renders swapped
  A4  «Import ALL playlist videos» button fires admin.importPlaylistVideos
  (A1 — the subscribe-gate settings card — was removed with the gate itself,
   owner contract 2026-12-03.)
Shots: /home/z/my-project/download/admin_controls_e2e/
Run: vite dev on 127.0.0.1:5173, then python3 scripts/admin_controls_e2e.py
"""
import json
import re
import subprocess
import sys
import time

from playwright.sync_api import sync_playwright

BASE = "http://127.0.0.1:5173"
OUT = "/home/z/my-project/download/admin_controls_e2e"
subprocess.run(["mkdir", "-p", OUT], check=True)

ADMIN_JSON = {"id": 9, "username": "admin", "name": "Admin", "role": "admin", "email": "a@b.c"}
COURSES = {"result": {"data": {"json": {"items": [{
    "id": 1, "slug": "etap-complete-course", "titleEn": "ETAP Complete Course", "titleAr": "كورس ETAP الشامل",
    "descriptionEn": "", "descriptionAr": "", "shortDescEn": None, "shortDescAr": None,
    "thumbnailUrl": None, "price": "1999", "isPremium": False, "isFeatured": False,
    "isPublished": True, "level": "beginner", "category": 1, "studentCount": 5,
    "createdAt": "2026-01-01T00:00:00.000Z", "updatedAt": "2026-01-01T00:00:00.000Z",
}], "total": 1}}}}
CATS = {"result": {"data": {"json": [{"id": 1, "nameEn": "Power", "nameAr": "قوى", "slug": "power"}]}}}

def lessons_payload(order):
    rows = [
        {"id": 101, "courseId": 1, "titleAr": "الدرس الأول", "titleEn": "Lesson One",
         "descriptionAr": "", "descriptionEn": "", "isFree": True, "durationMinutes": 10,
         "sortOrder": order[0], "isPublished": True},
        {"id": 102, "courseId": 1, "titleAr": "الدرس الثاني", "titleEn": "Lesson Two",
         "descriptionAr": "", "descriptionEn": "", "isFree": False, "durationMinutes": 12,
         "sortOrder": order[1], "isPublished": True},
    ]
    return {"result": {"data": {"json": {"items": rows}}}}

state = {"order": [1, 2], "moves": 0, "imports": 0}

def envelope_get(path, url):
    if path == "auth.me":
        return {"result": {"data": {"json": ADMIN_JSON}}}
    if path.startswith("admin.listCourses"):
        return COURSES
    if path.startswith("course.categories"):
        return CATS
    if path.startswith("admin.listLessons"):
        return lessons_payload(state["order"])
    return None


def envelope_post(path):
    if path.startswith("admin.moveLesson"):
        state["moves"] += 1
        state["order"] = state["order"][::-1]
        return {"result": {"data": {"json": {"success": True, "moved": True}}}}
    if path.startswith("admin.importPlaylistVideos"):
        state["imports"] += 1
        return {"result": {"data": {"json": {"created": 3, "skipped": 2, "total": 5, "verified": True, "titles": []}}}}
    return None


def envelope(method, path, url):
    if method == "GET":
        return envelope_get(path, url)
    if method == "POST":
        return envelope_post(path)
    return None

fails, notes = [], []
def check(name, cond, detail=""):
    print(f"[{'PASS' if cond else 'FAIL'}] {name}" + (f" — {detail}" if detail else ""))
    (notes if cond else fails).append((name, detail))

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
    ctx = browser.new_context(viewport={"width": 390, "height": 844}, is_mobile=True,
                              has_touch=True, locale="ar-EG", service_workers="block")
    ctx.add_cookies([{"name": "elbaz_auth_flag", "value": "1", "url": BASE}])
    pg = ctx.new_page()
    pg.add_init_script("try{localStorage.setItem('language','ar')}catch(e){}")

    def handler(route):
        url = route.request.url
        if "/api/trpc/" not in url:
            return route.continue_()
        method = route.request.method
        path = url.split("/api/trpc/")[1].split("?")[0]
        body = envelope(method, path, url)
        if body is None:
            # Benign fallback: ANY unmocked 401 from the dev backend would nuke
            # the session and bounce to /login — answer 200 with an empty json
            # instead (shape mismatches are harmless on tabs we never open).
            body = {"result": {"data": {"json": {} if method == "GET" else {"success": True}}}}
        return route.fulfill(status=200, content_type="application/json", body=json.dumps(body))

    pg.route("**/api/trpc/**", handler)
    pg.goto(BASE + "/admin", wait_until="domcontentloaded", timeout=45_000)
    pg.wait_for_timeout(4_000)
    pg.evaluate("() => document.querySelector('vite-error-overlay')?.remove()")
    pg.evaluate("() => document.querySelector('[data-testid=cookie-consent-backdrop]')?.click()")
    pg.wait_for_timeout(600)

    # Land on the courses tab — on mobile the sidebar is off-canvas: open the
    # top-bar hamburger first (same pattern as mobile_nav_e2e M3/M4).
    tab = pg.get_by_text("إدارة الكورسات", exact=False)
    if tab.count() == 0 or not tab.first.is_visible():
        burger = pg.locator("[data-testid=admin-mobile-menu]")
        burger.first.click()
        pg.wait_for_timeout(900)
        tab = pg.get_by_text("إدارة الكورسات", exact=False)
    if tab.count() > 0:
        tab.first.click()
        pg.wait_for_timeout(1_500)

    # (A1 removed with the subscribe gate — owner contract 2026-12-03.)

    # Open the lessons dialog
    lessons_btn = pg.get_by_role("button", name=re.compile("الدروس|Lessons")).first
    lessons_btn.click()
    pg.wait_for_timeout(1_800)
    dlg = pg.locator("[data-testid=import-all-playlist]")
    check("A2-pre) lessons dialog opened", dlg.count() > 0)

    up = pg.locator("[data-testid^=lesson-move-up-]")
    down = pg.locator("[data-testid^=lesson-move-down-]")
    check("A2) reorder buttons rendered for lessons", up.count() >= 1 and down.count() >= 2,
          f"up={up.count()} down={down.count()}")

    first_row_title = pg.locator("[data-testid^=lesson-move-down-]").first
    # click ▼ on the FIRST lesson → server swaps → invalidated list refetches swapped
    first_row_title.click()
    pg.wait_for_timeout(1_500)
    check("A3) admin.moveLesson fired", state["moves"] == 1, f"moves={state['moves']}")
    first_title = pg.locator("p", has_text="الدرس الثاني").first
    check("A3) list re-rendered in the swapped order", first_title.count() > 0)

    import_all = pg.locator("[data-testid=import-all-playlist]")
    check("A4-pre) import-all button visible", import_all.count() > 0 and import_all.first.is_visible())
    pg.evaluate("() => document.querySelector('[data-testid=import-all-playlist]')?.scrollIntoView({block:'center'})")
    pg.wait_for_timeout(400)
    import_all.first.click()
    pg.wait_for_timeout(1_500)
    check("A4) admin.importPlaylistVideos fired", state["imports"] == 1, f"imports={state['imports']}")
    pg.screenshot(path=f"{OUT}/A4_after_import_click.png")

    ctx.close()
    browser.close()

print("\n=== RESULT ===")
if fails:
    print("FAILURES:")
    for f in fails: print(" -", f)
    sys.exit(1)
print(f"ADMIN CONTROLS E2E PASSED ✓ ({len(notes)} checks)")