Skip to content

Commit 7cf4329

Browse files
Alterting compartment 2 to obtain kits from the DB instead of a CSV file in compartment 1
1 parent 19a27dd commit 7cf4329

File tree

6 files changed

+91
-45
lines changed

6 files changed

+91
-45
lines changed

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,4 @@ oracledb>=2.5.1
66
pandas>=2.2.3
77
python-dotenv~=1.0.1
88
Flask~=3.0.3
9-
fastparquet>=2024.11.0
9+
sqlalchemy>=2.0.38

tests/Smokescreen/test_compartment_2.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from utils.batch_processing import batch_processing
55
from datetime import datetime
66
from utils.screening_subject_page_searcher import verify_subject_event_status_by_nhs_no
7-
import pandas as pd
7+
from utils.fit_kit_generation import create_fit_id_df
88

99
@pytest.mark.wip1
1010
def test_compartment_2(page: Page) -> None:
@@ -13,23 +13,22 @@ def test_compartment_2(page: Page) -> None:
1313

1414
MainMenu(page).go_to_fit_test_kits_page()
1515
FITTestKits(page).go_to_log_devices_page()
16-
subjectdf = pd.read_parquet('subject_kit_number.parquet', engine='fastparquet')
17-
os.remove('subject_kit_number.parquet')
16+
subjectdf = create_fit_id_df()
1817

1918
for subject in range(4):
20-
fit_device_id = subjectdf["FIT_Device_ID"].iloc[subject-1]
19+
fit_device_id = subjectdf["fit_device_id"].iloc[subject]
2120
LogDevices(page).fill_fit_device_id_field(fit_device_id)
2221
sample_date = datetime.now().strftime("%#d %b %Y")
2322
LogDevices(page).fill_sample_date_field(sample_date)
2423
LogDevices(page).verify_successfully_logged_device_text()
2524

26-
nhs_no = subjectdf["NHS_Number"].iloc[0]
25+
nhs_no = subjectdf["subject_nhs_number"].iloc[0]
2726
verify_subject_event_status_by_nhs_no(page, nhs_no, "S43 - Kit Returned and Logged (Initial Test)")
2827

2928
NavigationBar(page).click_main_menu_link()
3029
MainMenu(page).go_to_fit_test_kits_page()
3130
FITTestKits(page).go_to_log_devices_page()
32-
spoilt_fit_device_id = subjectdf["FIT_Device_ID"].iloc[4]
31+
spoilt_fit_device_id = subjectdf["fit_device_id"].iloc[-1]
3332
LogDevices(page).fill_fit_device_id_field(spoilt_fit_device_id)
3433
LogDevices(page).click_device_spoilt_button()
3534
LogDevices(page).select_spoilt_device_dropdown_option()

utils/batch_processing.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
from pages.manage_active_batch_page import ManageActiveBatch
66
from pages.archived_batch_list_page import ArchivedBatchList
77
from utils.pdf_reader import extract_nhs_no_from_pdf
8-
from utils.csv_reader import convert_csv_to_df
98
from utils.screening_subject_page_searcher import verify_subject_event_status_by_nhs_no
109
import os
1110
import pytest
@@ -59,9 +58,6 @@ def batch_processing(page: Page, batch_type: str, batch_description: str, latest
5958
first_nhs_no = nhs_numbers[0]
6059
os.remove(file) # Deletes the file after extracting the necessary data
6160
elif file.endswith(".csv"):
62-
if batch_type == "S9":
63-
csv_df = convert_csv_to_df(file) # Currently no use in compartment 1, will be necessary for future compartments
64-
csv_df.to_parquet('subject_kit_number.parquet', engine='fastparquet')
6561
os.remove(file) # Deletes the file after extracting the necessary data
6662

6763
# This loops through each Confirm printed button and clicks each one

utils/csv_reader.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
import pandas as pd
22
from datetime import datetime
33

4-
def convert_csv_to_df(file: str):
5-
csv_df = pd.read_csv(file)
6-
csv_df.drop(csv_df.columns[[0,2,3,4,5,6,7,8,9,10,12]], axis = 1, inplace = True) # Removing unnecessary columns
7-
df = csv_df.rename(columns={csv_df.columns[0]: "NHS_Number",csv_df.columns[1]: "Kit_ID"}) # Renaming the columns to something more meaningful
8-
df.dropna(inplace = True) # Deleting any Null records
9-
df["NHS_Number"] = df["NHS_Number"].str.replace(" ", "") # Removing the space from the nhs number
10-
df["FIT_Device_ID"] = df["Kit_ID"].apply(convert_kit_id_to_fit_device_id)
11-
return df
4+
# Commented out as no longer required, need to see if it will be used at all
5+
# def convert_csv_to_df(file: str):
6+
# csv_df = pd.read_csv(file)
7+
# csv_df.drop(csv_df.columns[[0,2,3,4,5,6,7,8,9,10,12]], axis = 1, inplace = True) # Removing unnecessary columns
8+
# df = csv_df.rename(columns={csv_df.columns[0]: "NHS_Number",csv_df.columns[1]: "Kit_ID"}) # Renaming the columns to something more meaningful
9+
# df.dropna(inplace = True) # Deleting any Null records
10+
# df["NHS_Number"] = df["NHS_Number"].str.replace(" ", "") # Removing the space from the nhs number
11+
# df["FIT_Device_ID"] = df["Kit_ID"].apply(convert_kit_id_to_fit_device_id)
12+
# return df
1213

13-
def convert_kit_id_to_fit_device_id(kit_id):
14-
today = datetime.now()
15-
year = today.strftime("%y") # Get the year from todays date in YY format
16-
return f"{kit_id}12{int(year)+1}12345/KD00001" # Creating the fit device id with an expiry date set to December next year
14+
# def convert_kit_id_to_fit_device_id(kit_id):
15+
# today = datetime.now()
16+
# year = today.strftime("%y") # Get the year from todays date in YY format
17+
# return f"{kit_id}12{int(year)+1}12345/KD00001" # Creating the fit device id with an expiry date set to December next year

utils/fit_kit_generation.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from oracle import OracleDB
2+
import pandas as pd
3+
from datetime import datetime
4+
5+
def create_fit_id_df():
6+
df = get_kit_id_from_db()
7+
df["fit_device_id"] = df["kitid"].apply(calculate_check_digit)
8+
df["fit_device_id"] = df["fit_device_id"].apply(convert_kit_id_to_fit_device_id)
9+
10+
temp_string = df["screening_subject_id"].apply(str).iloc[0]
11+
for subject in range(df.shape[0]):
12+
subject_id = df["screening_subject_id"].apply(str).iloc[subject]
13+
temp_string += f" or SCREENING_SUBJECT_ID = {subject_id}"
14+
15+
df = get_nhs_number_from_subject_id(temp_string, df)
16+
return df
17+
18+
def get_kit_id_from_db():
19+
kit_id_df = OracleDB().execute_query("""select tk.kitid, tk.screening_subject_id
20+
from tk_items_t tk
21+
inner join ep_subject_episode_t se on se.screening_subject_id = tk.screening_subject_id
22+
inner join screening_subject_t sst on (sst.screening_subject_id = tk.screening_subject_id)
23+
inner join sd_contact_t sdc on (sdc.nhs_number = sst.subject_nhs_number)
24+
where tk.tk_type_id = 3
25+
and tk.logged_in_flag = 'N'
26+
and sdc.hub_id = 23159
27+
and device_id is null
28+
and tk.invalidated_date is null
29+
and se.latest_event_status_id in (11198, 11213)
30+
fetch first 5 rows only""")
31+
32+
return kit_id_df
33+
34+
def calculate_check_digit(kitID: str):
35+
total = 0
36+
charString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%"
37+
for i in range(len(kitID)):
38+
total += charString.index(kitID[i-1])
39+
check_digit = charString[total % 43]
40+
return f"{kitID}-{check_digit}"
41+
42+
def convert_kit_id_to_fit_device_id(kit_id: str):
43+
today = datetime.now()
44+
year = today.strftime("%y") # Get the year from todays date in YY format
45+
return f"{kit_id}12{int(year)+1}12345/KD00001"
46+
47+
def get_nhs_number_from_subject_id(subject_ids, df):
48+
temp_df = OracleDB().execute_query(f"SELECT SCREENING_SUBJECT_ID, SUBJECT_NHS_NUMBER FROM SCREENING_SUBJECT_T WHERE SCREENING_SUBJECT_ID = {subject_ids}")
49+
df = df.merge(temp_df[["screening_subject_id","subject_nhs_number"]], on="screening_subject_id", how="left")
50+
return df

utils/oracle.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import oracledb
22
import os
33
from dotenv import load_dotenv
4-
4+
from sqlalchemy import create_engine
5+
import pandas as pd
56
class OracleDB:
67
def __init__(self):
78
load_dotenv()
@@ -74,7 +75,26 @@ def delete_all_users_from_approved_users_table(self): # To remove all users fro
7475
except Exception as connectionError:
7576
print(f"Failed to connect to the DB! with connection error {connectionError}")
7677

77-
# The following two functions are commented out as they are not used currently, but may be needed in future compartments
78+
def execute_query(self, query: str,): # To use when "select xxxx" (stored procedures)
79+
try:
80+
print("Attempting DB connection...")
81+
conn = oracledb.connect(user=self.user, password=self.password, dsn=self.dns)
82+
engine = create_engine('oracle+oracledb://', creator=lambda: conn)
83+
print(conn.version, "DB connection successful!")
84+
try:
85+
print(f"Attempting to execute query")
86+
df = pd.read_sql(query, engine)
87+
print(conn.version, "query execution successful!")
88+
except Exception as executionError:
89+
print(f"Failed to execute query with execution error {executionError}")
90+
finally:
91+
if conn is not None:
92+
conn.close()
93+
return df
94+
except Exception as connectionError:
95+
print(f"Failed to connect to the DB! with connection error {connectionError}")
96+
97+
# The following function is commented out as it is not used currently, but may be needed in future compartments
7898

7999
# def execute_stored_procedure(self, procedure: str): # To use when "exec xxxx" (stored procedures)
80100
# try:
@@ -93,23 +113,3 @@ def delete_all_users_from_approved_users_table(self): # To remove all users fro
93113
# conn.close()
94114
# except Exception as connectionError:
95115
# print(f"Failed to connect to the DB! with connection error: {connectionError}")
96-
97-
# def execute_query(self, query: str,): # To use when "select xxxx" (stored procedures)
98-
# try:
99-
# print("Attempting DB connection...")
100-
# conn = oracledb.connect(user=self.user, password=self.password, dsn=self.dns)
101-
# print(conn.version, "DB connection successful!")
102-
# try:
103-
# print(f"Attempting to execute query: {query}")
104-
# cursor = conn.cursor()
105-
# cursor.execute(query)
106-
# result = cursor.fetchall()
107-
# print(conn.version, "query execution successful!")
108-
# except Exception as executionError:
109-
# print(f"Failed to execute query with execution error {executionError}")
110-
# finally:
111-
# if conn is not None:
112-
# conn.close()
113-
# return result
114-
# except Exception as connectionError:
115-
# print(f"Failed to connect to the DB! with connection error {connectionError}")

0 commit comments

Comments
 (0)