2025-08-12 13:33:25 +03:00

177 lines
6.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# hospital_management_system/core/management/commands/generate_tenants.py
import random
import uuid
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone
from faker import Faker
from core.models import Tenant
from django.contrib.auth import get_user_model
User = get_user_model()
HOSPITAL_NAMES = [
"King Fahd Medical City",
"Riyadh Military Hospital",
"King Abdulaziz University Hospital",
"King Khalid University Hospital",
"King Saud Medical City",
"Security Forces Hospital Riyadh",
"King Abdullah Medical City",
"Prince Sultan Military Medical City",
"King Faisal Specialist Hospital & Research Centre",
"National Guard Health Affairs",
"King Abdullah Bin Abdulaziz University Hospital",
"Dr. Sulaiman Al Habib Hospital",
"Mouwasat Hospital",
"Dallah Hospital",
"Al Hammadi Hospital",
"Al Noor Specialist Hospital",
"International Medical Center",
"Saudi German Hospital",
"Al-Elm Clinic",
"Abeer Medical Group"
]
ORG_TYPES = [choice[0] for choice in Tenant._meta.get_field('organization_type').choices]
PLANS = [choice[0] for choice in Tenant._meta.get_field('subscription_plan').choices]
class Command(BaseCommand):
help = "Generate Saudi Arabiaoriented Tenant records and a superuser for tenant_id=1."
def add_arguments(self, parser):
parser.add_argument(
'--clear',
action='store_true',
help='Delete all existing tenants before generating new ones.'
)
parser.add_argument(
'--count',
type=int,
default=10,
help='How many tenants to create (default: 10).'
)
parser.add_argument(
'--admin-username',
type=str,
default='admin',
help='Username for the superuser (default: admin).'
)
parser.add_argument(
'--admin-email',
type=str,
default='admin@hospital.sa',
help='Email for the superuser (default: admin@hospital.sa).'
)
parser.add_argument(
'--admin-password',
type=str,
default='AdminPass123!',
help='Password for the superuser (default: AdminPass123!).'
)
def handle(self, *args, **options):
faker = Faker('ar_SA')
Faker.seed(42)
random.seed(42)
count = options['count']
clear = options['clear']
admin_username = options['admin_username']
admin_email = options['admin_email']
admin_password = options['admin_password']
if clear:
self.stdout.write("🗑️ Clearing existing tenants...")
Tenant.objects.all().delete()
self.stdout.write(self.style.SUCCESS("Cleared all tenants."))
with transaction.atomic():
created = []
self.stdout.write(f"▶️ Generating {count} tenants...")
for i in range(count):
# Determine name
if i < len(HOSPITAL_NAMES):
name = HOSPITAL_NAMES[i]
else:
name = f"{faker.city()} {random.choice(['Hospital','Clinic','Medical Center','Health System'])}"
display_name = name.replace("Medical City", "Med. City")
org_type = random.choice(ORG_TYPES)
address = faker.street_address()
city = faker.city()
state = faker.state()
postal = faker.postcode()
country = "Saudi Arabia"
phone = faker.phone_number()
email = faker.company_email()
website = f"https://www.{name.lower().replace(' ','')}.sa"
license_num = str(uuid.uuid4())[:8].upper()
acc_body = random.choice(["CBAHI", "JCI", "MOH", ""])
acc_num = faker.bothify(text="ACC-####") if acc_body else ""
expiry = faker.date_between(start_date="today", end_date="+365d") if acc_body else None
tz = "Asia/Riyadh"
locale = "ar-SA"
currency = "SAR"
plan = random.choice(PLANS)
max_users = random.randint(20, 200)
max_patients = random.randint(100, 5000)
is_trial = random.choice([True, False])
trial_exp = (timezone.now() + timedelta(days=random.randint(7, 30))) if is_trial else None
tenant = Tenant.objects.create(
tenant_id=uuid.uuid4(),
name=name,
display_name=display_name,
description=faker.text(max_nb_chars=200),
organization_type=org_type,
address_line1=address,
address_line2="",
city=city,
state=state,
postal_code=postal,
country=country,
phone_number=phone,
email=email,
website=website,
license_number=license_num,
accreditation_body=acc_body,
accreditation_number=acc_num,
accreditation_expiry=expiry,
timezone=tz,
locale=locale,
currency=currency,
subscription_plan=plan,
max_users=max_users,
max_patients=max_patients,
is_active=True,
is_trial=is_trial,
trial_expires_at=trial_exp,
)
created.append(tenant)
self.stdout.write(self.style.SUCCESS(f"✅ Created {len(created)} tenants."))
# Create or update superuser on tenant pk=1
try:
tenant1 = Tenant.objects.get(pk=1)
except Tenant.DoesNotExist:
self.stdout.write(self.style.ERROR("❌ Tenant with pk=1 not found; cannot create superuser."))
return
if User.objects.filter(username=admin_username).exists():
self.stdout.write(f"⚠️ Superuser `{admin_username}` already exists.")
else:
User.objects.create_superuser(
username=admin_username,
email=admin_email,
password=admin_password,
tenant=tenant1 # assumes your User model has a ForeignKey to Tenant named `tenant`
)
self.stdout.write(self.style.SUCCESS(
f"🔑 Superuser `{admin_username}` created and assigned to tenant `{tenant1.name}` (pk=1)."
))