Skip to content

Commit

Permalink
lint care/facility/management/
Browse files Browse the repository at this point in the history
  • Loading branch information
sainak committed Sep 24, 2024
1 parent 28976e7 commit e561f58
Show file tree
Hide file tree
Showing 12 changed files with 49 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,18 @@ class Command(BaseCommand):
help = "Populate daily round for consultations"

def handle(self, *args, **options):
batch_size = 10000
consultations = list(
PatientConsultation.objects.filter(
last_daily_round__isnull=True
).values_list("external_id")
)
total_count = len(consultations)
print(f"{total_count} Consultations need to be updated")
self.stdout.write(f"{total_count} Consultations need to be updated")
i = 0
for consultation_eid in consultations:
if i > 10000 and i % 10000 == 0:
print(f"{i} operations performed")
if i > batch_size and i % batch_size == 0:
self.stdout.write(f"{i} operations performed")
i = i + 1
PatientConsultation.objects.filter(external_id=consultation_eid[0]).update(
last_daily_round=DailyRound.objects.filter(
Expand All @@ -30,4 +31,4 @@ def handle(self, *args, **options):
.order_by("-created_date")
.first()
)
print("Operation Completed")
self.stdout.write("Operation Completed")
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,5 @@ def handle(self, *args, **options) -> str | None:
except Exception:
failed.append({"id": patient.id, "phone_number": patient.phone_number})

print(f"Completed for {qs.count()} | Failed for {len(failed)}")
print(f"Failed for {json.dumps(failed)}")
self.stdout.write(f"Completed for {qs.count()} | Failed for {len(failed)}")
self.stdout.write(f"Failed for {json.dumps(failed)}")
2 changes: 1 addition & 1 deletion care/facility/management/commands/generate_jwks.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ class Command(BaseCommand):
help = "Generate JWKS"

def handle(self, *args, **options):
print(generate_encoded_jwks())
self.stdout.write(generate_encoded_jwks())
7 changes: 3 additions & 4 deletions care/facility/management/commands/load_dummy_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@ class Command(BaseCommand):
def handle(self, *args, **options):
env = os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
if "production" in env or "staging" in env:
raise CommandError(
"This command is not intended to be run in production environment."
)
msg = "This command is not intended to be run in production environment."
raise CommandError(msg)

try:
management.call_command("loaddata", self.BASE_URL + "states.json")
Expand All @@ -32,4 +31,4 @@ def handle(self, *args, **options):
)
management.call_command("populate_investigations")
except Exception as e:
raise CommandError(e)
raise CommandError(e) from e
5 changes: 4 additions & 1 deletion care/facility/management/commands/load_event_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,10 @@ class Command(BaseCommand):
)

def create_objects(
self, types: tuple[EventType, ...], model: str = None, parent: EventType = None
self,
types: tuple[EventType, ...],
model: str | None = None,
parent: EventType = None,
):
for event_type in types:
model = event_type.get("model", model)
Expand Down
18 changes: 12 additions & 6 deletions care/facility/management/commands/load_icd11_diagnoses_data.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import json
from typing import TYPE_CHECKING

from django.conf import settings
from django.core.management import BaseCommand, CommandError

from care.facility.models.icd11_diagnosis import ICD11Diagnosis

if TYPE_CHECKING:
from pathlib import Path


def fetch_data():
with open("data/icd11.json") as json_file:
icd11_json: Path = settings.BASE_DIR / "data" / "icd11.json"
with icd11_json.open() as json_file:
return json.load(json_file)


Expand Down Expand Up @@ -117,17 +123,17 @@ def my(x):

# The following code is never executed as the `icd11.json` file is
# pre-sorted and hence the parent is always present before the child.
print("Full-scan for", id, item["label"])
self.stdout.write("Full-scan for", id, item["label"])
return self.find_roots(
[
next(
icd11_object
for icd11_object in self.data
if icd11_object["ID"] == item["parentId"]
][0]
)
)

def handle(self, *args, **options):
print("Loading ICD11 diagnoses data to database...")
self.stdout.write("Loading ICD11 diagnoses data to database...")
try:
self.data = fetch_data()

Expand Down Expand Up @@ -162,4 +168,4 @@ def roots(item):
ignore_conflicts=True, # Voluntarily set to skip duplicates, so that we can run this command multiple times + existing relations are not affected
)
except Exception as e:
raise CommandError(e)
raise CommandError(e) from e
12 changes: 10 additions & 2 deletions care/facility/management/commands/load_medicines_data.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import json
from typing import TYPE_CHECKING

from django.conf import settings
from django.core.management import BaseCommand

from care.facility.models import MedibaseMedicine

if TYPE_CHECKING:
from pathlib import Path


class Command(BaseCommand):
"""
Expand All @@ -14,11 +19,14 @@ class Command(BaseCommand):
help = "Loads Medibase Medicines into the database from medibase.json"

def fetch_data(self):
with open("data/medibase.json") as json_file:
medibase_json: Path = settings.BASE_DIR / "data" / "medibase.json"
with medibase_json.open() as json_file:
return json.load(json_file)

def handle(self, *args, **options):
print("Loading Medibase Medicines into the database from medibase.json")
self.stdout.write(
"Loading Medibase Medicines into the database from medibase.json"
)

medibase_objects = self.fetch_data()
MedibaseMedicine.objects.bulk_create(
Expand Down
8 changes: 4 additions & 4 deletions care/facility/management/commands/load_redis_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ class Command(BaseCommand):

def handle(self, *args, **options):
if cache.get("redis_index_loading"):
print("Redis Index already loading, skipping")
self.stdout.write("Redis Index already loading, skipping")
return

cache.set("redis_index_loading", True, timeout=60 * 5)
cache.set("redis_index_loading", value=True, timeout=60 * 5)

load_icd11_diagnosis()
load_medibase_medicines()
Expand All @@ -35,8 +35,8 @@ def handle(self, *args, **options):
if load_static_data:
load_static_data()
except ModuleNotFoundError:
print(f"Module {module_path} not found")
self.stdout.write(f"Module {module_path} not found")
except Exception as e:
print(f"Error loading static data for {plug.name}: {e}")
self.stdout.write(f"Error loading static data for {plug.name}: {e}")

cache.delete("redis_index_loading")
2 changes: 1 addition & 1 deletion care/facility/management/commands/port_patient_wards.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def handle(self, *args, **options):
patient.save()
except Exception:
failed += 1
print(
self.stdout.write(
str(failed),
" failed operations ",
str(success),
Expand Down
6 changes: 3 additions & 3 deletions care/facility/management/commands/summarize.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ class Command(BaseCommand):

def handle(self, *args, **options):
patient_summary()
print("Patients Summarised")
self.stdout.write("Patients Summarised")
facility_capacity_summary()
print("Capacity Summarised")
self.stdout.write("Capacity Summarised")
district_patient_summary()
print("District Wise Patient Summarised")
self.stdout.write("District Wise Patient Summarised")
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ class Command(BaseCommand):
help = "Sync the patient created flag in external tests"

def handle(self, *args, **options):
print("Starting Sync")
self.stdout.write("Starting Sync")
for patient in PatientRegistration.objects.all():
if patient.srf_id:
PatientExternalTest.objects.filter(
srf_id__iexact=patient.srf_id
).update(patient_created=True)
print("Completed Sync")
self.stdout.write("Completed Sync")
4 changes: 2 additions & 2 deletions care/facility/management/commands/sync_patient_age.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ def handle(self, *args, **options):
except Exception:
failed += 1
if failed:
print(f"Failed for {failed} Patient")
self.stdout.write(f"Failed for {failed} Patient")
else:
print("Successfully Synced Age")
self.stdout.write("Successfully Synced Age")

0 comments on commit e561f58

Please sign in to comment.