File size: 27,702 Bytes
97f32ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
import requests
import json
import uuid
import sys
import os
import time
from getpass import getpass
from tabulate import tabulate
from colorama import init, Fore, Style

# Initialize colorama
init()

BASE_URL = 'http://localhost:8000/'
API_URL = f"{BASE_URL}api/"
ADMIN_URL = f"{BASE_URL}admin_app/"
AUTH_URL = f"{BASE_URL}auth/"

class AdminAPITester:
    def __init__(self):
        self.session = requests.Session()
        self.token = None
        self.headers = {}
        self.user_role = None
        self.username = None
        self.last_response = None
        self.researchers = []
        self.paperworks = []
    
    def login(self, username, password):
        """Login to get authentication token"""
        try:
            print(f"{Fore.CYAN}Attempting to login...{Style.RESET_ALL}")
            response = self.session.post(
                f"{AUTH_URL}login/",
                data={'username': username, 'password': password},
                timeout=10
            )
            
            self.last_response = response
            
            if response.status_code == 200:
                data = response.json()
                self.token = data.get('token')
                self.headers = {'Authorization': f'Token {self.token}'}
                self.username = username
                
                # Assume admin role for this tool after successful login
                self.user_role = 'ADMIN'
                role_display = f"{Fore.GREEN}{self.user_role}{Style.RESET_ALL}"
                print(f"{Fore.GREEN}βœ… Logged in as {Fore.YELLOW}{username}{Fore.GREEN} (Role: {role_display}){Style.RESET_ALL}")
                return True
            else:
                print(f"{Fore.RED}❌ Login failed: {response.text}{Style.RESET_ALL}")
                return False
        except requests.exceptions.ConnectionError:
            print(f"{Fore.RED}❌ Connection error: Could not connect to the server. Is the server running?{Style.RESET_ALL}")
            return False
        except requests.exceptions.Timeout:
            print(f"{Fore.RED}❌ Timeout: The server took too long to respond.{Style.RESET_ALL}")
            return False
        except Exception as e:
            print(f"{Fore.RED}❌ Error during login: {str(e)}{Style.RESET_ALL}")
            return False
            

    
    def create_user(self, username, email, password, role="RESEARCHER", status="ACTIVE"):
        """Create a new user (Admin only)"""
        try:
            print(f"{Fore.CYAN}Creating new user: {username}...{Style.RESET_ALL}")
            
            data = {
                "username": username,
                "email": email,
                "password": password,
                "role": role,
                "status": status
            }
            
            response = requests.post(
                f"{AUTH_URL}register/",
                json=data,
                headers=self.headers,
                timeout=10
            )
            
            self.last_response = response
            
            if response.status_code in [200, 201]:
                user_data = response.json()
                print(f"{Fore.GREEN}βœ… User created successfully: {Fore.YELLOW}{username}{Style.RESET_ALL}")
                
                # If it's a researcher, add to our list
                if role == "RESEARCHER":
                    self.researchers.append(user_data)
                
                return user_data
            else:
                print(f"{Fore.RED}❌ Failed to create user: {response.text}{Style.RESET_ALL}")
                return None
        except requests.exceptions.ConnectionError:
            print(f"{Fore.RED}❌ Connection error: Could not connect to the server.{Style.RESET_ALL}")
            return None
        except requests.exceptions.Timeout:
            print(f"{Fore.RED}❌ Timeout: The server took too long to respond.{Style.RESET_ALL}")
            return None
        except Exception as e:
            print(f"{Fore.RED}❌ Error creating user: {str(e)}{Style.RESET_ALL}")
            return None
    
    def update_user_status(self, username, new_status):
        """Update a user's status (Admin only)"""
        try:
            print(f"{Fore.CYAN}Updating status for user {username} to {new_status}...{Style.RESET_ALL}")
            
            data = {"status": new_status}
            
            response = requests.patch(
                f"{ADMIN_URL}users/{username}/status/",
                json=data,
                headers=self.headers,
                timeout=10
            )
            
            self.last_response = response
            
            if response.status_code == 200:
                user_data = response.json()
                print(f"{Fore.GREEN}βœ… User status updated successfully: {Fore.YELLOW}{username}{Fore.GREEN} β†’ {Fore.YELLOW}{new_status}{Style.RESET_ALL}")
                return user_data
            else:
                print(f"{Fore.RED}❌ Failed to update user status: {response.text}{Style.RESET_ALL}")
                return None
        except requests.exceptions.ConnectionError:
            print(f"{Fore.RED}❌ Connection error: Could not connect to the server.{Style.RESET_ALL}")
            return None
        except requests.exceptions.Timeout:
            print(f"{Fore.RED}❌ Timeout: The server took too long to respond.{Style.RESET_ALL}")
            return None
        except Exception as e:
            print(f"{Fore.RED}❌ Error updating user status: {str(e)}{Style.RESET_ALL}")
            return None
    
    def list_users(self):
        """List all users (Admin only)"""
        try:
            print(f"{Fore.CYAN}Fetching users...{Style.RESET_ALL}")
            
            response = requests.get(
                f"{AUTH_URL}users/",
                headers=self.headers,
                timeout=10
            )
            
            self.last_response = response
            
            if response.status_code == 200:
                users = response.json()
                print(f"{Fore.GREEN}βœ… Retrieved {len(users)} users{Style.RESET_ALL}")
                
                # Store researchers for later use
                self.researchers = [u for u in users if u.get('role') == 'RESEARCHER']
                
                # Display users in a table
                table_data = []
                for user in users:
                    table_data.append([
                        user.get('id', 'N/A'),
                        user.get('username', 'N/A'),
                        user.get('email', 'N/A'),
                        user.get('role', 'N/A'),
                        user.get('status', 'N/A')
                    ])
                
                headers = ["ID", "Username", "Email", "Role", "Status"]
                print(tabulate(table_data, headers=headers, tablefmt="grid"))
                
                return users
            else:
                print(f"{Fore.RED}❌ Failed to get users: {response.text}{Style.RESET_ALL}")
                return None
        except requests.exceptions.ConnectionError:
            print(f"{Fore.RED}❌ Connection error: Could not connect to the server.{Style.RESET_ALL}")
            return None
        except requests.exceptions.Timeout:
            print(f"{Fore.RED}❌ Timeout: The server took too long to respond.{Style.RESET_ALL}")
            return None
        except Exception as e:
            print(f"{Fore.RED}❌ Error retrieving users: {str(e)}{Style.RESET_ALL}")
            return None
    
    def assign_paperwork(self, title, researcher_id, deadline=None):
        """Assign a new paperwork to a researcher (Admin only)"""
        try:
            print(f"{Fore.CYAN}Assigning new paperwork: {title}...{Style.RESET_ALL}")
            
            data = {
                "title": title,
                "researcher_id": researcher_id
            }
            
            if deadline:
                data["deadline"] = deadline
            
            response = self.session.post(
                f"{ADMIN_URL}paperworks/",
                json=data,
                headers=self.headers,
                timeout=10
            )
            
            self.last_response = response
            
            if response.status_code in [200, 201]:
                paperwork = response.json()
                print(f"{Fore.GREEN}βœ… Paperwork assigned successfully: {Fore.YELLOW}{title}{Style.RESET_ALL}")
                
                # Add to our list of paperworks
                self.paperworks.append(paperwork)
                
                # Display paperwork details
                print(f"\n{Fore.CYAN}Paperwork Details:{Style.RESET_ALL}")
                print(f"ID: {Fore.YELLOW}{paperwork.get('id')}{Style.RESET_ALL}")
                print(f"Title: {Fore.YELLOW}{paperwork.get('title')}{Style.RESET_ALL}")
                print(f"Status: {Fore.YELLOW}{paperwork.get('status')}{Style.RESET_ALL}")
                print(f"Assigned At: {Fore.YELLOW}{paperwork.get('assigned_at')}{Style.RESET_ALL}")
                if paperwork.get('deadline'):
                    print(f"Deadline: {Fore.YELLOW}{paperwork.get('deadline')}{Style.RESET_ALL}")
                if paperwork.get('deadline'):
                    print(f"Deadline: {Fore.YELLOW}{paperwork.get('deadline')}{Style.RESET_ALL}")
                
                return paperwork
            else:
                print(f"{Fore.RED}❌ Failed to assign paperwork: {response.text}{Style.RESET_ALL}")
                return None
        except requests.exceptions.ConnectionError:
            print(f"{Fore.RED}❌ Connection error: Could not connect to the server.{Style.RESET_ALL}")
            return None
        except requests.exceptions.Timeout:
            print(f"{Fore.RED}❌ Timeout: The server took too long to respond.{Style.RESET_ALL}")
            return None
        except Exception as e:
            print(f"{Fore.RED}❌ Error assigning paperwork: {str(e)}{Style.RESET_ALL}")
            return None
    
    def list_paperworks(self):
        """List all paperworks (Admin sees all)"""
        try:
            print(f"{Fore.CYAN}Fetching paperworks...{Style.RESET_ALL}")
            
            response = requests.get(
                f"{API_URL}paperworks/",
                headers=self.headers,
                timeout=10
            )
            
            self.last_response = response
            
            if response.status_code == 200:
                paperworks = response.json()
                print(f"{Fore.GREEN}βœ… Retrieved {len(paperworks)} paperworks{Style.RESET_ALL}")
                
                # Store for later use
                self.paperworks = paperworks
                
                # Display paperworks in a table
                table_data = []
                for pw in paperworks:
                    table_data.append([
                        pw.get('id'),
                        pw.get('title'),
                        pw.get('researcher', {}).get('username', 'N/A'),
                        pw.get('status')
                    ])
                
                headers = ["ID", "Title", "Researcher", "Status"]
                print(tabulate(table_data, headers=headers, tablefmt="grid"))
                
                return paperworks
            else:
                print(f"{Fore.RED}❌ Failed to get paperworks: {response.text}{Style.RESET_ALL}")
                return None
        except requests.exceptions.ConnectionError:
            print(f"{Fore.RED}❌ Connection error: Could not connect to the server.{Style.RESET_ALL}")
            return None
        except requests.exceptions.Timeout:
            print(f"{Fore.RED}❌ Timeout: The server took too long to respond.{Style.RESET_ALL}")
            return None
        except Exception as e:
            print(f"{Fore.RED}❌ Error retrieving paperworks: {str(e)}{Style.RESET_ALL}")
            return None
    
    def review_paperwork(self, paperwork_id, action, reviewer_notes, ai_percent_verified=None, reassign_to=None):
        """Review a paperwork (Admin only)"""
        try:
            print(f"{Fore.CYAN}Reviewing paperwork {paperwork_id}...{Style.RESET_ALL}")
            
            data = {
                "action": action,
                "reviewer_notes": reviewer_notes
            }
            
            if action == "APPROVE" and ai_percent_verified is not None:
                data["ai_percent_verified"] = ai_percent_verified
            
            if action == "REQUEST_CHANGES" and reassign_to is not None:
                data["reassign_to"] = reassign_to
            
            response = requests.post(
                f"{API_URL}paperworks/{paperwork_id}/review/",
                json=data,
                headers=self.headers,
                timeout=10
            )
            
            self.last_response = response
            
            if response.status_code == 200:
                result = response.json()
                status = result.get('status')
                status_color = Fore.GREEN if status == "APPROVED" else Fore.YELLOW
                print(f"{Fore.GREEN}βœ… Paperwork reviewed successfully. New status: {status_color}{status}{Style.RESET_ALL}")
                
                # Display review details
                print(f"\n{Fore.CYAN}Review Details:{Style.RESET_ALL}")
                print(f"Action: {Fore.YELLOW}{action}{Style.RESET_ALL}")
                print(f"Notes: {Fore.YELLOW}{reviewer_notes}{Style.RESET_ALL}")
                if ai_percent_verified:
                    print(f"AI Percentage: {Fore.YELLOW}{ai_percent_verified}%{Style.RESET_ALL}")
                
                return result
            else:
                print(f"{Fore.RED}❌ Failed to review paperwork: {response.text}{Style.RESET_ALL}")
                return None
        except requests.exceptions.ConnectionError:
            print(f"{Fore.RED}❌ Connection error: Could not connect to the server.{Style.RESET_ALL}")
            return None
        except requests.exceptions.Timeout:
            print(f"{Fore.RED}❌ Timeout: The server took too long to respond.{Style.RESET_ALL}")
            return None
        except Exception as e:
            print(f"{Fore.RED}❌ Error reviewing paperwork: {str(e)}{Style.RESET_ALL}")
            return None
    
    def get_reports_summary(self):
        """Get reports summary (Admin only)"""
        try:
            print(f"{Fore.CYAN}Fetching reports summary...{Style.RESET_ALL}")
            
            response = requests.get(
                f"{API_URL}reports/summary/",
                headers=self.headers,
                timeout=10
            )
            
            self.last_response = response
            
            if response.status_code == 200:
                summary = response.json()
                print(f"{Fore.GREEN}βœ… Retrieved reports summary{Style.RESET_ALL}")
                
                # Display summary in a table
                table_data = []
                for status, count in summary.items():
                    table_data.append([status, count])
                
                headers = ["Status", "Count"]
                print(tabulate(table_data, headers=headers, tablefmt="grid"))
                
                return summary
            else:
                print(f"{Fore.RED}❌ Failed to get reports summary: {response.text}{Style.RESET_ALL}")
                return None
        except requests.exceptions.ConnectionError:
            print(f"{Fore.RED}❌ Connection error: Could not connect to the server.{Style.RESET_ALL}")
            return None
        except requests.exceptions.Timeout:
            print(f"{Fore.RED}❌ Timeout: The server took too long to respond.{Style.RESET_ALL}")
            return None
        except Exception as e:
            print(f"{Fore.RED}❌ Error retrieving reports summary: {str(e)}{Style.RESET_ALL}")
            return None

def clear_screen():
    """Clear the terminal screen"""
    os.system('cls' if os.name == 'nt' else 'clear')

def print_header():
    """Print application header"""
    clear_screen()
    print(f"{Fore.CYAN}{'=' * 80}{Style.RESET_ALL}")
    print(f"{Fore.YELLOW}{'PMS ADMIN API TESTING TOOL':^80}{Style.RESET_ALL}")
    print(f"{Fore.CYAN}{'=' * 80}{Style.RESET_ALL}")

def main():
    print_header()
    print(f"{Fore.GREEN}Welcome to the PMS Admin API Testing Tool!{Style.RESET_ALL}")
    print(f"This tool allows you to test the admin-specific API endpoints of the PMS-Backend system.\n")
    
    # Check if server is running
    try:
        requests.get(BASE_URL, timeout=2)
    except requests.exceptions.ConnectionError:
        print(f"{Fore.RED}ERROR: Cannot connect to the server at {BASE_URL}{Style.RESET_ALL}")
        print(f"{Fore.YELLOW}Please make sure the server is running before using this tool.{Style.RESET_ALL}")
        print(f"\nTo start the server, run: {Fore.CYAN}python manage.py runserver{Style.RESET_ALL}")
        sys.exit(1)
    except Exception:
        pass
    
    tester = AdminAPITester()
    
    # Get login credentials
    print(f"\n{Fore.YELLOW}Please login with ADMIN credentials:{Style.RESET_ALL}")
    username = input(f"{Fore.CYAN}Username: {Style.RESET_ALL}")
    password = getpass(f"{Fore.CYAN}Password: {Style.RESET_ALL}")
    
    if not tester.login(username, password):
        print(f"\n{Fore.RED}Login failed or user is not an admin. Exiting...{Style.RESET_ALL}")
        time.sleep(2)
        sys.exit(1)
    
    # Store last used IDs for convenience
    last_paperwork_id = None
    last_researcher_id = None
    last_username = None
    
    # Test menu
    while True:
        print(f"\n{Fore.CYAN}{'=' * 80}{Style.RESET_ALL}")
        print(f"{Fore.YELLOW}{'ADMIN API TESTING MENU':^80}{Style.RESET_ALL}")
        print(f"{Fore.CYAN}{'=' * 80}{Style.RESET_ALL}")
        
        # Show user info
        if tester.username and tester.user_role:
            print(f"Logged in as: {Fore.YELLOW}{tester.username}{Style.RESET_ALL} | Role: {Fore.GREEN}{tester.user_role}{Style.RESET_ALL}")
        
        print(f"\n{Fore.CYAN}User Management:{Style.RESET_ALL}")
        print(f"{Fore.WHITE}1. List all users{Style.RESET_ALL}")
        print(f"{Fore.WHITE}2. Create new user{Style.RESET_ALL}")
        print(f"{Fore.WHITE}3. Update user status{Style.RESET_ALL}")
        
        print(f"\n{Fore.CYAN}Paperwork Management:{Style.RESET_ALL}")
        print(f"{Fore.WHITE}4. List all paperworks{Style.RESET_ALL}")
        print(f"{Fore.WHITE}5. Assign new paperwork{Style.RESET_ALL}")
        print(f"\n{Fore.CYAN}Reports:{Style.RESET_ALL}")
        print(f"{Fore.WHITE}6. Get reports summary{Style.RESET_ALL}")
        
        print(f"\n{Fore.WHITE}7. Clear screen{Style.RESET_ALL}")
        print(f"{Fore.RED}0. Exit{Style.RESET_ALL}")
        
        choice = input(f"\n{Fore.YELLOW}Enter your choice: {Style.RESET_ALL}")
        
        if choice == '1':
            # List all users
            users = tester.list_users()
            if users and len(users) > 0:
                # Store the first researcher ID for convenience
                researchers = [u for u in users if u.get('role') == 'RESEARCHER']
                if researchers:
                    last_researcher_id = researchers[0].get('id')
                    last_username = researchers[0].get('username')
        
        elif choice == '2':
            # Create new user
            print(f"\n{Fore.CYAN}Create New User:{Style.RESET_ALL}")
            username = input(f"Username: ")
            email = input(f"Email: ")
            password = getpass(f"Password: ")
            
            print(f"\nSelect role:")
            print(f"1. RESEARCHER")
            print(f"2. ADMIN")
            role_choice = input(f"Choice (default: 1): ") or "1"
            role = "ADMIN" if role_choice == "2" else "RESEARCHER"
            
            print(f"\nSelect status:")
            print(f"1. ACTIVE")
            print(f"2. FROZEN")
            print(f"3. INACTIVE")
            status_choice = input(f"Choice (default: 1): ") or "1"
            status = "ACTIVE"
            if status_choice == "2":
                status = "FROZEN"
            elif status_choice == "3":
                status = "INACTIVE"
            
            user = tester.create_user(username, email, password, role, status)
            if user and role == "RESEARCHER":
                last_researcher_id = user.get('id')
                last_username = user.get('username')
        
        elif choice == '3':
            # Update user status
            if last_username:
                print(f"Last used username: {Fore.YELLOW}{last_username}{Style.RESET_ALL}")
                use_last = input(f"Use this username? (y/n, default: y): ").lower() != 'n'
                if use_last:
                    username = last_username
                else:
                    username = input(f"Enter username to update: ")
            else:
                username = input(f"Enter username to update: ")
            
            print(f"\nSelect new status:")
            print(f"1. ACTIVE")
            print(f"2. FROZEN")
            print(f"3. INACTIVE")
            status_choice = input(f"Choice: ")
            status = "ACTIVE"
            if status_choice == "2":
                status = "FROZEN"
            elif status_choice == "3":
                status = "INACTIVE"
            
            tester.update_user_status(username, status)
            last_username = username
        
        elif choice == '4':
            # List all paperworks
            paperworks = tester.list_paperworks()
            if paperworks and len(paperworks) > 0:
                # Store the first paperwork ID for convenience
                last_paperwork_id = paperworks[0].get('id')
        
        elif choice == '5':
            # Assign new paperwork
            if not last_researcher_id:
                # Try to get researchers first
                tester.list_users()
            
            if tester.researchers:
                print(f"\n{Fore.CYAN}Available Researchers:{Style.RESET_ALL}")
                for i, r in enumerate(tester.researchers):
                    print(f"{i+1}. {r.get('username')} (ID: {r.get('id')})")
                
                researcher_choice = input(f"\nSelect researcher (1-{len(tester.researchers)}): ")
                try:
                    idx = int(researcher_choice) - 1
                    if 0 <= idx < len(tester.researchers):
                        researcher_id = tester.researchers[idx].get('id')
                        title = input(f"\nEnter paperwork title: ")
                        deadline_choice = input(f"Set deadline? (y/n, default: n): ").lower()
                        deadline = None
                        if deadline_choice == 'y':
                            deadline_date = input(f"Enter deadline date (YYYY-MM-DD): ")
                            deadline_time = input(f"Enter deadline time (HH:MM): ")
                            deadline = f"{deadline_date}T{deadline_time}:00Z"
                        paperwork = tester.assign_paperwork(title, researcher_id, deadline)
                        if paperwork:
                            last_paperwork_id = paperwork.get('id')
                    else:
                        print(f"{Fore.RED}Invalid selection.{Style.RESET_ALL}")
                except ValueError:
                    print(f"{Fore.RED}Please enter a valid number.{Style.RESET_ALL}")
            else:
                print(f"{Fore.RED}No researchers available. Please create a researcher first.{Style.RESET_ALL}")
        
        elif choice == '6':
            # Review paperwork
            if not last_paperwork_id:
                # Try to get paperworks first
                tester.list_paperworks()
            
            if tester.paperworks:
                if last_paperwork_id:
                    print(f"Last used paperwork ID: {Fore.YELLOW}{last_paperwork_id}{Style.RESET_ALL}")
                    use_last = input(f"Use this ID? (y/n, default: y): ").lower() != 'n'
                    if use_last:
                        paperwork_id = last_paperwork_id
                    else:
                        paperwork_id = input(f"Enter paperwork ID to review: ")
                else:
                    paperwork_id = input(f"Enter paperwork ID to review: ")
                
                print(f"\nSelect review action:")
                print(f"1. APPROVE")
                print(f"2. REQUEST_CHANGES")
                action_choice = input(f"Choice: ")
                
                if action_choice == "1":
                    action = "APPROVE"
                    ai_percent = input(f"Enter AI percentage verified (0-100): ")
                    try:
                        ai_percent = float(ai_percent)
                        notes = input(f"Enter reviewer notes: ")
                        tester.review_paperwork(paperwork_id, action, notes, ai_percent_verified=ai_percent)
                    except ValueError:
                        print(f"{Fore.RED}Please enter a valid number for AI percentage.{Style.RESET_ALL}")
                elif action_choice == "2":
                    action = "REQUEST_CHANGES"
                    notes = input(f"Enter reviewer notes: ")
                    reassign = input(f"Reassign to another researcher? (y/n, default: n): ").lower() == 'y'
                    
                    if reassign and tester.researchers:
                        print(f"\n{Fore.CYAN}Available Researchers:{Style.RESET_ALL}")
                        for i, r in enumerate(tester.researchers):
                            print(f"{i+1}. {r.get('username')} (ID: {r.get('id')})")
                        
                        researcher_choice = input(f"\nSelect researcher (1-{len(tester.researchers)}): ")
                        try:
                            idx = int(researcher_choice) - 1
                            if 0 <= idx < len(tester.researchers):
                                reassign_to = tester.researchers[idx].get('id')
                                tester.review_paperwork(paperwork_id, action, notes, reassign_to=reassign_to)
                            else:
                                print(f"{Fore.RED}Invalid selection.{Style.RESET_ALL}")
                        except ValueError:
                            print(f"{Fore.RED}Please enter a valid number.{Style.RESET_ALL}")
                    else:
                        tester.review_paperwork(paperwork_id, action, notes)
                else:
                    print(f"{Fore.RED}Invalid action choice.{Style.RESET_ALL}")
                
                last_paperwork_id = paperwork_id
            else:
                print(f"{Fore.RED}No paperworks available. Please assign a paperwork first.{Style.RESET_ALL}")
        
        elif choice == '7':
            # Get reports summary
            tester.get_reports_summary()
        
        elif choice == '8':
            # Clear screen
            print_header()
        
        elif choice == '0':
            # Exit
            print(f"\n{Fore.GREEN}Thank you for using the PMS Admin API Testing Tool. Goodbye!{Style.RESET_ALL}")
            sys.exit(0)
        
        else:
            print(f"{Fore.RED}Invalid choice. Please try again.{Style.RESET_ALL}")
        
        input(f"\n{Fore.CYAN}Press Enter to continue...{Style.RESET_ALL}")

if __name__ == "__main__":
    main()