@@ -18,14 +18,13 @@ def get_ieds_table():
1818
1919def ieds_check_exist (id : str ) -> bool :
2020 """Check if a record exists in the IEDS table for the given ID."""
21+ logger .info (f"ieds_check_exist. Get ID: { id } " )
2122 search_patient_pk = f"Patient#{ id } "
2223
23- # Only fetch 1 record to check existence
24- response = get_ieds_table ().query (
25- KeyConditionExpression = Key ("PK" ).eq (search_patient_pk ),
26- Limit = 1
27- )
28- return response .get ("Count" , 0 ) > 0
24+ response = get_ieds_table ().get_item (Key = {'PatientPk' : search_patient_pk })
25+ found = 'Item' in response
26+ logger .info (f"ieds_check_exist. Record found: { found } for ID: { id } " )
27+ return found
2928
3029
3130def ieds_update_patient_id (old_id : str , new_id : str ) -> dict :
@@ -38,23 +37,72 @@ def ieds_update_patient_id(old_id: str, new_id: str) -> dict:
3837 return {"status" : "success" , "message" : f"No change in patient ID: { old_id } " }
3938
4039 try :
41- # Update the table with new id
42- response = get_ieds_table ().update_item (
43- Key = {"PK" : f"Patient#{ old_id } " },
44- UpdateExpression = "SET PK = :new_id" ,
45- ExpressionAttributeValues = {":new_id" : f"Patient#{ new_id } " }
46- )
40+ logger .info (f"Updating patient ID in IEDS from { old_id } to { new_id } " )
41+ ieds_table = get_ieds_table ()
42+ new_patient_pk = f"Patient#{ new_id } "
43+ old_patient_pk = f"Patient#{ old_id } "
4744
48- # Check update successful
49- if response ['ResponseMetadata' ]['HTTPStatusCode' ] == 200 :
45+ logger .info ("Getting items to update in IEDS table..." )
46+ items_to_update = get_items_to_update (old_patient_pk )
47+
48+ if not items_to_update :
49+ logger .warning (f"No items found to update for patient ID: { old_id } " )
5050 return {
5151 "status" : "success" ,
52- "message" : f"Updated IEDS, patient ID: { old_id } to { new_id } "
52+ "message" : f"No items found to update for patient ID: { old_id } "
53+ }
54+
55+ transact_items = []
56+
57+ logger .info ("loop through items to update..." )
58+ logger .info (f"Items to update: { len (items_to_update )} " )
59+ for item in items_to_update :
60+ logger .info ("Update item" )
61+ logger .info (f"Updating item: { item ['PatientPK' ]} " )
62+ transact_items .append ({
63+ 'Update' : {
64+ 'TableName' : get_ieds_table_name (),
65+ 'Key' : {
66+ 'PK' : {'S' : item ['PK' ]},
67+ },
68+ 'UpdateExpression' : 'SET PatientPK = :new_val' ,
69+ 'ExpressionAttributeValues' : {
70+ ':new_val' : {'S' : new_patient_pk }
71+ }
72+ }
73+ })
74+
75+ logger .info ("Transacting items in IEDS table..." )
76+ # ✅ Fix: Initialize success tracking
77+ all_batches_successful = True
78+ total_batches = 0
79+
80+ # Batch transact in chunks of 25
81+ for i in range (0 , len (transact_items ), 25 ):
82+ batch = transact_items [i :i + 25 ]
83+ total_batches += 1
84+ logger .info (f"Transacting batch { total_batches } of size: { len (batch )} " )
85+
86+ response = ieds_table .transact_write_items (TransactItems = batch )
87+ logger .info ("Batch update complete. Response: %s" , response )
88+
89+ # ✅ Fix: Check each batch response
90+ if response ['ResponseMetadata' ]['HTTPStatusCode' ] != 200 :
91+ all_batches_successful = False
92+ logger .error (f"Batch { total_batches } failed with status: { response ['ResponseMetadata' ]['HTTPStatusCode' ]} " )
93+
94+ # ✅ Fix: Consolidated response handling outside the loop
95+ logger .info (f"All batches complete. Total batches: { total_batches } , All successful: { all_batches_successful } " )
96+
97+ if all_batches_successful :
98+ return {
99+ "status" : "success" ,
100+ "message" : f"Updated IEDS, patient ID: { old_id } to { new_id } . { len (items_to_update )} items updated in { total_batches } batches."
53101 }
54102 else :
55103 return {
56104 "status" : "error" ,
57- "message" : f"Failed to update patient ID: { old_id } "
105+ "message" : f"Failed to update some batches for patient ID: { old_id } "
58106 }
59107
60108 except Exception as e :
@@ -64,24 +112,39 @@ def ieds_update_patient_id(old_id: str, new_id: str) -> dict:
64112 nhs_numbers = [old_id , new_id ],
65113 exception = e
66114 )
67- raise e
68-
69-
70- def test_ieds_insert_patient (patient_id : str ) -> dict : # NOSONAR
71- """Test function for inserting patient ID."""
72- logger .info ("insert to db..." )
73- # write the patient id to table
74- res = '{"resourceType": "Immunization"}'
75- result = get_ieds_table ().put_item (Item = {
76- "PK" : f"Patient#{ patient_id } " ,
77- "PatientPK" : f"Patient#{ patient_id } " ,
78- "PatientSK" : f"Patient#{ patient_id } " ,
79- "Resource" : res ,
80- "IdentifierPK" : "https://www.ieds.england.nhs.uk/#a7e06f66-339f-4b81-b2f6-016b88bfc422" ,
81- "Operation" : "CREATE" ,
82- "Version" : "1" ,
83- "SupplierSystem" : "RAVS" ,
84- })
85-
86- logger .info (f"Test result: { result } " )
87- return result
115+ # ✅ Fix: Remove duplicate raise
116+ # raise e # Remove this line
117+
118+ # def test_ieds_insert_patient(patient_id: str) -> dict: # NOSONAR
119+ # """Test function for inserting patient ID."""
120+ # logger.info("insert to db...")
121+ # # write the patient id to table
122+ # res = '{"resourceType": "Immunization"}'
123+ # result = get_ieds_table().put_item(Item={
124+ # "PK": f"Patient#{patient_id}",
125+ # "PatientPK": f"Patient#{patient_id}",
126+ # "PatientSK": f"Patient#{patient_id}",
127+ # "Resource": res,
128+ # "IdentifierPK": "https://www.ieds.england.nhs.uk/#a7e06f66-339f-4b81-b2f6-016b88bfc422",
129+ # "Operation": "CREATE",
130+ # "Version": "1",
131+ # "SupplierSystem": "RAVS",
132+ # })
133+
134+ # logger.info(f"Test result: {result}")
135+ # return result
136+
137+
138+ def get_items_to_update (old_patient_pk : str ) -> list :
139+ """Get items that need to be updated in the IEDS table."""
140+ logger .info (f"Getting items to update for old patient PK: { old_patient_pk } " )
141+ response = get_ieds_table ().query (
142+ KeyConditionExpression = Key ('PatientPK' ).eq (old_patient_pk ),
143+ Limit = 25 # Adjust limit as needed
144+ )
145+
146+ if 'Items' not in response or not response ['Items' ]:
147+ logger .warning (f"No items found for old patient PK: { old_patient_pk } " )
148+ return []
149+
150+ return response ['Items' ]
0 commit comments