|
2 | 2 | from os_vars import get_ieds_table_name |
3 | 3 | from common.aws_dynamodb import get_dynamodb_table |
4 | 4 | from common.clients import logger, dynamodb_client |
| 5 | +import json |
| 6 | +import ast |
| 7 | + |
5 | 8 | from utils import make_status |
6 | 9 | from exceptions.id_sync_exception import IdSyncException |
7 | 10 |
|
@@ -136,13 +139,34 @@ def extract_patient_resource_from_item(item: dict) -> dict | None: |
136 | 139 | Extract a Patient resource dict from an IEDS database. |
137 | 140 | """ |
138 | 141 | patient_resource = item.get("Resource", None) |
| 142 | + logger.info(f"patient_resource (raw): {patient_resource}") |
| 143 | + |
| 144 | + # Accept either a dict (preferred) or a JSON / Python-literal string |
| 145 | + if isinstance(patient_resource, str): |
| 146 | + # Try JSON first, then fall back to ast.literal_eval for single-quotes |
| 147 | + try: |
| 148 | + patient_resource_parsed = json.loads(patient_resource) |
| 149 | + except Exception: |
| 150 | + try: |
| 151 | + patient_resource_parsed = ast.literal_eval(patient_resource) |
| 152 | + except Exception: |
| 153 | + logger.debug("extract_patient_resource_from_item: Resource is a string but could not be parsed") |
| 154 | + return None |
| 155 | + patient_resource = patient_resource_parsed |
| 156 | + |
139 | 157 | if not isinstance(patient_resource, dict): |
140 | 158 | return None |
141 | 159 |
|
142 | | - for response in patient_resource.get("contained", []): |
| 160 | + # The Patient resource may be nested under 'contained' or be the resource itself |
| 161 | + contained = patient_resource.get("contained") or [] |
| 162 | + for response in contained: |
143 | 163 | if isinstance(response, dict) and response.get("resourceType") == "Patient": |
144 | 164 | return response |
145 | 165 |
|
| 166 | + # Fallback: if the resource is itself a Patient, return it |
| 167 | + if patient_resource.get("resourceType") == "Patient": |
| 168 | + return patient_resource |
| 169 | + |
146 | 170 | return None |
147 | 171 |
|
148 | 172 |
|
|
0 commit comments