""" Database connection, lookup queries, atomic registration persistence, idempotency, staged uploads, outbox, and admin/audit helpers using PyMySQL. All SQL queries use parameterized placeholders (%s). """ import hashlib import json import os import uuid from datetime import datetime, timedelta, timezone import pymysql from dotenv import load_dotenv from crypto_utils import compute_match_token, encrypt_pii, mask_aadhaar, mask_pan load_dotenv() FALLBACK_TITLES = [ {"id": 1, "name": "Mr."}, {"id": 2, "name": "Miss."}, {"id": 3, "name": "Mrs."}, {"id": 4, "name": "Ms."}, {"id": 5, "name": "Prof."}, {"id": 6, "name": "Dr."}, {"id": 7, "name": "Sr."}, {"id": 8, "name": "B/O "}, {"id": 9, "name": "Col."}, {"id": 10, "name": "MB/O "}, {"id": 11, "name": "FB/O "}, {"id": 12, "name": "M/s"}, {"id": 13, "name": "Smt."}, {"id": 14, "name": "Mast "}, {"id": 15, "name": "Fetus Of. "}, {"id": 16, "name": "Mx."}, {"id": 17, "name": "Major "}, ] FALLBACK_GENDERS = [ {"id": 1, "name": "Male"}, {"id": 2, "name": "Female"}, {"id": 3, "name": "Unisex"}, {"id": 4, "name": "Other"}, {"id": 5, "name": "Foetus"}, ] FALLBACK_RELATIONS = [ {"id": 1, "name": "Self"}, {"id": 2, "name": "Spouse"}, {"id": 3, "name": "Brother"}, {"id": 4, "name": "Sister"}, {"id": 5, "name": "Friend"}, {"id": 6, "name": "Father"}, {"id": 7, "name": "Mother"}, {"id": 8, "name": "Relative"}, {"id": 9, "name": "Son"}, {"id": 10, "name": "Daughter"}, {"id": 11, "name": "Father in law"}, {"id": 12, "name": "Grand father"}, {"id": 13, "name": "Grand mother"}, {"id": 14, "name": "Husband"}, {"id": 15, "name": "Mother in law"}, {"id": 16, "name": "Wife"}, {"id": 17, "name": "Uncle"}, {"id": 18, "name": "Aunty"}, {"id": 19, "name": "Brother In Law"}, {"id": 20, "name": "Sister In Law"}, {"id": 21, "name": "Nephew"}, {"id": 22, "name": "Niece"}, {"id": 23, "name": "Son In Law"}, {"id": 24, "name": "Daughter In Law"}, {"id": 25, "name": "Grand Daughter"}, {"id": 26, "name": "Grand Son"}, {"id": 27, "name": "Major Brother"}, {"id": 28, "name": "Major Sister"}, {"id": 29, "name": "Major Son"}, {"id": 30, "name": "Major Daughter"}, ] FALLBACK_DOC_TYPES = [ {"id": 539, "name": "Driver's License Frontside"}, {"id": 540, "name": "Driver's License Backside"}, {"id": 573, "name": "Passport Book"}, {"id": 1570, "name": "Aadhar card"}, {"id": 1571, "name": "Election card"}, {"id": 1572, "name": "Pan card"}, {"id": 1573, "name": "Birth certificate"}, {"id": 1576, "name": "Affidavit"}, {"id": 1578, "name": "Marriage certificate"}, {"id": 1636, "name": "Visa Details"}, ] FALLBACK_STATES = [ {"id": 32, "name": "Andaman & Nicobar"}, {"id": 1, "name": "Andhra Pradesh"}, {"id": 3, "name": "Arunachal Pradesh"}, {"id": 2, "name": "Assam"}, {"id": 5, "name": "Bihar"}, {"id": 31, "name": "Chandigarh"}, {"id": 35, "name": "Chattisgarh"}, {"id": 30, "name": "Dadra & Nagar"}, {"id": 29, "name": "Daman & Diu"}, {"id": 25, "name": "Delhi"}, {"id": 26, "name": "Goa"}, {"id": 4, "name": "Gujrat"}, {"id": 6, "name": "Haryana"}, {"id": 7, "name": "Himachal Pradesh"}, {"id": 8, "name": "Jammu & Kashmir"}, {"id": 34, "name": "Jharkhand"}, {"id": 9, "name": "Karnataka"}, {"id": 10, "name": "Kerala"}, {"id": 28, "name": "Lakshdweep"}, {"id": 11, "name": "Madhya Pradesh"}, {"id": 12, "name": "Maharashtra"}, {"id": 13, "name": "Manipur"}, {"id": 14, "name": "Meghalaya"}, {"id": 15, "name": "Mizoram"}, {"id": 16, "name": "Nagaland"}, {"id": 17, "name": "Orissa"}, {"id": 27, "name": "Pondichery"}, {"id": 18, "name": "Punjab"}, {"id": 19, "name": "Rajasthan"}, {"id": 20, "name": "Sikkim"}, {"id": 21, "name": "Tamil Nadu"}, {"id": 87, "name": "Telangana"}, {"id": 22, "name": "Tripura"}, {"id": 23, "name": "Uttar Pradesh"}, {"id": 33, "name": "Uttaranchal"}, {"id": 24, "name": "West Bengal"}, ] FALLBACK_CITIES = { 12: [ {"id": 306, "name": "Ahilya Nagar"}, {"id": 290, "name": "Akola"}, {"id": 303, "name": "Amravati"}, {"id": 287, "name": "Bandra(Mumbai Suburban district)"}, {"id": 307, "name": "Beed"}, {"id": 308, "name": "Bhandara"}, {"id": 298, "name": "Buldhana"}, {"id": 291, "name": "Chandrapur"}, {"id": 311, "name": "Dharashiv"}, {"id": 299, "name": "Dhule"}, {"id": 309, "name": "Gadchiroli"}, {"id": 319, "name": "Gondia"}, {"id": 320, "name": "Hingoli"}, {"id": 292, "name": "Jalgaon"}, {"id": 310, "name": "Jalna"}, {"id": 300, "name": "Kolhapur"}, {"id": 296, "name": "Latur"}, {"id": 297, "name": "Mumbai-City"}, {"id": 288, "name": "Nagpur"}, {"id": 301, "name": "Nanded"}, {"id": 317, "name": "Nandurbar"}, {"id": 304, "name": "Nashik"}, {"id": 606, "name": "Palghar"}, {"id": 293, "name": "Parbhani"}, {"id": 289, "name": "Pune"}, {"id": 302, "name": "Raigad"}, {"id": 312, "name": "Ratnagiri"}, {"id": 286, "name": "Sambhaji Nagar"}, {"id": 313, "name": "Sangli"}, {"id": 314, "name": "Satara"}, {"id": 315, "name": "Sindudurg"}, {"id": 294, "name": "Solapur"}, {"id": 295, "name": "Thane"}, {"id": 305, "name": "Wardha"}, {"id": 318, "name": "Washim"}, {"id": 316, "name": "Yavatmal"}, ], 1: [{"id": 1011, "name": "Visakhapatnam"}, {"id": 1012, "name": "Vijayawada"}, {"id": 1013, "name": "Guntur"}, {"id": 1014, "name": "Nellore"}, {"id": 1015, "name": "Kurnool"}, {"id": 1016, "name": "Tirupati"}, {"id": 1017, "name": "Rajahmundry"}, {"id": 1018, "name": "Kakinada"}], 2: [{"id": 1019, "name": "Guwahati"}, {"id": 1020, "name": "Silchar"}, {"id": 1021, "name": "Dibrugarh"}, {"id": 1022, "name": "Jorhat"}, {"id": 1023, "name": "Nagaon"}, {"id": 1024, "name": "Tinsukia"}, {"id": 1025, "name": "Tezpur"}], 3: [{"id": 1026, "name": "Itanagar"}, {"id": 1027, "name": "Naharlagun"}, {"id": 1028, "name": "Pasighat"}, {"id": 1029, "name": "Tawang"}, {"id": 1030, "name": "Ziro"}], 4: [{"id": 1003, "name": "Ahmedabad"}, {"id": 1004, "name": "Surat"}, {"id": 1031, "name": "Vadodara"}, {"id": 1032, "name": "Rajkot"}, {"id": 1033, "name": "Bhavnagar"}, {"id": 1034, "name": "Jamnagar"}, {"id": 1035, "name": "Junagadh"}, {"id": 1036, "name": "Gandhinagar"}, {"id": 1037, "name": "Anand"}], 5: [{"id": 1038, "name": "Patna"}, {"id": 1039, "name": "Gaya"}, {"id": 1040, "name": "Bhagalpur"}, {"id": 1041, "name": "Muzaffarpur"}, {"id": 1042, "name": "Darbhanga"}, {"id": 1043, "name": "Purnia"}, {"id": 1044, "name": "Arrah"}, {"id": 1045, "name": "Begusarai"}], 6: [{"id": 1046, "name": "Gurugram"}, {"id": 1047, "name": "Faridabad"}, {"id": 1048, "name": "Panipat"}, {"id": 1049, "name": "Ambala"}, {"id": 1050, "name": "Hisar"}, {"id": 1051, "name": "Karnal"}, {"id": 1052, "name": "Rohtak"}, {"id": 1053, "name": "Sonipat"}], 7: [{"id": 1054, "name": "Shimla"}, {"id": 1055, "name": "Dharamshala"}, {"id": 1056, "name": "Mandi"}, {"id": 1057, "name": "Solan"}, {"id": 1058, "name": "Kullu"}, {"id": 1059, "name": "Bilaspur"}, {"id": 1060, "name": "Hamirpur"}], 8: [{"id": 1061, "name": "Srinagar"}, {"id": 1062, "name": "Jammu"}, {"id": 1063, "name": "Anantnag"}, {"id": 1064, "name": "Baramulla"}, {"id": 1065, "name": "Udhampur"}, {"id": 1066, "name": "Kathua"}], 9: [{"id": 1001, "name": "Bengaluru"}, {"id": 1002, "name": "Mysuru"}, {"id": 1067, "name": "Mangaluru"}, {"id": 1068, "name": "Hubballi-Dharwad"}, {"id": 1069, "name": "Belagavi"}, {"id": 1070, "name": "Kalaburagi"}, {"id": 1071, "name": "Davanagere"}, {"id": 1072, "name": "Ballari"}, {"id": 1073, "name": "Shivamogga"}, {"id": 1074, "name": "Udupi"}], 10: [{"id": 1010, "name": "Kochi"}, {"id": 1075, "name": "Thiruvananthapuram"}, {"id": 1076, "name": "Kozhikode"}, {"id": 1077, "name": "Thrissur"}, {"id": 1078, "name": "Kollam"}, {"id": 1079, "name": "Kannur"}, {"id": 1080, "name": "Alappuzha"}, {"id": 1081, "name": "Palakkad"}, {"id": 1082, "name": "Kottayam"}], 11: [{"id": 1083, "name": "Indore"}, {"id": 1084, "name": "Bhopal"}, {"id": 1085, "name": "Jabalpur"}, {"id": 1086, "name": "Gwalior"}, {"id": 1087, "name": "Ujjain"}, {"id": 1088, "name": "Sagar"}, {"id": 1089, "name": "Rewa"}, {"id": 1090, "name": "Satna"}], 13: [{"id": 1091, "name": "Imphal"}, {"id": 1092, "name": "Thoubal"}, {"id": 1093, "name": "Bishnupur"}, {"id": 1094, "name": "Churachandpur"}], 14: [{"id": 1095, "name": "Shillong"}, {"id": 1096, "name": "Tura"}, {"id": 1097, "name": "Jowai"}, {"id": 1098, "name": "Nongpoh"}], 15: [{"id": 1099, "name": "Aizawl"}, {"id": 1100, "name": "Lunglei"}, {"id": 1101, "name": "Champhai"}, {"id": 1102, "name": "Serchhip"}], 16: [{"id": 1103, "name": "Kohima"}, {"id": 1104, "name": "Dimapur"}, {"id": 1105, "name": "Mokokchung"}, {"id": 1106, "name": "Tuensang"}], 17: [{"id": 1107, "name": "Bhubaneswar"}, {"id": 1108, "name": "Cuttack"}, {"id": 1109, "name": "Rourkela"}, {"id": 1110, "name": "Berhampur"}, {"id": 1111, "name": "Sambalpur"}, {"id": 1112, "name": "Puri"}, {"id": 1113, "name": "Balasore"}], 18: [{"id": 1114, "name": "Ludhiana"}, {"id": 1115, "name": "Amritsar"}, {"id": 1116, "name": "Jalandhar"}, {"id": 1117, "name": "Patiala"}, {"id": 1118, "name": "Bathinda"}, {"id": 1119, "name": "Mohali"}, {"id": 1120, "name": "Pathankot"}, {"id": 1121, "name": "Hoshiarpur"}], 19: [{"id": 1122, "name": "Jaipur"}, {"id": 1123, "name": "Jodhpur"}, {"id": 1124, "name": "Udaipur"}, {"id": 1125, "name": "Kota"}, {"id": 1126, "name": "Ajmer"}, {"id": 1127, "name": "Bikaner"}, {"id": 1128, "name": "Alwar"}, {"id": 1129, "name": "Bhilwara"}], 20: [{"id": 1130, "name": "Gangtok"}, {"id": 1131, "name": "Namchi"}, {"id": 1132, "name": "Gyalshing"}, {"id": 1133, "name": "Mangan"}], 21: [{"id": 1006, "name": "Chennai"}, {"id": 1134, "name": "Coimbatore"}, {"id": 1135, "name": "Madurai"}, {"id": 1136, "name": "Tiruchirappalli"}, {"id": 1137, "name": "Salem"}, {"id": 1138, "name": "Tirunelveli"}, {"id": 1139, "name": "Erode"}, {"id": 1140, "name": "Vellore"}, {"id": 1141, "name": "Thanjavur"}], 22: [{"id": 1142, "name": "Agartala"}, {"id": 1143, "name": "Udaipur"}, {"id": 1144, "name": "Dharmanagar"}, {"id": 1145, "name": "Kailashahar"}], 23: [{"id": 1146, "name": "Lucknow"}, {"id": 1147, "name": "Kanpur"}, {"id": 1148, "name": "Ghaziabad"}, {"id": 1149, "name": "Agra"}, {"id": 1150, "name": "Varanasi"}, {"id": 1151, "name": "Meerut"}, {"id": 1152, "name": "Prayagraj"}, {"id": 1153, "name": "Noida"}, {"id": 1154, "name": "Bareilly"}, {"id": 1155, "name": "Gorakhpur"}], 24: [{"id": 1008, "name": "Kolkata"}, {"id": 1156, "name": "Howrah"}, {"id": 1157, "name": "Durgapur"}, {"id": 1158, "name": "Asansol"}, {"id": 1159, "name": "Siliguri"}, {"id": 1160, "name": "Bardhaman"}, {"id": 1161, "name": "Darjeeling"}], 25: [{"id": 1005, "name": "New Delhi"}, {"id": 1162, "name": "Central Delhi"}, {"id": 1163, "name": "North Delhi"}, {"id": 1164, "name": "South Delhi"}, {"id": 1165, "name": "East Delhi"}, {"id": 1166, "name": "West Delhi"}, {"id": 1167, "name": "Dwarka"}], 26: [{"id": 1009, "name": "Panaji"}, {"id": 1168, "name": "Margao"}, {"id": 1169, "name": "Vasco da Gama"}, {"id": 1170, "name": "Mapusa"}, {"id": 1171, "name": "Ponda"}], 27: [{"id": 1172, "name": "Puducherry"}, {"id": 1173, "name": "Karaikal"}, {"id": 1174, "name": "Mahe"}, {"id": 1175, "name": "Yanam"}], 28: [{"id": 1176, "name": "Kavaratti"}, {"id": 1177, "name": "Agatti"}, {"id": 1178, "name": "Minicoy"}, {"id": 1179, "name": "Amini"}], 29: [{"id": 1180, "name": "Daman"}, {"id": 1181, "name": "Diu"}], 30: [{"id": 1182, "name": "Silvassa"}, {"id": 1183, "name": "Amli"}, {"id": 1184, "name": "Khanvel"}], 31: [{"id": 1185, "name": "Chandigarh"}], 32: [{"id": 1186, "name": "Port Blair"}, {"id": 1187, "name": "Diglipur"}, {"id": 1188, "name": "Mayabunder"}, {"id": 1189, "name": "Car Nicobar"}], 33: [{"id": 1190, "name": "Dehradun"}, {"id": 1191, "name": "Haridwar"}, {"id": 1192, "name": "Roorkee"}, {"id": 1193, "name": "Haldwani"}, {"id": 1194, "name": "Nainital"}, {"id": 1195, "name": "Rishikesh"}, {"id": 1196, "name": "Rudrapur"}], 34: [{"id": 1197, "name": "Ranchi"}, {"id": 1198, "name": "Jamshedpur"}, {"id": 1199, "name": "Dhanbad"}, {"id": 1200, "name": "Bokaro"}, {"id": 1201, "name": "Deoghar"}, {"id": 1202, "name": "Hazaribagh"}], 35: [{"id": 1203, "name": "Raipur"}, {"id": 1204, "name": "Bhilai"}, {"id": 1205, "name": "Bilaspur"}, {"id": 1206, "name": "Korba"}, {"id": 1207, "name": "Durg"}, {"id": 1208, "name": "Rajnandgaon"}, {"id": 1209, "name": "Jagdalpur"}], 87: [{"id": 1007, "name": "Hyderabad"}, {"id": 1210, "name": "Warangal"}, {"id": 1211, "name": "Nizamabad"}, {"id": 1212, "name": "Karimnagar"}, {"id": 1213, "name": "Khammam"}, {"id": 1214, "name": "Ramagundam"}], } VALID_TITLE_IDS = set(range(1, 18)) VALID_GENDER_IDS = {1, 2, 3, 4, 5} VALID_RELATION_IDS = set(range(1, 31)) VALID_DOC_TYPE_IDS = {539, 540, 573, 1570, 1571, 1572, 1573, 1576, 1578, 1636} VALID_COUNTRY_IDS = { 109, 1, 2, 3, 4, 100, 5, 6, 7, 95, 8, 9, 10, 11, 12, 13, 14, 96, 15, 16, 17, 18, 104, 19, 20, 21, 22, 23, 120, 24, 25, 26, 27, 123, 28, 29, 30, 122, 31, 32, 33, 35, 111, 36, 37, 38, 106, 39, 110, 40, 41, 42, 117, 88, 116, 91, 44, 45, 46, 47, 48, 49, 50, 89, 51, 52, 53, 54, 55, 112, 94, 56, 57, 108, 59, 90, 114, 60, 61, 115, 62, 63, 64, 65, 66, 67, 105, 68, 87, 69, 113, 70, 71, 72, 118, 98, 73, 93, 103, 74, 75, 76, 77, 78, 97, 119, 79, 121, 80, 81, 101, 82, 92, 83, 84, 85, 102, 107, 86, 99, } ALLOWED_TRANSITIONS = { "SUBMITTED": {"CHECKING_DUPLICATES"}, "CHECKING_DUPLICATES": {"PENDING_REVIEW", "PENDING_HIS_SYNC", "SYNC_FAILED"}, "PENDING_REVIEW": {"PENDING_HIS_SYNC", "LINKED_EXISTING", "REJECTED"}, "PENDING_HIS_SYNC": {"REGISTERED", "SYNC_FAILED"}, "SYNC_FAILED": {"CHECKING_DUPLICATES", "PENDING_HIS_SYNC", "LINKED_EXISTING", "REJECTED"}, } def _utcnow_naive() -> datetime: return datetime.now(timezone.utc).replace(tzinfo=None) def get_connection(): return pymysql.connect( host=os.getenv("MYSQL_HOST", "localhost"), port=int(os.getenv("MYSQL_PORT", "3306")), user=os.getenv("MYSQL_USER", "root"), password=os.getenv("MYSQL_PASSWORD", ""), database=os.getenv("MYSQL_DB", "dmh_registration"), charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor, autocommit=False, ) def get_states_by_country(country_id: int): try: conn = get_connection() try: with conn.cursor() as cur: cur.execute( "SELECT id, name FROM lookup_states WHERE country_id = %s AND is_active = 1 ORDER BY name", (country_id,), ) return cur.fetchall() finally: conn.close() except pymysql.MySQLError: return FALLBACK_STATES if country_id == 38 else [] def get_cities_by_state(state_id: int): try: conn = get_connection() try: with conn.cursor() as cur: cur.execute( "SELECT id, name FROM lookup_cities WHERE state_id = %s AND is_active = 1 ORDER BY name", (state_id,), ) return cur.fetchall() finally: conn.close() except pymysql.MySQLError: return FALLBACK_CITIES.get(state_id, []) def get_master_list(master_type: str): table_map = { "titles": ("lookup_titles", FALLBACK_TITLES), "genders": ("lookup_genders", FALLBACK_GENDERS), "relations": ("lookup_relations", FALLBACK_RELATIONS), "doc-types": ("lookup_doc_types", FALLBACK_DOC_TYPES), "countries": ("lookup_countries", [{"id": cid, "name": f"Country {cid}"} for cid in sorted(VALID_COUNTRY_IDS)]), } if master_type not in table_map: return None table, fallback = table_map[master_type] try: conn = get_connection() try: with conn.cursor() as cur: cur.execute(f"SELECT id, name FROM {table} WHERE is_active = 1 ORDER BY id") return cur.fetchall() finally: conn.close() except pymysql.MySQLError: return fallback def generate_next_reference_id(cur) -> str: """Atomically increment reference_sequences starting from 250044.""" cur.execute( "SELECT next_val FROM reference_sequences WHERE seq_name = 'patient_registration' FOR UPDATE" ) row = cur.fetchone() if row: val = int(row["next_val"]) cur.execute( "UPDATE reference_sequences SET next_val = %s WHERE seq_name = 'patient_registration'", (val + 1,), ) return str(val) cur.execute( "INSERT INTO reference_sequences (seq_name, next_val) VALUES ('patient_registration', 250045)" ) return "250044" # --- Sessions & CAPTCHA --- def create_registration_session(ttl_minutes: int = 60) -> dict: sid = str(uuid.uuid4()) exp = _utcnow_naive() + timedelta(minutes=ttl_minutes) conn = get_connection() try: with conn.cursor() as cur: cur.execute( "INSERT INTO registration_sessions (id, expires_at) VALUES (%s, %s)", (sid, exp), ) conn.commit() return {"sessionId": sid, "expiresAt": exp.isoformat()} finally: conn.close() def create_captcha_challenge(session_id: str, answer: str, ttl_minutes: int = 5) -> dict: cid = str(uuid.uuid4()) exp = _utcnow_naive() + timedelta(minutes=ttl_minutes) ans_hash = hashlib.sha256(answer.encode("utf-8")).hexdigest() conn = get_connection() try: with conn.cursor() as cur: cur.execute( "INSERT INTO captcha_challenges (id, session_id, answer_hash, expires_at) VALUES (%s, %s, %s, %s)", (cid, session_id, ans_hash, exp), ) conn.commit() return {"challengeId": cid, "expiresAt": exp.isoformat()} finally: conn.close() def verify_and_consume_captcha(cur, session_id: str, challenge_id: str, answer: str) -> bool: ans_hash = hashlib.sha256((answer or "").strip().encode("utf-8")).hexdigest() cur.execute( """ SELECT id, answer_hash, expires_at, consumed FROM captcha_challenges WHERE id = %s AND session_id = %s FOR UPDATE """, (challenge_id, session_id), ) row = cur.fetchone() if not row or row["consumed"] or row["expires_at"] < _utcnow_naive(): return False if row["answer_hash"] != ans_hash: return False cur.execute("UPDATE captcha_challenges SET consumed = 1 WHERE id = %s", (challenge_id,)) return True # --- Staged Uploads --- def save_staged_upload(meta: dict): conn = get_connection() try: with conn.cursor() as cur: cur.execute( """ INSERT INTO patient_documents ( id, session_id, doc_category, doc_type_id, storage_key, mime_type, size_bytes, scan_status, expires_at ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) """, ( meta["id"], meta["session_id"], meta["doc_category"], meta["doc_type_id"], meta["storage_key"], meta["mime_type"], meta["size_bytes"], meta["scan_status"], meta["expires_at"], ), ) conn.commit() finally: conn.close() def delete_staged_upload(upload_id: str, session_id: str) -> str | None: conn = get_connection() try: with conn.cursor() as cur: cur.execute( "SELECT storage_key FROM patient_documents WHERE id = %s AND session_id = %s AND patient_id IS NULL", (upload_id, session_id), ) row = cur.fetchone() if not row: return None cur.execute("DELETE FROM patient_documents WHERE id = %s", (upload_id,)) conn.commit() return row["storage_key"] finally: conn.close() # --- Idempotency --- def check_or_reserve_idempotency(cur, session_id: str, idem_key: str, fingerprint: str) -> dict: """ Returns {'state': 'NEW' | 'COMPLETED' | 'IN_PROGRESS' | 'CONFLICT', ...} """ cur.execute( """ SELECT status, payload_fingerprint, http_status, response_json FROM idempotency_records WHERE session_id = %s AND idempotency_key = %s FOR UPDATE """, (session_id, idem_key), ) row = cur.fetchone() if not row: cur.execute( """ INSERT INTO idempotency_records (session_id, idempotency_key, payload_fingerprint, status) VALUES (%s, %s, %s, 'IN_PROGRESS') """, (session_id, idem_key, fingerprint), ) return {"state": "NEW"} if row["payload_fingerprint"] != fingerprint: return {"state": "CONFLICT"} if row["status"] == "COMPLETED": resp = row["response_json"] if isinstance(resp, str): resp = json.loads(resp) return {"state": "COMPLETED", "http_status": row["http_status"], "response": resp} return {"state": "IN_PROGRESS"} def release_idempotency_reservation(cur, session_id: str, idem_key: str) -> None: """Remove an IN_PROGRESS idempotency key on recoverable 422 errors so clients can retry.""" cur.execute( "DELETE FROM idempotency_records WHERE session_id = %s AND idempotency_key = %s AND status = 'IN_PROGRESS'", (session_id, idem_key), ) def _insert_registration_records(cur, cleaned: dict, ref_id: str, session_id: str | None = None) -> int: """Core atomic insert shared by legacy and v1 registration endpoints.""" now = _utcnow_naive() cur.execute( """ INSERT INTO patient_registration ( reference_form_id, session_id, status, title_id, lname, fname, mname, gender_id, father_husband_name, dob, age, age_unit, approx_dob, age_recorded_at, marital_status, dom, before_marriage_name, monthly_income, email, cell_phone, phone, office_phone, emg_lname, emg_fname, emg_mname, emg_relation_id, emg_no, rep_name, rep_relation_id, doc_type_id, ptn_photo_path, id_file_path ) VALUES ( %s, %s, 'SUBMITTED', %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s ) """, ( ref_id, session_id, cleaned["title"], cleaned["lname"], cleaned["fname"], cleaned["mname"], cleaned["gender"], cleaned["father"], cleaned["dob"], cleaned["age"], cleaned["ageUnit"], cleaned["approx_dob"], now, cleaned["marital_status"], cleaned["dom"], cleaned["bmname"], cleaned["patient_income"], cleaned["email"], cleaned["cell_phone"], cleaned["phone"], cleaned["office_phone"], cleaned["emg_person"], cleaned["emg_person1"], cleaned["emg_person2"], cleaned["relation"], cleaned["emg_no"], cleaned["re_persone"], cleaned["re_relation"], cleaned["doc_type"], cleaned["ptn_photo_path"], cleaned["id_file_path"], ), ) patient_id = cur.lastrowid addr_sql = """ INSERT INTO patient_address ( patient_id, address_type, address1, address2, post_office, country_id, state_id, other_state, city_id, other_city, pincode, phone ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ cur.execute( addr_sql, ( patient_id, "LOCAL", cleaned["address1"], cleaned["address2"], cleaned["post_office"], cleaned["country"], cleaned["state"], cleaned["other_state"], cleaned["city"], cleaned["other_city"], cleaned["pincode"], cleaned["phone"], ), ) cur.execute( addr_sql, ( patient_id, "PERMANENT", cleaned["p_address1"], cleaned["p_address2"], cleaned["p_post_office"], cleaned["p_country"], cleaned["p_state"], cleaned["other_p_state"], cleaned["p_city"], cleaned["other_p_city"], cleaned["p_pincode"], cleaned["p_phone"], ), ) # Encrypted PII identifiers if cleaned.get("pan_no"): cur.execute( """ INSERT INTO patient_identifiers (reference_form_id, id_type, encrypted_value, masked_value, match_token) VALUES (%s, 'PAN', %s, %s, %s) """, (ref_id, encrypt_pii(cleaned["pan_no"]), mask_pan(cleaned["pan_no"]), compute_match_token("PAN", cleaned["pan_no"])), ) if cleaned.get("aadhar_no"): cur.execute( """ INSERT INTO patient_identifiers (reference_form_id, id_type, encrypted_value, masked_value, match_token) VALUES (%s, 'AADHAAR', %s, %s, %s) """, (ref_id, encrypt_pii(cleaned["aadhar_no"]), mask_aadhaar(cleaned["aadhar_no"]), compute_match_token("AADHAAR", cleaned["aadhar_no"])), ) # Consent record cur.execute( """ INSERT INTO consent_records (patient_id, privacy_notice_version, lawful_basis) VALUES (%s, %s, %s) """, (patient_id, cleaned.get("privacy_notice_version", "v1.0"), cleaned.get("lawful_basis", "PATIENT_REGISTRATION")), ) # Outbox events (duplicate check + async email) corr_id = str(uuid.uuid4()) for ev_type in ("DUPLICATE_CHECK", "EMAIL_CONFIRMATION"): cur.execute( """ INSERT INTO outbox_events (id, registration_id, event_type, status, correlation_id) VALUES (%s, %s, %s, 'PENDING', %s) """, (str(uuid.uuid4()), patient_id, ev_type, corr_id), ) # Audit log cur.execute( """ INSERT INTO audit_logs (registration_id, actor, action, to_status, correlation_id) VALUES (%s, 'PATIENT_PORTAL', 'REGISTRATION_SUBMITTED', 'SUBMITTED', %s) """, (patient_id, corr_id), ) return patient_id def save_registration(cleaned: dict, save_files_cb=None) -> str: """Legacy atomic registration save returning sequential reference_form_id.""" conn = get_connection() try: with conn.cursor() as cur: ref_id = generate_next_reference_id(cur) if save_files_cb is not None: photo_path, id_path = save_files_cb(ref_id) cleaned["ptn_photo_path"] = photo_path cleaned["id_file_path"] = id_path _insert_registration_records(cur, cleaned, ref_id) conn.commit() return ref_id except Exception: conn.rollback() raise finally: conn.close() def save_registration_v1( *, cleaned: dict, session_id: str, idempotency_key: str, payload_fingerprint: str, photo_upload_id: str, kyc_upload_id: str, ) -> tuple[int, dict]: """ Atomic v1 registration transaction: 1. Replay check before CAPTCHA consumption (handled by caller/tx) 2. Attach CLEAN staged uploads owned by session_id 3. Persist patient, addresses, encrypted IDs, consent, outbox & idempotent response. """ if photo_upload_id == kyc_upload_id: raise ValueError("photoUploadId and kycUploadId must be distinct uploads.") conn = get_connection() try: with conn.cursor() as cur: cur.execute( """ SELECT id, storage_key, scan_status, session_id, patient_id, doc_category FROM patient_documents WHERE id IN (%s, %s) FOR UPDATE """, (photo_upload_id, kyc_upload_id), ) docs = {d["id"]: d for d in cur.fetchall()} for uid, expected_cat in ((photo_upload_id, "PHOTO"), (kyc_upload_id, "KYC")): doc = docs.get(uid) if ( not doc or doc["session_id"] != session_id or doc["scan_status"] != "CLEAN" or doc["patient_id"] is not None or doc["doc_category"] != expected_cat ): raise ValueError(f"Invalid or unowned {expected_cat} upload ID: {uid}") cleaned["ptn_photo_path"] = docs[photo_upload_id]["storage_key"] cleaned["id_file_path"] = docs[kyc_upload_id]["storage_key"] ref_id = generate_next_reference_id(cur) patient_id = _insert_registration_records(cur, cleaned, ref_id, session_id=session_id) cur.execute( """ UPDATE patient_documents SET patient_id = %s, scan_status = 'ATTACHED' WHERE id IN (%s, %s) """, (patient_id, photo_upload_id, kyc_upload_id), ) response_body = { "success": True, "data": { "registrationReference": ref_id, "status": "SUBMITTED", "hospitalPatientId": None, }, } cur.execute( """ UPDATE idempotency_records SET status = 'COMPLETED', http_status = 201, response_json = %s WHERE session_id = %s AND idempotency_key = %s """, (json.dumps(response_body), session_id, idempotency_key), ) conn.commit() return 201, response_body except Exception: conn.rollback() raise finally: conn.close() def transition_registration_status( cur, registration_id: int, to_status: str, actor: str, reason: str | None = None, hospital_patient_id: str | None = None, correlation_id: str | None = None, ): """Enforce allowed state-machine transitions with optimistic version check.""" cur.execute( "SELECT status, version FROM patient_registration WHERE id = %s FOR UPDATE", (registration_id,), ) row = cur.fetchone() if not row: raise ValueError("Registration not found") current = row["status"] if to_status not in ALLOWED_TRANSITIONS.get(current, set()): raise ValueError(f"Invalid transition {current} -> {to_status}") cur.execute( """ UPDATE patient_registration SET status = %s, version = version + 1, hospital_patient_id = COALESCE(%s, hospital_patient_id) WHERE id = %s AND version = %s """, (to_status, hospital_patient_id, registration_id, row["version"]), ) cur.execute( """ INSERT INTO audit_logs (registration_id, actor, action, from_status, to_status, reason, correlation_id) VALUES (%s, %s, 'STATUS_TRANSITION', %s, %s, %s, %s) """, (registration_id, actor, current, to_status, reason, correlation_id), ) def get_admin_user(sso_subject: str) -> dict | None: """Look up active admin user by SSO subject.""" conn = get_connection() try: with conn.cursor() as cur: cur.execute( "SELECT id, sso_subject, role FROM admin_users WHERE sso_subject = %s AND is_active = 1", (sso_subject,), ) return cur.fetchone() finally: conn.close() def get_registration_document_for_admin(reg_id: int, doc_id: str, actor: str) -> dict | None: """Fetch document metadata for a registration and record audit log.""" conn = get_connection() try: with conn.cursor() as cur: cur.execute( "SELECT id, storage_key, mime_type, doc_category FROM patient_documents WHERE id = %s AND patient_id = %s", (doc_id, reg_id), ) doc = cur.fetchone() if doc: cur.execute( "INSERT INTO audit_logs (registration_id, actor, action, reason) VALUES (%s, %s, 'DOCUMENT_DOWNLOAD', %s)", (reg_id, actor, f"Downloaded {doc['doc_category']} document {doc_id}"), ) conn.commit() return doc finally: conn.close() def get_registration_status_by_ref(reference_form_id: str) -> dict | None: conn = get_connection() try: with conn.cursor() as cur: cur.execute( """ SELECT reference_form_id, session_id, status, hospital_patient_id, email_status, created_at, status_updated_at FROM patient_registration WHERE reference_form_id = %s """, (reference_form_id,), ) return cur.fetchone() finally: conn.close() def list_registrations_admin(status_filter: str | None = None) -> list[dict]: conn = get_connection() try: with conn.cursor() as cur: if status_filter: cur.execute( """ SELECT id, reference_form_id, status, hospital_patient_id, fname, lname, email_status, created_at FROM patient_registration WHERE status = %s ORDER BY created_at DESC LIMIT 100 """, (status_filter,), ) else: cur.execute( """ SELECT id, reference_form_id, status, hospital_patient_id, fname, lname, email_status, created_at FROM patient_registration ORDER BY created_at DESC LIMIT 100 """ ) return cur.fetchall() finally: conn.close() def list_audit_logs_admin(registration_id: int | None = None) -> list[dict]: conn = get_connection() try: with conn.cursor() as cur: if registration_id: cur.execute( "SELECT * FROM audit_logs WHERE registration_id = %s ORDER BY created_at DESC LIMIT 100", (registration_id,), ) else: cur.execute("SELECT * FROM audit_logs ORDER BY created_at DESC LIMIT 100") return cur.fetchall() finally: conn.close()