Skip to content

Commit 01a819f

Browse files
committed
clenup
1 parent 2814527 commit 01a819f

File tree

1 file changed

+51
-53
lines changed

1 file changed

+51
-53
lines changed

scripts/maintenance/pre_registration.py

Lines changed: 51 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -39,27 +39,25 @@
3939
)
4040

4141

42-
# Message helper functions
43-
def print_info(message: str) -> None:
42+
def _print_info(message: str) -> None:
4443
typer.secho(message, fg=typer.colors.BLUE)
4544

4645

47-
def print_success(message: str) -> None:
46+
def _print_success(message: str) -> None:
4847
typer.secho(message, fg=typer.colors.GREEN)
4948

5049

51-
def print_error(message: str) -> None:
50+
def _print_error(message: str) -> None:
5251
typer.secho(f"Error: {message}", fg=typer.colors.RED, err=True)
5352

5453

55-
class LoginCredentials(BaseModel):
54+
class LoginCredentialsRequest(BaseModel):
5655
"""Request body model for login endpoint"""
5756

5857
email: EmailStr
5958
password: SecretStr
6059

6160

62-
# TODO: move classes to models-library from webserver and use them here
6361
class PreRegisterUserRequest(BaseModel):
6462
"""Request body model for pre-registering a user"""
6563

@@ -90,7 +88,7 @@ async def _login(
9088
"""Login user with the provided credentials"""
9189
path = "/v0/auth/login"
9290

93-
credentials = LoginCredentials(email=email, password=password)
91+
credentials = LoginCredentialsRequest(email=email, password=password)
9492

9593
response = await client.post(
9694
path,
@@ -196,15 +194,15 @@ async def _pre_register_users_from_list(
196194
extras=user_data.extras,
197195
)
198196
results.append(result)
199-
print_success(f"Successfully pre-registered user: {user_data.email}")
197+
_print_success(f"Successfully pre-registered user: {user_data.email}")
200198

201199
except HTTPStatusError as e:
202-
print_error(
200+
_print_error(
203201
f"Failed to pre-register user {user_data.email} with {e.response.status_code}: {e.response.text}"
204202
)
205203

206204
except Exception as e:
207-
print_error(f"Failed to pre-register user {user_data.email}: {str(e)}")
205+
_print_error(f"Failed to pre-register user {user_data.email}: {str(e)}")
208206

209207
return results
210208

@@ -226,16 +224,16 @@ async def _create_invitations_from_list(
226224
extra_credits=extra_credits,
227225
)
228226
results.append({"email": email, "invitation": result})
229-
print_success(f"Successfully generated invitation for: {email}")
227+
_print_success(f"Successfully generated invitation for: {email}")
230228

231229
except HTTPStatusError as e:
232-
print_error(
230+
_print_error(
233231
f"Failed to generate invitation for {email} with {e.response.status_code}: {e.response.text}"
234232
)
235233
results.append({"email": email, "error": str(e)})
236234

237235
except Exception as e:
238-
print_error(f"Failed to generate invitation for {email}: {str(e)}")
236+
_print_error(f"Failed to generate invitation for {email}: {str(e)}")
239237
results.append({"email": email, "error": str(e)})
240238

241239
return results
@@ -255,30 +253,30 @@ async def run_pre_registration(
255253
users_data_raw
256254
)
257255
except json.JSONDecodeError:
258-
print_error(f"{users_file_path} is not a valid JSON file")
256+
_print_error(f"{users_file_path} is not a valid JSON file")
259257
sys.exit(os.EX_DATAERR)
260258
except ValidationError as e:
261-
print_error(f"Invalid user data format: {e}")
259+
_print_error(f"Invalid user data format: {e}")
262260
sys.exit(os.EX_DATAERR)
263261
except Exception as e:
264-
print_error(f"Reading or parsing {users_file_path}: {str(e)}")
262+
_print_error(f"Reading or parsing {users_file_path}: {str(e)}")
265263
sys.exit(os.EX_IOERR)
266264

267265
# Create an HTTP client and process
268266
async with AsyncClient(base_url=base_url, timeout=30) as client:
269267
try:
270268
# Login as admin
271-
print_info(f"Logging in as {admin_email}...")
269+
_print_info(f"Logging in as {admin_email}...")
272270
await _login(
273271
client=client,
274272
email=admin_email,
275273
password=admin_password,
276274
)
277275

278276
# Pre-register users
279-
print_info(f"Pre-registering {len(users_data)} users...")
277+
_print_info(f"Pre-registering {len(users_data)} users...")
280278
results = await _pre_register_users_from_list(client, users_data)
281-
print_success(f"Successfully pre-registered {len(results)} users")
279+
_print_success(f"Successfully pre-registered {len(results)} users")
282280

283281
# Dump results to a file
284282
timestamp = datetime.datetime.now(tz=datetime.UTC).strftime("%Y%m%d_%H%M%S")
@@ -287,14 +285,14 @@ async def run_pre_registration(
287285
output_path = users_file_path.parent / output_filename
288286

289287
output_path.write_text(json.dumps(results, indent=1))
290-
print_success(f"Results written to {output_path}")
288+
_print_success(f"Results written to {output_path}")
291289

292290
# Logout
293-
print_info("Logging out...")
291+
_print_info("Logging out...")
294292
await _logout_current_user(client)
295293

296294
except Exception as e:
297-
print_error(f"{str(e)}")
295+
_print_error(f"{str(e)}")
298296
sys.exit(os.EX_SOFTWARE)
299297

300298

@@ -310,41 +308,41 @@ async def run_create_invitation(
310308
async with AsyncClient(base_url=base_url, timeout=30) as client:
311309
try:
312310
# Login as admin
313-
print_info(f"Logging in as {admin_email}...")
311+
_print_info(f"Logging in as {admin_email}...")
314312
await _login(
315313
client=client,
316314
email=admin_email,
317315
password=admin_password,
318316
)
319317

320318
# Generate invitation
321-
print_info(f"Generating invitation for {guest_email}...")
319+
_print_info(f"Generating invitation for {guest_email}...")
322320
result = await _create_invitation(
323321
client, guest_email, trial_days=trial_days, extra_credits=extra_credits
324322
)
325323

326324
# Display invitation link
327-
print_success(f"Successfully generated invitation for {guest_email}")
328-
print_success(f"Invitation link: {result.get('link', 'No link returned')}")
325+
_print_success(f"Successfully generated invitation for {guest_email}")
326+
_print_success(f"Invitation link: {result.get('link', 'No link returned')}")
329327

330328
# Save result to a file
331329
timestamp = datetime.datetime.now(tz=datetime.UTC).strftime("%Y%m%d_%H%M%S")
332330
output_filename = f"invitation_{guest_email.split('@')[0]}_{timestamp}.json"
333331
output_path = Path(output_filename)
334332
output_path.write_text(json.dumps(result, indent=1))
335-
print_success(f"Result written to {output_path}")
333+
_print_success(f"Result written to {output_path}")
336334

337335
# Logout
338-
print_info("Logging out...")
336+
_print_info("Logging out...")
339337
await _logout_current_user(client)
340338

341339
except HTTPStatusError as e:
342-
print_error(
340+
_print_error(
343341
f"Failed to generate invitation with {e.response.status_code}: {e.response.text}"
344342
)
345343
sys.exit(os.EX_SOFTWARE)
346344
except Exception as e:
347-
print_error(f"{str(e)}")
345+
_print_error(f"{str(e)}")
348346
sys.exit(os.EX_SOFTWARE)
349347

350348

@@ -371,7 +369,7 @@ async def run_bulk_create_invitation(
371369
# List of objects with email property (like pre-registered users)
372370
data = [item["email"].lower() for item in data]
373371
else:
374-
print_error(
372+
_print_error(
375373
"File must contain either a list of email strings or objects with 'email' property"
376374
)
377375
sys.exit(os.EX_DATAERR)
@@ -380,38 +378,38 @@ async def run_bulk_create_invitation(
380378
list[Annotated[BeforeValidator(lambda s: s.lower()), EmailStr]]
381379
).validate_python(data)
382380
else:
383-
print_error("File must contain a JSON array")
381+
_print_error("File must contain a JSON array")
384382
sys.exit(os.EX_DATAERR)
385383

386384
except json.JSONDecodeError:
387-
print_error(f"{emails_file_path} is not a valid JSON file")
385+
_print_error(f"{emails_file_path} is not a valid JSON file")
388386
sys.exit(os.EX_DATAERR)
389387
except ValidationError as e:
390-
print_error(f"Invalid email format: {e}")
388+
_print_error(f"Invalid email format: {e}")
391389
sys.exit(os.EX_DATAERR)
392390
except Exception as e:
393-
print_error(f"Reading or parsing {emails_file_path}: {str(e)}")
391+
_print_error(f"Reading or parsing {emails_file_path}: {str(e)}")
394392
sys.exit(os.EX_IOERR)
395393

396394
# Create an HTTP client and process
397395
async with AsyncClient(base_url=base_url, timeout=30) as client:
398396
try:
399397
# Login as admin
400-
print_info(f"Logging in as {admin_email}...")
398+
_print_info(f"Logging in as {admin_email}...")
401399
await _login(
402400
client=client,
403401
email=admin_email,
404402
password=admin_password,
405403
)
406404

407405
# Generate invitations
408-
print_info(f"Generating invitations for {len(emails)} users...")
406+
_print_info(f"Generating invitations for {len(emails)} users...")
409407
results = await _create_invitations_from_list(
410408
client, emails, trial_days=trial_days, extra_credits=extra_credits
411409
)
412410

413411
successful = sum(1 for r in results if "invitation" in r)
414-
print_success(
412+
_print_success(
415413
f"Successfully generated {successful} invitations out of {len(emails)} users"
416414
)
417415

@@ -422,14 +420,14 @@ async def run_bulk_create_invitation(
422420
output_path = emails_file_path.parent / output_filename
423421

424422
output_path.write_text(json.dumps(results, indent=1))
425-
print_success(f"Results written to {output_path}")
423+
_print_success(f"Results written to {output_path}")
426424

427425
# Logout
428-
print_info("Logging out...")
426+
_print_info("Logging out...")
429427
await _logout_current_user(client)
430428

431429
except Exception as e:
432-
print_error(f"{str(e)}")
430+
_print_error(f"{str(e)}")
433431
sys.exit(os.EX_SOFTWARE)
434432

435433

@@ -483,15 +481,15 @@ def pre_register(
483481
firstName, lastName, email, and optionally institution, phone, address, city, state, postalCode, country.
484482
"""
485483
if not users_file.exists():
486-
print_error(f"File {users_file} does not exist")
484+
_print_error(f"File {users_file} does not exist")
487485
sys.exit(os.EX_NOINPUT)
488486

489487
if not admin_email:
490488
admin_email = typer.prompt("Admin email")
491489

492-
print_info(f"Pre-registering users from {users_file} using {base_url}")
490+
_print_info(f"Pre-registering users from {users_file} using {base_url}")
493491
asyncio.run(run_pre_registration(base_url, users_file, admin_email, admin_password))
494-
print_success("Pre-registration completed")
492+
_print_success("Pre-registration completed")
495493

496494

497495
@app.command()
@@ -526,14 +524,14 @@ def invite(
526524

527525
# Validate trial_days and extra_credits
528526
if trial_days is not None and trial_days <= 0:
529-
print_error("Trial days must be a positive integer")
527+
_print_error("Trial days must be a positive integer")
530528
sys.exit(os.EX_USAGE)
531529

532530
if extra_credits is not None and (extra_credits < 0 or extra_credits >= 500):
533-
print_error("Extra credits must be between 0 and 499")
531+
_print_error("Extra credits must be between 0 and 499")
534532
sys.exit(os.EX_USAGE)
535533

536-
print_info(f"Generating invitation for {guest_email} using {base_url}")
534+
_print_info(f"Generating invitation for {guest_email} using {base_url}")
537535
asyncio.run(
538536
run_create_invitation(
539537
base_url,
@@ -544,7 +542,7 @@ def invite(
544542
extra_credits,
545543
)
546544
)
547-
print_success("Invitation generation completed")
545+
_print_success("Invitation generation completed")
548546

549547

550548
@app.command()
@@ -580,22 +578,22 @@ def invite_all(
580578
2. A list of objects with an email property: [{"email": "[email protected]", ...}, ...]
581579
"""
582580
if not emails_file.exists():
583-
print_error(f"File {emails_file} does not exist")
581+
_print_error(f"File {emails_file} does not exist")
584582
sys.exit(os.EX_NOINPUT)
585583

586584
if not admin_email:
587585
admin_email = typer.prompt("Admin email")
588586

589587
# Validate trial_days and extra_credits
590588
if trial_days is not None and trial_days <= 0:
591-
print_error("Trial days must be a positive integer")
589+
_print_error("Trial days must be a positive integer")
592590
sys.exit(os.EX_USAGE)
593591

594592
if extra_credits is not None and (extra_credits < 0 or extra_credits >= 500):
595-
print_error("Extra credits must be between 0 and 499")
593+
_print_error("Extra credits must be between 0 and 499")
596594
sys.exit(os.EX_USAGE)
597595

598-
print_info(f"Generating invitations for users in {emails_file} using {base_url}")
596+
_print_info(f"Generating invitations for users in {emails_file} using {base_url}")
599597
asyncio.run(
600598
run_bulk_create_invitation(
601599
base_url,
@@ -606,7 +604,7 @@ def invite_all(
606604
extra_credits,
607605
)
608606
)
609-
print_success("Bulk invitation completed")
607+
_print_success("Bulk invitation completed")
610608

611609

612610
if __name__ == "__main__":

0 commit comments

Comments
 (0)