""" Server-side validation mirroring every client-side rule from DMH_Registration_FORM_frontend.txt and DMH_Registration_Formvalidation.js, plus v2.0 JSON DTO validation & server-side permanent address derivation. """ import os import re from datetime import date, datetime from db import ( VALID_COUNTRY_IDS, VALID_DOC_TYPE_IDS, VALID_GENDER_IDS, VALID_RELATION_IDS, VALID_TITLE_IDS, get_cities_by_state, get_states_by_country, ) PAN_RE = re.compile(r"^[A-Za-z]{5}[0-9]{4}[A-Za-z]$") AADHAR_RE = re.compile(r"^\d{12}$") CELL_RE = re.compile(r"^\d{10}$") DIGITS_RE = re.compile(r"^\d+$") INCOME_RE = re.compile(r"^\d+(\.\d{1,2})?$") EMAIL_RE = re.compile(r"^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$") CAPTCHA_RE = re.compile(r"^[A-Za-z]{4}$") ALLOWED_ID_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".pdf"} ALLOWED_PHOTO_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"} VALID_MARITAL_STATUSES = {"Single", "Married", "Divorced", "Widowed"} AGE_UNIT_MAP = {"0": 0, "1": 1, "2": 2, "3": 3, "years": 0, "months": 1, "days": 2, "weeks": 3} def _clean_str(form, key: str) -> str: return (form.get(key) or "").strip() def _parse_int_id(val: str, valid_set: set[int]) -> int | None: if not val or not DIGITS_RE.match(val): return None num = int(val) return num if num in valid_set else None def _parse_ddmmyyyy(val: str) -> date | None: try: parsed = datetime.strptime(val, "%d/%m/%Y").date() if parsed > date.today(): return None return parsed except ValueError: return None def _validate_address_block(form, errors: list[str], *, is_permanent: bool) -> dict: prefix = "p_" if is_permanent else "" label = "Permanent " if is_permanent else "" address1 = _clean_str(form, f"{prefix}address1") address2 = _clean_str(form, f"{prefix}address2") or None post_office = _clean_str(form, f"{prefix}post_office") or None country_raw = _clean_str(form, f"{prefix}country") pincode = _clean_str(form, f"{prefix}pincode") phone = _clean_str(form, f"{prefix}phone") or None if not is_permanent and not address1: errors.append("Please Enter House Name/Appt.No Details") country_id = _parse_int_id(country_raw, VALID_COUNTRY_IDS) if country_id is None: errors.append(f"Please Select {label}Country".strip()) state_id = None city_id = None other_state = None other_city = None state_key = f"{prefix}state" city_key = f"{prefix}city" other_state_key = "other_p_state" if is_permanent else "other_state" other_city_key = "other_p_city" if is_permanent else "other_city" if country_id == 38: state_raw = _clean_str(form, state_key) city_raw = _clean_str(form, city_key) valid_state_ids = {s["id"] for s in get_states_by_country(38)} if not is_permanent: state_id = _parse_int_id(state_raw, valid_state_ids) if state_id is None: errors.append("Please Select State") elif state_raw: state_id = _parse_int_id(state_raw, valid_state_ids) if state_id is None: errors.append("Please Select Valid Permanent State") if state_id is not None: valid_city_ids = {c["id"] for c in get_cities_by_state(state_id)} if not is_permanent: city_id = _parse_int_id(city_raw, valid_city_ids) if city_id is None: errors.append("Please Select City") elif city_raw: city_id = _parse_int_id(city_raw, valid_city_ids) if city_id is None: errors.append("Please Select Valid Permanent City") elif not is_permanent: errors.append("Please Select City") elif country_id is not None: other_state = _clean_str(form, other_state_key) or _clean_str(form, state_key) or None other_city = _clean_str(form, other_city_key) or _clean_str(form, city_key) or None if not is_permanent: if not other_state: errors.append("Please Enter State") if not other_city: errors.append("Please Enter City") if pincode: if not DIGITS_RE.match(pincode): errors.append(f"Please Enter Numbers In {label}Pin Number".strip()) elif country_id == 38 and len(pincode) != 6: errors.append(f"Please Enter 6 Digit {label}Pin Number".strip()) elif len(pincode) > 20: errors.append(f"{label}Pincode is too long (max 20 digits).".strip()) return { f"{prefix}address1": address1 or None, f"{prefix}address2": address2, f"{prefix}post_office": post_office, f"{prefix}country": country_id, f"{prefix}state": state_id, other_state_key: other_state, f"{prefix}city": city_id, other_city_key: other_city, f"{prefix}pincode": pincode or None, f"{prefix}phone": phone, } def _derive_permanent_from_local(local_addr: dict) -> dict: """Server-side permanent address derivation when copyToPermanentAddress is true.""" return { "p_address1": local_addr["address1"], "p_address2": local_addr["address2"], "p_post_office": local_addr["post_office"], "p_country": local_addr["country"], "p_state": local_addr["state"], "other_p_state": local_addr["other_state"], "p_city": local_addr["city"], "other_p_city": local_addr["other_city"], "p_pincode": local_addr["pincode"], "p_phone": local_addr["phone"], } def _validate_file(files, field_name: str, allowed_exts: set[str], missing_msg: str, invalid_msg: str, errors: list[str]): file_obj = files.get(field_name) if files else None if not file_obj or not (file_obj.filename or "").strip(): errors.append(missing_msg) return None ext = os.path.splitext(file_obj.filename.strip())[1].lower() if ext not in allowed_exts: errors.append(invalid_msg) return None return file_obj def _check_max_len(val: str | None, max_len: int, label: str, errors: list[str]) -> None: if val and len(val) > max_len: errors.append(f"{label} exceeds maximum length of {max_len} characters.") def validate_core_fields(form, *, skip_captcha: bool = False) -> tuple[dict, list[str]]: """Validate all non-file registration fields uniformly for legacy and v1 API.""" errors: list[str] = [] if _clean_str(form, "honeypot"): errors.append("Invalid submission detected.") return {}, errors title_id = _parse_int_id(_clean_str(form, "title"), VALID_TITLE_IDS) if title_id is None: errors.append("Please Select Title") lname = _clean_str(form, "lname").upper() if not lname: errors.append("Please Enter Last Name") _check_max_len(lname, 100, "Last Name", errors) fname = _clean_str(form, "fname").upper() if not fname: errors.append("Please Enter First Name") _check_max_len(fname, 100, "First Name", errors) mname = _clean_str(form, "mname").upper() or None _check_max_len(mname, 100, "Middle Name", errors) pan_no = _clean_str(form, "pan_no").upper() if pan_no and not PAN_RE.match(pan_no): errors.append("Enter Valid Pan Card Number") aadhar_no = _clean_str(form, "aadhar_no") if aadhar_no: if not DIGITS_RE.match(aadhar_no): errors.append("Please Enter Numbers In Aadhar Number") elif not AADHAR_RE.match(aadhar_no): errors.append("Please Enter 12 Digit Aadhar Number") gender_id = _parse_int_id(_clean_str(form, "gender"), VALID_GENDER_IDS) if gender_id is None: errors.append("Please Select Gender") father = _clean_str(form, "father") or None _check_max_len(father, 150, "Father/Husband Name", errors) dob_str = _clean_str(form, "dob") age_str = _clean_str(form, "age") if not dob_str or not age_str: errors.append("Please Enter Date Of Birth Or Age.") dob_date = _parse_ddmmyyyy(dob_str) if dob_str else None if dob_str and dob_date is None: errors.append("Please Enter Valid Date Of Birth (dd/mm/yyyy).") elif dob_date and (date.today().year - dob_date.year) > 120: errors.append("Date Of Birth cannot be more than 120 years ago.") age_unit_raw = _clean_str(form, "ageUnit") or "0" age_unit = AGE_UNIT_MAP.get(age_unit_raw) if age_unit is None: errors.append("Invalid Age Unit.") age_unit = 0 age_val = None if age_str: if not DIGITS_RE.match(age_str) or int(age_str) <= 0: errors.append("Patient age should be greater than zero.") else: age_val = int(age_str) max_age = {0: 120, 1: 1440, 2: 43800, 3: 6260}.get(age_unit, 120) if age_val > max_age: errors.append("Patient age is out of valid range.") approx_dob_raw = _clean_str(form, "approx_dob") or "0" approx_dob = 1 if approx_dob_raw == "1" else 0 marital_status = _clean_str(form, "marital_status") or None dom_date = None bmname = _clean_str(form, "bmname") or None _check_max_len(bmname, 150, "Before Marriage Name", errors) if gender_id == 2: if not marital_status or marital_status not in VALID_MARITAL_STATUSES: errors.append("Please Choose Marital Status.") elif marital_status != "Single": dom_str = _clean_str(form, "dom") if not dom_str: errors.append("Please Enter Date Of Marriage.") else: dom_date = _parse_ddmmyyyy(dom_str) if dom_date is None: errors.append("Please Enter Valid Date Of Marriage (dd/mm/yyyy).") elif dob_date and dom_date < dob_date: errors.append("Date Of Marriage cannot be before Date Of Birth.") if not bmname: errors.append("Please Enter Before Marriage Name.") else: marital_status = None dom_date = None bmname = None income_str = _clean_str(form, "patient_income") income_val = None if income_str: if len(income_str) > 10 or not INCOME_RE.match(income_str): errors.append("Please Enter Numbers In Monthly Income") else: income_val = float(income_str) local_addr = _validate_address_block(form, errors, is_permanent=False) _check_max_len(local_addr["address1"], 255, "Address1", errors) _check_max_len(local_addr["address2"], 255, "Address2", errors) _check_max_len(local_addr["post_office"], 150, "PostOffice/Town", errors) _check_max_len(local_addr["other_state"], 150, "State", errors) _check_max_len(local_addr["other_city"], 150, "City", errors) copy_flag = _clean_str(form, "copy").lower() in ("copy", "true", "1", "on", "yes") if copy_flag: perm_addr = _derive_permanent_from_local(local_addr) else: perm_addr = _validate_address_block(form, errors, is_permanent=True) _check_max_len(perm_addr["p_address1"], 255, "Permanent Address1", errors) _check_max_len(perm_addr["p_address2"], 255, "Permanent Address2", errors) _check_max_len(perm_addr["p_post_office"], 150, "Permanent PostOffice/Town", errors) _check_max_len(perm_addr["other_p_state"], 150, "Permanent State", errors) _check_max_len(perm_addr["other_p_city"], 150, "Permanent City", errors) office_phone = _clean_str(form, "office_phone") or None _check_max_len(office_phone, 30, "Office Phone", errors) _check_max_len(local_addr["phone"], 30, "Phone", errors) _check_max_len(perm_addr["p_phone"], 30, "Permanent Phone", errors) cell_phone = _clean_str(form, "cell_phone") if cell_phone: if not DIGITS_RE.match(cell_phone): errors.append("Please Enter Numbers In Cell Number") elif not CELL_RE.match(cell_phone): errors.append("Please Enter 10 Digit Cell Number") email = _clean_str(form, "email").lower() _check_max_len(email, 150, "Email", errors) if not email: errors.append("Please Enter Email Address") elif not EMAIL_RE.match(email): errors.append("You have entered an invalid email address!") emg_person = _clean_str(form, "emg_person") emg_person1 = _clean_str(form, "emg_person1") emg_person2 = _clean_str(form, "emg_person2") or None if not emg_person or not emg_person1: errors.append("Please Enter Emergency Contact Person") _check_max_len(emg_person, 100, "Emergency Contact Last Name", errors) _check_max_len(emg_person1, 100, "Emergency Contact First Name", errors) _check_max_len(emg_person2, 100, "Emergency Contact Middle Name", errors) emg_rel_id = _parse_int_id(_clean_str(form, "relation"), VALID_RELATION_IDS) if emg_rel_id is None: errors.append("Please Select Relation With Patient") emg_no = _clean_str(form, "emg_no") if not emg_no: errors.append("Please Enter Emergency Contact Number") elif not DIGITS_RE.match(emg_no) or len(emg_no) < 7 or len(emg_no) > 15: errors.append("Please Enter Valid Emergency Contact Number (7-15 digits)") re_persone = _clean_str(form, "re_persone") if not re_persone: errors.append("Please Enter Name Of Representative") _check_max_len(re_persone, 150, "Name of Representative", errors) re_rel_id = _parse_int_id(_clean_str(form, "re_relation"), VALID_RELATION_IDS) if re_rel_id is None: errors.append("Please Select Representative Relation To Patient") doc_type_id = _parse_int_id(_clean_str(form, "doc_type"), VALID_DOC_TYPE_IDS) if doc_type_id is None: errors.append("Please Select Patient Document Type") if not skip_captcha: txtcaptcha = _clean_str(form, "txtcaptcha").replace(" ", "") if not txtcaptcha: errors.append("Enter captcha text.") elif not CAPTCHA_RE.match(txtcaptcha): errors.append("Invalid Captcha Text!") cleaned = { "title": title_id, "lname": lname, "fname": fname, "mname": mname, "pan_no": pan_no or None, "aadhar_no": aadhar_no or None, "gender": gender_id, "father": father, "dob": dob_date, "age": age_val, "ageUnit": age_unit, "approx_dob": approx_dob, "marital_status": marital_status, "dom": dom_date, "bmname": bmname, "patient_income": income_val, "office_phone": office_phone, "cell_phone": cell_phone or None, "email": email, "emg_person": emg_person, "emg_person1": emg_person1, "emg_person2": emg_person2, "relation": emg_rel_id, "emg_no": emg_no, "re_persone": re_persone, "re_relation": re_rel_id, "doc_type": doc_type_id, "privacy_notice_version": _clean_str(form, "privacyNoticeVersion") or "v1.0", "lawful_basis": _clean_str(form, "lawfulBasis") or "PATIENT_REGISTRATION", **local_addr, **perm_addr, } return cleaned, errors def validate_registration(form, files, session_captcha: str | None = None) -> tuple[dict, list[str]]: """Legacy multipart form validation.""" cleaned, errors = validate_core_fields(form, skip_captcha=False) if errors and "Invalid submission detected." in errors: return {}, errors txtcaptcha = _clean_str(form, "txtcaptcha").replace(" ", "") if session_captcha and txtcaptcha and txtcaptcha != session_captcha: errors.append("Invalid Captcha Text!") ptn_photo_file = _validate_file( files, "ptnPhoto", ALLOWED_PHOTO_EXTENSIONS, "Please Upload Patient Image", "Invalid Patient Image file type", errors, ) id_file = _validate_file( files, "id_file", ALLOWED_ID_EXTENSIONS, "Please Upload Identity Proof", "Invalid file type", errors, ) cleaned["ptnPhoto_file"] = ptn_photo_file cleaned["id_file_obj"] = id_file return cleaned, errors