From 6c03977aabb53616841055cb1779d25022e8143b Mon Sep 17 00:00:00 2001 From: Ayush <155418492+Ayushshah1109@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:07:03 +0530 Subject: [PATCH] Initial commit: DMH Patient Registration Flask app --- .env.example | 16 + .gitignore | 7 + Dockerfile | 13 + app.py | 675 +++++++++++++++++++ crypto_utils.py | 89 +++ db.py | 734 +++++++++++++++++++++ docker-compose.yml | 33 + email_service.py | 39 ++ his_adapter.py | 87 +++ migrate_v2.sql | 136 ++++ requirements.txt | 6 + schema.sql | 395 +++++++++++ static/calender-touch/jquery-1.10.2.js | 70 ++ static/calender-touch/jquery-ui.css | 32 + static/calender-touch/jquery-ui.js | 100 +++ static/calender-touch/style.css | 1 + static/css/bootstrap.min.css | 45 ++ static/images/no_image.png | Bin 0 -> 1859 bytes static/images/refresh.png | Bin 0 -> 216 bytes static/js/ajax.js | 193 ++++++ static/js/alert.mob.css | 16 + static/js/alert.mob.js | 49 ++ static/js/jquery-image-upload-resizer.js | 47 ++ static/js/jquery.min.js | 5 + static/js/validation.js | 512 +++++++++++++++ static/logo.png | Bin 0 -> 2990 bytes templates/error.html | 27 + templates/index.html | 797 +++++++++++++++++++++++ templates/success.html | 32 + tests/test_app.py | 234 +++++++ tests/test_v2_features.py | 256 ++++++++ upload_service.py | 162 +++++ validators.py | 412 ++++++++++++ worker.py | 225 +++++++ 34 files changed, 5445 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 app.py create mode 100644 crypto_utils.py create mode 100644 db.py create mode 100644 docker-compose.yml create mode 100644 email_service.py create mode 100644 his_adapter.py create mode 100644 migrate_v2.sql create mode 100644 requirements.txt create mode 100644 schema.sql create mode 100644 static/calender-touch/jquery-1.10.2.js create mode 100644 static/calender-touch/jquery-ui.css create mode 100644 static/calender-touch/jquery-ui.js create mode 100644 static/calender-touch/style.css create mode 100644 static/css/bootstrap.min.css create mode 100644 static/images/no_image.png create mode 100644 static/images/refresh.png create mode 100644 static/js/ajax.js create mode 100644 static/js/alert.mob.css create mode 100644 static/js/alert.mob.js create mode 100644 static/js/jquery-image-upload-resizer.js create mode 100644 static/js/jquery.min.js create mode 100644 static/js/validation.js create mode 100644 static/logo.png create mode 100644 templates/error.html create mode 100644 templates/index.html create mode 100644 templates/success.html create mode 100644 tests/test_app.py create mode 100644 tests/test_v2_features.py create mode 100644 upload_service.py create mode 100644 validators.py create mode 100644 worker.py diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..732ade5 --- /dev/null +++ b/.env.example @@ -0,0 +1,16 @@ +MYSQL_HOST=localhost +MYSQL_PORT=3306 +MYSQL_USER=root +MYSQL_PASSWORD= +MYSQL_DB=dmh_registration +FLASK_SECRET_KEY=change-me-in-production +UPLOAD_FOLDER=uploads +PII_ENCRYPTION_KEY=dev-32-byte-fernet-or-aes-secret-key!! +PII_HMAC_KEY=dev-hmac-secret-key-change-me +ADMIN_SSO_SECRET=dev-admin-sso-token +HIS_MODE=mock +SMTP_HOST=localhost +SMTP_PORT=1025 +SMTP_USER= +SMTP_PASSWORD= +SMTP_FROM=noreply@dmhospital.org diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f0ba430 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.env +__pycache__/ +*.pyc +.pytest_cache/ +uploads/ +.venv/ +venv/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e796669 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM python:3.13-slim + +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . +RUN useradd -m appuser && mkdir -p /app/uploads && chown -R appuser:appuser /app +USER appuser + +EXPOSE 5000 +HEALTHCHECK --interval=30s --timeout=5s CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:5000/healthz')" || exit 1 +CMD ["waitress-serve", "--host=0.0.0.0", "--port=5000", "app:app"] diff --git a/app.py b/app.py new file mode 100644 index 0000000..2d3b022 --- /dev/null +++ b/app.py @@ -0,0 +1,675 @@ +""" +Flask application for DMH Patient Registration Form. +Serves the registration UI, legacy .php endpoints (secured with upload_service +and server-side CAPTCHA), and /api/v1 REST endpoints. +""" + +import base64 +import hashlib +import html +import io +import json +import logging +import os +import random +import shutil +import string +import time +import uuid +from collections import defaultdict +from datetime import date, timedelta +from functools import wraps + +from dotenv import load_dotenv +from flask import Flask, jsonify, render_template, request, send_file, session +from PIL import Image, ImageDraw, ImageFont +from werkzeug.utils import secure_filename + +import db +from crypto_utils import PiiRedactingFilter, validate_production_secrets +from upload_service import UploadValidationError, process_staged_upload +from validators import validate_core_fields, validate_registration + +load_dotenv() +validate_production_secrets() + +app = Flask(__name__, static_folder="static", static_url_path="") +app.secret_key = os.getenv("FLASK_SECRET_KEY", "dev-secret-change-me") +app.config["UPLOAD_FOLDER"] = os.getenv("UPLOAD_FOLDER", "uploads") +app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024 # 16 MB + +app.logger.addFilter(PiiRedactingFilter()) +logging.getLogger("werkzeug").addFilter(PiiRedactingFilter()) + +# Simple in-memory sliding-window rate limiter +_RATE_BUCKETS: dict[str, list[float]] = defaultdict(list) + + +def _is_rate_limited(bucket: str, limit: int, window_sec: int = 60) -> bool: + if app.config.get("TESTING") and not app.config.get("ENABLE_RATE_LIMIT_IN_TESTS"): + return False + now = time.monotonic() + key = f"{bucket}:{request.remote_addr or 'local'}" + timestamps = [t for t in _RATE_BUCKETS[key] if now - t < window_sec] + if len(timestamps) >= limit: + _RATE_BUCKETS[key] = timestamps + return True + timestamps.append(now) + _RATE_BUCKETS[key] = timestamps + return False + + +def _render_captcha_png_b64(code: str) -> str: + width, height = 160, 44 + img = Image.new("RGB", (width, height), "#e4e0e0") + draw = ImageDraw.Draw(img) + for _ in range(4): + draw.line( + [(random.randint(0, width), random.randint(0, height)), (random.randint(0, width), random.randint(0, height))], + fill="#b0a8a8", + width=1, + ) + font = ImageFont.load_default(size=26) + x = 18 + for ch in code: + draw.text((x, random.randint(6, 11)), ch, fill="#111111", font=font) + x += 33 + buf = io.BytesIO() + img.save(buf, format="PNG") + return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("ascii") + + +@app.after_request +def apply_security_headers(response): + response.headers.setdefault("X-Content-Type-Options", "nosniff") + response.headers.setdefault("X-Frame-Options", "DENY") + response.headers.setdefault( + "Content-Security-Policy", + "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:;", + ) + return response + + +@app.route("/healthz", methods=["GET"]) +def healthz(): + try: + conn = db.get_connection() + try: + with conn.cursor() as cur: + cur.execute("SELECT 1") + finally: + conn.close() + return jsonify({"status": "ok"}), 200 + except Exception: + return jsonify({"status": "degraded"}), 503 + + +# ============================================================ +# Legacy HTML & SACK AJAX Endpoints +# ============================================================ + +def _render_state_html(country_id_raw: str, state_id_raw: str, other_state: str, is_permanent: bool) -> str: + name = "p_state" if is_permanent else "state" + other_name = "other_p_state" if is_permanent else "other_state" + onchange_fn = "p_getCity" if is_permanent else "getCity" + + if country_id_raw in ("", "38"): + selected_state = state_id_raw or ("12" if country_id_raw == "" else "") + states = db.get_states_by_country(38) + options = [''] + for st in states: + sel = " selected" if str(st["id"]) == str(selected_state) else "" + options.append(f'') + return ( + f'" + ) + + safe_val = html.escape(other_state or "") + return f'' + + +def _render_city_html(country_id_raw: str, state_id_raw: str, city_id_raw: str, other_city: str, is_permanent: bool) -> str: + name = "p_city" if is_permanent else "city" + other_name = "other_p_city" if is_permanent else "other_city" + + if country_id_raw in ("", "38"): + effective_state = state_id_raw + selected_city = city_id_raw + if country_id_raw == "" and state_id_raw == "": + effective_state = "12" + if not selected_city: + selected_city = "289" + + cities = db.get_cities_by_state(int(effective_state)) if effective_state.isdigit() else [] + options = [''] + for ct in cities: + sel = " selected" if str(ct["id"]) == str(selected_city) else "" + options.append(f'') + return f'" + + safe_val = html.escape(other_city or "") + return f'' + + +@app.route("/", methods=["GET"]) +@app.route("/index.php", methods=["GET"]) +def index(): + return render_template("index.html") + + +@app.route("/captcha-image", methods=["GET"]) +def legacy_captcha_image(): + if _is_rate_limited("captcha", 60): + return jsonify({"error": "Too many requests"}), 429 + code = "".join(random.choices(string.ascii_letters, k=4)) + session["captcha"] = code + return jsonify({"imageDataUrl": _render_captcha_png_b64(code)}), 200 + + +@app.route("/getState.php", methods=["GET", "POST"]) +def get_state(): + return _render_state_html( + request.values.get("countryId", "").strip(), + request.values.get("stateId", "").strip(), + request.values.get("other_state", "").strip(), + is_permanent=False, + ) + + +@app.route("/getCity.php", methods=["GET", "POST"]) +def get_city(): + return _render_city_html( + request.values.get("countryId", "").strip(), + request.values.get("stateId", "").strip(), + request.values.get("cityId", "").strip(), + request.values.get("other_city", "").strip(), + is_permanent=False, + ) + + +@app.route("/p_getState.php", methods=["GET", "POST"]) +def p_get_state(): + return _render_state_html( + request.values.get("countryId", "").strip(), + request.values.get("stateId", "").strip(), + request.values.get("other_state", "").strip(), + is_permanent=True, + ) + + +@app.route("/p_getCity.php", methods=["GET", "POST"]) +def p_get_city(): + return _render_city_html( + request.values.get("countryId", "").strip(), + request.values.get("stateId", "").strip(), + request.values.get("cityId", "").strip(), + request.values.get("other_city", "").strip(), + is_permanent=True, + ) + + +@app.route("/getDOB.php", methods=["GET", "POST"]) +def get_dob(): + age_raw = (request.values.get("age") or "").strip() + unit = (request.values.get("ageUnit") or "years").strip().lower() + if not age_raw.isdigit() or int(age_raw) <= 0: + return "", 400 + age = int(age_raw) + today = date.today() + + try: + if unit == "years": + if age > 120: + return "", 400 + try: + dob = today.replace(year=today.year - age) + except ValueError: + dob = today.replace(year=today.year - age, day=28) + elif unit == "months": + if age > 1440: + return "", 400 + total_months = today.year * 12 + (today.month - 1) - age + year, month_zero = divmod(total_months, 12) + month = month_zero + 1 + days_in_month = [31, 29 if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] + dob = date(year, month, min(today.day, days_in_month)) + elif unit == "weeks": + if age > 6260: + return "", 400 + dob = today - timedelta(weeks=age) + elif unit == "days": + if age > 43800: + return "", 400 + dob = today - timedelta(days=age) + else: + return "", 400 + except (OverflowError, ValueError): + return "", 400 + + return dob.strftime("%d/%m/%Y") + + +@app.route("/uploadProxy.php", methods=["POST"]) +def upload_proxy(): + if _is_rate_limited("upload_proxy", 20): + return render_template("error.html", errors=["Too many registration attempts. Please try again shortly."]), 429 + + cleaned, errors = validate_registration( + request.form, + request.files, + session_captcha=session.get("captcha"), + ) + if errors: + return render_template("error.html", errors=errors), 400 + + ptn_photo_file = cleaned.pop("ptnPhoto_file") + id_file_obj = cleaned.pop("id_file_obj") + + # Enforce magic-byte, size, dimension, EXIF strip & malware scan on legacy path too + try: + photo_meta = process_staged_upload( + raw_bytes=ptn_photo_file.read(), + category="PHOTO", + upload_root=app.config["UPLOAD_FOLDER"], + session_id="legacy", + ) + kyc_meta = process_staged_upload( + raw_bytes=id_file_obj.read(), + category="KYC", + upload_root=app.config["UPLOAD_FOLDER"], + session_id="legacy", + doc_type_id=cleaned["doc_type"], + ) + except UploadValidationError as exc: + return render_template("error.html", errors=[exc.message]), exc.status_code if exc.status_code in (400, 413) else 400 + + # Consume legacy session captcha after validation + session.pop("captcha", None) + + def _move_to_ref_dir(ref_id: str) -> tuple[str, str]: + ref_dir = os.path.join(app.config["UPLOAD_FOLDER"], ref_id) + os.makedirs(ref_dir, exist_ok=True) + photo_name = f"photo_{os.path.basename(photo_meta['storage_key'])}" + kyc_name = f"kyc_{os.path.basename(kyc_meta['storage_key'])}" + shutil.move(os.path.join(app.config["UPLOAD_FOLDER"], photo_meta["storage_key"]), os.path.join(ref_dir, photo_name)) + shutil.move(os.path.join(app.config["UPLOAD_FOLDER"], kyc_meta["storage_key"]), os.path.join(ref_dir, kyc_name)) + return f"{ref_id}/{photo_name}", f"{ref_id}/{kyc_name}" + + try: + ref_id = db.save_registration(cleaned, save_files_cb=_move_to_ref_dir) + except Exception: + corr = str(uuid.uuid4()) + app.logger.exception("Registration save failed correlation_id=%s", corr) + for meta in (photo_meta, kyc_meta): + p = os.path.join(app.config["UPLOAD_FOLDER"], meta["storage_key"]) + if os.path.exists(p): + os.remove(p) + return render_template("error.html", errors=[f"Unable to save registration at this time (Ref: {corr})."]), 500 + + return render_template("success.html", reference_form_id=ref_id) + + +# ============================================================ +# Modernized /api/v1 REST Endpoints +# ============================================================ + +def _api_error(code: str, message: str, status: int, errors: list[dict] | None = None): + body = {"success": False, "code": code, "message": message} + if errors is not None: + body["errors"] = errors + return jsonify(body), status + + +@app.route("/api/v1/registration-sessions", methods=["POST"]) +def api_create_session(): + if _is_rate_limited("sessions", 60): + return _api_error("RATE_LIMITED", "Too many session requests.", 429) + data = db.create_registration_session() + return jsonify({"success": True, "data": data}), 201 + + +@app.route("/api/v1/captcha", methods=["GET"]) +def api_get_captcha(): + if _is_rate_limited("captcha", 60): + return _api_error("RATE_LIMITED", "Too many CAPTCHA requests.", 429) + session_id = request.args.get("sessionId") or request.headers.get("X-Session-Id", "") + if not session_id: + return _api_error("BAD_REQUEST", "sessionId is required.", 400) + code = "".join(random.choices(string.ascii_letters, k=4)) + challenge = db.create_captcha_challenge(session_id, code) + # Never return plaintext CAPTCHA answer in API response + return jsonify({"success": True, "data": {**challenge, "imageDataUrl": _render_captcha_png_b64(code)}}), 200 + + +@app.route("/api/v1/masters/registration-options", methods=["GET"]) +def api_master_options(): + return jsonify({ + "success": True, + "data": { + "titles": db.get_master_list("titles"), + "genders": db.get_master_list("genders"), + "relations": db.get_master_list("relations"), + "docTypes": db.get_master_list("doc-types"), + "countries": db.get_master_list("countries"), + "defaults": {"countryId": 38, "stateId": 12, "cityId": 289}, + }, + }), 200 + + +@app.route("/api/v1/masters/", methods=["GET"]) +def api_master_by_type(master_type: str): + items = db.get_master_list(master_type) + if items is None: + return _api_error("NOT_FOUND", "Unknown master type.", 404) + return jsonify({"success": True, "data": items}), 200 + + +@app.route("/api/v1/masters/states", methods=["GET"]) +def api_master_states(): + cid = request.args.get("countryId", "38") + if not cid.isdigit(): + return _api_error("BAD_REQUEST", "Invalid countryId.", 400) + return jsonify({"success": True, "data": db.get_states_by_country(int(cid))}), 200 + + +@app.route("/api/v1/masters/cities", methods=["GET"]) +def api_master_cities(): + sid = request.args.get("stateId", "") + if not sid.isdigit(): + return _api_error("BAD_REQUEST", "Invalid stateId.", 400) + return jsonify({"success": True, "data": db.get_cities_by_state(int(sid))}), 200 + + +@app.route("/api/v1/uploads", methods=["POST"]) +def api_upload_staged(): + if _is_rate_limited("uploads", 30): + return _api_error("RATE_LIMITED", "Too many upload requests.", 429) + session_id = (request.form.get("sessionId") or request.headers.get("X-Session-Id") or "").strip() + category = (request.form.get("category") or "").strip() + doc_type_raw = (request.form.get("docTypeId") or "").strip() + file_obj = request.files.get("file") + + if not session_id: + return _api_error("BAD_REQUEST", "sessionId is required.", 400) + if not file_obj: + return _api_error("VALIDATION_ERROR", "File is required.", 422) + + doc_type_id = int(doc_type_raw) if doc_type_raw.isdigit() else None + try: + meta = process_staged_upload( + raw_bytes=file_obj.read(), + category=category, + upload_root=app.config["UPLOAD_FOLDER"], + session_id=session_id, + doc_type_id=doc_type_id, + ) + db.save_staged_upload(meta) + except UploadValidationError as exc: + return _api_error("UPLOAD_ERROR", exc.message, exc.status_code) + + return jsonify({ + "success": True, + "data": {"uploadId": meta["id"], "scanStatus": meta["scan_status"], "mimeType": meta["mime_type"]}, + }), 201 + + +@app.route("/api/v1/uploads/", methods=["DELETE"]) +def api_delete_staged_upload(upload_id: str): + session_id = request.args.get("sessionId") or request.headers.get("X-Session-Id", "") + if not session_id: + return _api_error("BAD_REQUEST", "sessionId is required.", 400) + storage_key = db.delete_staged_upload(upload_id, session_id) + if not storage_key: + return _api_error("NOT_FOUND", "Upload not found or not owned by session.", 404) + full_path = os.path.join(app.config["UPLOAD_FOLDER"], storage_key) + if os.path.exists(full_path): + os.remove(full_path) + return jsonify({"success": True}), 200 + + +@app.route("/api/v1/registrations", methods=["POST"]) +def api_create_registration(): + if _is_rate_limited("registrations", 20): + return _api_error("RATE_LIMITED", "Too many registration requests.", 429) + payload = request.get_json(silent=True) + if not isinstance(payload, dict): + return _api_error("BAD_REQUEST", "JSON payload is required.", 400) + + session_id = str(payload.get("sessionId") or request.headers.get("X-Session-Id") or "").strip() + idem_key = str(request.headers.get("Idempotency-Key") or "").strip() + if not session_id or not idem_key: + return _api_error("BAD_REQUEST", "sessionId and Idempotency-Key header are required.", 400) + + fp_payload = {k: v for k, v in payload.items() if k != "captcha"} + fingerprint = hashlib.sha256(json.dumps(fp_payload, sort_keys=True).encode("utf-8")).hexdigest() + + # 1. Replay check BEFORE field validation / CAPTCHA consumption + conn = db.get_connection() + try: + with conn.cursor() as cur: + idem = db.check_or_reserve_idempotency(cur, session_id, idem_key, fingerprint) + if idem["state"] == "CONFLICT": + conn.rollback() + return _api_error("IDEMPOTENCY_CONFLICT", "Idempotency-Key reused with different payload.", 409) + if idem["state"] == "COMPLETED": + conn.rollback() + return jsonify(idem["response"]), idem["http_status"] + if idem["state"] == "IN_PROGRESS": + conn.rollback() + return _api_error("CONFLICT", "Registration request already in progress.", 409) + + # 2. Validate fields BEFORE consuming CAPTCHA so validation errors don't burn CAPTCHA or trap key + cleaned, errors = validate_core_fields(payload, skip_captcha=True) + if errors: + db.release_idempotency_reservation(cur, session_id, idem_key) + conn.commit() + return _api_error( + "VALIDATION_ERROR", + "Validation failed.", + 422, + [{"field": "form", "message": msg} for msg in errors], + ) + + photo_upload_id = str(payload.get("photoUploadId") or "").strip() + kyc_upload_id = str(payload.get("kycUploadId") or "").strip() + if not photo_upload_id or not kyc_upload_id or photo_upload_id == kyc_upload_id: + db.release_idempotency_reservation(cur, session_id, idem_key) + conn.commit() + return _api_error("VALIDATION_ERROR", "Distinct photoUploadId and kycUploadId are required.", 422) + + # 3. Verify & consume single-use CAPTCHA + captcha = payload.get("captcha") or {} + if not db.verify_and_consume_captcha( + cur, session_id, str(captcha.get("challengeId") or ""), str(captcha.get("answer") or "") + ): + db.release_idempotency_reservation(cur, session_id, idem_key) + conn.commit() + return _api_error("VALIDATION_ERROR", "Invalid or expired CAPTCHA.", 422, [{"field": "captcha", "message": "Invalid or expired CAPTCHA."}]) + conn.commit() + finally: + conn.close() + + try: + status_code, body = db.save_registration_v1( + cleaned=cleaned, + session_id=session_id, + idempotency_key=idem_key, + payload_fingerprint=fingerprint, + photo_upload_id=photo_upload_id, + kyc_upload_id=kyc_upload_id, + ) + return jsonify(body), status_code + except ValueError as exc: + conn2 = db.get_connection() + try: + with conn2.cursor() as cur2: + db.release_idempotency_reservation(cur2, session_id, idem_key) + conn2.commit() + finally: + conn2.close() + return _api_error("VALIDATION_ERROR", str(exc), 422) + + +@app.route("/api/v1/registrations//status", methods=["GET"]) +def api_registration_status(reference: str): + session_id = request.headers.get("X-Session-Id") or request.args.get("sessionId") + if not session_id: + return _api_error("UNAUTHORIZED", "Session or access token required.", 401) + row = db.get_registration_status_by_ref(reference) + if not row: + return _api_error("NOT_FOUND", "Registration not found.", 404) + if not row["session_id"] or row["session_id"] != session_id: + return _api_error("FORBIDDEN", "Not authorized to access this registration.", 403) + return jsonify({ + "success": True, + "data": { + "registrationReference": row["reference_form_id"], + "status": row["status"], + "hospitalPatientId": row["hospital_patient_id"], + "emailStatus": row["email_status"], + }, + }), 200 + + +# ============================================================ +# Staff / Admin Endpoints (SSO Token + DB-Backed RBAC) +# ============================================================ + +def _require_admin_role(*allowed_roles: str): + def decorator(fn): + @wraps(fn) + def wrapper(*args, **kwargs): + expected_secret = os.getenv("ADMIN_SSO_SECRET", "dev-admin-sso-token") + token = request.headers.get("X-Admin-Token", "") + sso_subject = (request.headers.get("X-Admin-Subject") or "").strip() + if not token or token != expected_secret or not sso_subject: + return _api_error("UNAUTHORIZED", "Valid staff SSO token and subject required.", 401) + user = db.get_admin_user(sso_subject) + if not user or user["role"] not in allowed_roles: + return _api_error("FORBIDDEN", "Insufficient role permissions.", 403) + request.admin_user = user + return fn(*args, **kwargs) + return wrapper + return decorator + + +@app.route("/api/v1/admin/registrations", methods=["GET"]) +@_require_admin_role("REG_STAFF", "SUPERVISOR", "SYS_ADMIN") +def api_admin_list_registrations(): + status_filter = request.args.get("status") + return jsonify({"success": True, "data": db.list_registrations_admin(status_filter)}), 200 + + +@app.route("/api/v1/admin/registrations//documents/", methods=["GET"]) +@_require_admin_role("REG_STAFF", "SUPERVISOR") +def api_admin_download_document(reg_id: int, doc_id: str): + doc = db.get_registration_document_for_admin(reg_id, doc_id, request.admin_user["sso_subject"]) + if not doc: + return _api_error("NOT_FOUND", "Document not found.", 404) + full_path = os.path.join(app.config["UPLOAD_FOLDER"], doc["storage_key"]) + if not os.path.exists(full_path): + return _api_error("NOT_FOUND", "Document file missing on disk.", 404) + return send_file(full_path, mimetype=doc["mime_type"], as_attachment=True) + + +@app.route("/api/v1/admin/registrations//review", methods=["POST"]) +@_require_admin_role("SUPERVISOR") +def api_admin_review_registration(reg_id: int): + body = request.get_json(silent=True) or {} + decision = (body.get("decision") or "").upper() + reason = (body.get("reason") or "").strip() + uhid = (body.get("hospitalPatientId") or "").strip() or None + actor = request.admin_user["sso_subject"] + + decision_map = { + "APPROVE_NEW": "PENDING_HIS_SYNC", + "LINK_EXISTING": "LINKED_EXISTING", + "REJECT": "REJECTED", + } + if decision not in decision_map or not reason: + return _api_error("VALIDATION_ERROR", "Valid decision and audit reason are required.", 422) + if decision == "LINK_EXISTING" and not uhid: + return _api_error("VALIDATION_ERROR", "hospitalPatientId is required for LINK_EXISTING.", 422) + + conn = db.get_connection() + try: + with conn.cursor() as cur: + db.transition_registration_status( + cur, reg_id, decision_map[decision], actor, reason=reason, hospital_patient_id=uhid + ) + if decision == "APPROVE_NEW": + cur.execute( + """ + INSERT INTO outbox_events (id, registration_id, event_type, status, correlation_id) + VALUES (%s, %s, 'HIS_CREATE', 'PENDING', %s) + """, + (str(uuid.uuid4()), reg_id, str(uuid.uuid4())), + ) + conn.commit() + return jsonify({"success": True, "data": {"status": decision_map[decision]}}), 200 + except ValueError as exc: + conn.rollback() + return _api_error("VALIDATION_ERROR", str(exc), 422) + finally: + conn.close() + + +@app.route("/api/v1/admin/registrations//retry", methods=["POST"]) +@_require_admin_role("SUPERVISOR", "SYS_ADMIN") +def api_admin_retry_registration(reg_id: int): + actor = request.admin_user["sso_subject"] + conn = db.get_connection() + try: + with conn.cursor() as cur: + cur.execute("SELECT status FROM patient_registration WHERE id = %s FOR UPDATE", (reg_id,)) + row = cur.fetchone() + if not row: + conn.rollback() + return _api_error("NOT_FOUND", "Registration not found.", 404) + + if row["status"] == "CHECKING_DUPLICATES": + event_type = "DUPLICATE_CHECK" + next_status = "CHECKING_DUPLICATES" + cur.execute( + "INSERT INTO audit_logs (registration_id, actor, action, from_status, to_status, reason) VALUES (%s, %s, 'MANUAL_RETRY', %s, %s, %s)", + (reg_id, actor, "CHECKING_DUPLICATES", "CHECKING_DUPLICATES", "Manual duplicate check retry"), + ) + else: + next_status = "PENDING_HIS_SYNC" + event_type = "HIS_CREATE" + db.transition_registration_status( + cur, reg_id, next_status, actor, reason="Manual retry requested" + ) + + cur.execute( + """ + INSERT INTO outbox_events (id, registration_id, event_type, status, correlation_id) + VALUES (%s, %s, %s, 'PENDING', %s) + """, + (str(uuid.uuid4()), reg_id, event_type, str(uuid.uuid4())), + ) + conn.commit() + return jsonify({"success": True, "data": {"status": next_status}}), 200 + except ValueError as exc: + conn.rollback() + return _api_error("VALIDATION_ERROR", str(exc), 422) + finally: + conn.close() + + +@app.route("/api/v1/admin/audit-logs", methods=["GET"]) +@_require_admin_role("SUPERVISOR", "SYS_ADMIN") +def api_admin_audit_logs(): + reg_id_raw = request.args.get("registrationId", "").strip() + if reg_id_raw and not reg_id_raw.isdigit(): + return _api_error("BAD_REQUEST", "registrationId must be a positive integer.", 400) + reg_id = int(reg_id_raw) if reg_id_raw else None + return jsonify({"success": True, "data": db.list_audit_logs_admin(reg_id)}), 200 + + +if __name__ == "__main__": + debug_flag = os.getenv("FLASK_DEBUG", "false").strip().lower() in ("1", "true", "yes") + app.run(debug=debug_flag, host="127.0.0.1", port=5000) diff --git a/crypto_utils.py b/crypto_utils.py new file mode 100644 index 0000000..ed6214f --- /dev/null +++ b/crypto_utils.py @@ -0,0 +1,89 @@ +""" +Field-level encryption (Fernet), keyed match tokens, +PII masking, and log redaction helpers. +Fails fast in production if secrets are missing or use dev defaults. +""" + +import base64 +import hashlib +import hmac +import logging +import os +import re + +from cryptography.fernet import Fernet + +_DEV_ENC_DEFAULT = "dev-pii-encryption-key-change-in-prod" +_DEV_HMAC_DEFAULT = "dev-hmac-secret-key-change-me" + + +def validate_production_secrets() -> None: + """Ensure production deployments never run with missing or default secrets.""" + if os.getenv("FLASK_ENV", "development").strip().lower() != "production": + return + required = { + "FLASK_SECRET_KEY": {"", "dev-secret-change-me", "change-me-in-production"}, + "PII_ENCRYPTION_KEY": {"", _DEV_ENC_DEFAULT, "dev-32-byte-fernet-or-aes-secret-key!!"}, + "PII_HMAC_KEY": {"", _DEV_HMAC_DEFAULT}, + "ADMIN_SSO_SECRET": {"", "dev-admin-sso-token"}, + } + for var, bad_vals in required.items(): + val = (os.getenv(var) or "").strip() + if val in bad_vals or len(val) < 16: + raise RuntimeError(f"Insecure or missing {var} for FLASK_ENV=production.") + + +def _get_fernet() -> Fernet: + validate_production_secrets() + raw = os.getenv("PII_ENCRYPTION_KEY", _DEV_ENC_DEFAULT) + digest = hashlib.sha256(raw.encode("utf-8")).digest() + return Fernet(base64.urlsafe_b64encode(digest)) + + +def encrypt_pii(plaintext: str | None) -> bytes | None: + if not plaintext: + return None + return _get_fernet().encrypt(plaintext.encode("utf-8")) + + +def decrypt_pii(ciphertext: bytes | None) -> str | None: + if not ciphertext: + return None + return _get_fernet().decrypt(ciphertext).decode("utf-8") + + +def compute_match_token(id_type: str, plaintext: str | None) -> str | None: + if not plaintext: + return None + validate_production_secrets() + key = os.getenv("PII_HMAC_KEY", _DEV_HMAC_DEFAULT).encode("utf-8") + msg = f"{id_type}:{plaintext.strip().upper()}".encode("utf-8") + return hmac.new(key, msg, hashlib.sha256).hexdigest() + + +def mask_aadhaar(aadhar: str | None) -> str | None: + if not aadhar or len(aadhar) < 4: + return None + return f"XXXX-XXXX-{aadhar[-4:]}" + + +def mask_pan(pan: str | None) -> str | None: + if not pan or len(pan) < 4: + return None + return f"XXXXXX{pan[-4:]}" + + +_AADHAAR_LOG_RE = re.compile(r"\b\d{12}\b") +_PAN_LOG_RE = re.compile(r"\b[A-Za-z]{5}\d{4}[A-Za-z]\b") + + +class PiiRedactingFilter(logging.Filter): + """Redact accidental Aadhaar/PAN patterns from log messages.""" + + def filter(self, record: logging.LogRecord) -> bool: + msg = str(record.getMessage()) + msg = _AADHAAR_LOG_RE.sub("XXXX-XXXX-REDACTED", msg) + msg = _PAN_LOG_RE.sub("XXXXX-REDACTED", msg) + record.msg = msg + record.args = () + return True diff --git a/db.py b/db.py new file mode 100644 index 0000000..39aaf53 --- /dev/null +++ b/db.py @@ -0,0 +1,734 @@ +""" +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() diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..656b675 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,33 @@ +services: + web: + build: . + ports: + - "5000:5000" + env_file: + - .env + volumes: + - uploads_data:/app/uploads + depends_on: + - db + + worker: + build: . + command: ["python", "worker.py"] + env_file: + - .env + volumes: + - uploads_data:/app/uploads + depends_on: + - db + + db: + image: mysql:8.0 + environment: + MYSQL_DATABASE: dmh_registration + volumes: + - mysql_data:/var/lib/mysql + - ./schema.sql:/docker-entrypoint-initdb.d/01_schema.sql:ro + +volumes: + uploads_data: + mysql_data: diff --git a/email_service.py b/email_service.py new file mode 100644 index 0000000..b1b0427 --- /dev/null +++ b/email_service.py @@ -0,0 +1,39 @@ +""" +Minimal, PII-free confirmation email sender with STARTTLS support. +Email delivery failure never rolls back registration. +""" + +import os +import smtplib +from email.message import EmailMessage + + +def send_confirmation_email(*, to_email: str, reference_form_id: str, status: str) -> None: + """Send minimal registration acknowledgement without raw PII or KYC attachments.""" + host = os.getenv("SMTP_HOST", "localhost") + port = int(os.getenv("SMTP_PORT", "587")) + use_tls = os.getenv("SMTP_USE_TLS", "true").strip().lower() in ("1", "true", "yes") + sender = os.getenv("SMTP_FROM", "noreply@dmhospital.org") + + msg = EmailMessage() + msg["Subject"] = f"DMH Patient Registration Received - Ref {reference_form_id}" + msg["From"] = sender + msg["To"] = to_email + msg.set_content( + f"Dear Patient,\n\n" + f"Your registration request has been received.\n" + f"Reference Form ID: {reference_form_id}\n" + f"Current Status: {status}\n\n" + f"Deenanath Mangeshkar Hospital Support Team\n" + ) + + with smtplib.SMTP(host, port, timeout=10) as smtp: + smtp.ehlo() + if use_tls: + smtp.starttls() + smtp.ehlo() + user = os.getenv("SMTP_USER", "") + pwd = os.getenv("SMTP_PASSWORD", "") + if user and pwd: + smtp.login(user, pwd) + smtp.send_message(msg) diff --git a/his_adapter.py b/his_adapter.py new file mode 100644 index 0000000..0d2938f --- /dev/null +++ b/his_adapter.py @@ -0,0 +1,87 @@ +""" +Amrita HIS Integration Adapter interface + HIS_MODE guard. +Never fabricates a production UHID; MockHISAdapter is blocked in production. +""" + +import os +from abc import ABC, abstractmethod +from dataclasses import dataclass + + +@dataclass +class HISSearchResult: + outcome: str # 'NONE' | 'CANDIDATE' | 'ERROR' + candidate_uhid: str | None = None + reason: str | None = None + + +@dataclass +class HISCreateResult: + outcome: str # 'SUCCESS' | 'REJECTED' | 'TIMEOUT' + uhid: str | None = None + reason: str | None = None + + +@dataclass +class HISReconcileResult: + outcome: str # 'FOUND' | 'ABSENT' | 'UNRESOLVED' + uhid: str | None = None + reason: str | None = None + + +class BaseHISAdapter(ABC): + @abstractmethod + def search_patient(self, *, match_tokens: list[str], fname: str, lname: str, dob: str, mobile: str | None) -> HISSearchResult: + pass + + @abstractmethod + def create_patient(self, *, correlation_id: str, payload: dict) -> HISCreateResult: + pass + + @abstractmethod + def reconcile_registration(self, *, correlation_id: str, reference_form_id: str) -> HISReconcileResult: + pass + + +class MockHISAdapter(BaseHISAdapter): + """Deterministic mock adapter for local/test environments only.""" + + def search_patient(self, *, match_tokens: list[str], fname: str, lname: str, dob: str, mobile: str | None) -> HISSearchResult: + if lname == "DUPLICATE": + return HISSearchResult(outcome="CANDIDATE", candidate_uhid="UHID-900001", reason="Exact name+DOB match") + return HISSearchResult(outcome="NONE") + + def create_patient(self, *, correlation_id: str, payload: dict) -> HISCreateResult: + return HISCreateResult(outcome="SUCCESS", uhid=f"MOCK-UHID-{payload['reference_form_id']}") + + def reconcile_registration(self, *, correlation_id: str, reference_form_id: str) -> HISReconcileResult: + return HISReconcileResult(outcome="ABSENT", reason="Not found in mock HIS") + + +class DisabledHISAdapter(BaseHISAdapter): + """Safe no-op adapter when HIS_MODE=disabled: never issues fake UHIDs.""" + + def search_patient(self, *, match_tokens: list[str], fname: str, lname: str, dob: str, mobile: str | None) -> HISSearchResult: + return HISSearchResult(outcome="NONE") + + def create_patient(self, *, correlation_id: str, payload: dict) -> HISCreateResult: + return HISCreateResult(outcome="TIMEOUT", reason="HIS integration disabled (HIS_MODE=disabled)") + + def reconcile_registration(self, *, correlation_id: str, reference_form_id: str) -> HISReconcileResult: + return HISReconcileResult(outcome="ABSENT", reason="HIS integration disabled") + + +def get_his_adapter() -> BaseHISAdapter: + """Resolve HIS adapter from HIS_MODE, blocking mock mode in production.""" + mode = os.getenv("HIS_MODE", "disabled").strip().lower() + env = os.getenv("FLASK_ENV", "development").strip().lower() + + if mode == "mock": + if env == "production": + raise RuntimeError("HIS_MODE=mock is forbidden when FLASK_ENV=production.") + return MockHISAdapter() + if mode == "disabled": + return DisabledHISAdapter() + if mode == "amrita": + raise NotImplementedError("Official Amrita HIS adapter is not yet configured.") + raise ValueError(f"Unsupported HIS_MODE: {mode}") diff --git a/migrate_v2.sql b/migrate_v2.sql new file mode 100644 index 0000000..4caa64c --- /dev/null +++ b/migrate_v2.sql @@ -0,0 +1,136 @@ +-- Upgrade script for an existing v1 dmh_registration database to v2.0 +-- Run in MySQL: SOURCE C:/Users/Ayush Shah/Desktop/Reverse_Engeering_Flask_Form/migrate_v2.sql + +USE dmh_registration; + +-- 1. Add is_active to existing lookup tables +ALTER TABLE lookup_genders ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1; +ALTER TABLE lookup_titles ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1; +ALTER TABLE lookup_relations ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1; +ALTER TABLE lookup_doc_types ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1; +ALTER TABLE lookup_countries ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1; +ALTER TABLE lookup_states ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1; +ALTER TABLE lookup_cities ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1; + +-- 2. Add v2.0 lifecycle/UHID columns to existing patient_registration +ALTER TABLE patient_registration + ADD COLUMN hospital_patient_id VARCHAR(50) NULL UNIQUE AFTER reference_form_id, + ADD COLUMN status ENUM( + 'SUBMITTED','CHECKING_DUPLICATES','PENDING_REVIEW','PENDING_HIS_SYNC', + 'REGISTERED','SYNC_FAILED','LINKED_EXISTING','REJECTED' + ) NOT NULL DEFAULT 'SUBMITTED' AFTER hospital_patient_id, + ADD COLUMN version INT NOT NULL DEFAULT 1 AFTER status, + ADD COLUMN age_recorded_at DATETIME NULL AFTER approx_dob, + ADD COLUMN email_status ENUM('PENDING','SENT','FAILED') NOT NULL DEFAULT 'PENDING' AFTER id_file_path, + ADD COLUMN status_updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER created_at; + +-- 3. Create all new v2.0 tables (safe with IF NOT EXISTS) +CREATE TABLE IF NOT EXISTS reference_sequences ( + seq_name VARCHAR(50) NOT NULL PRIMARY KEY, + next_val BIGINT NOT NULL +) ENGINE=InnoDB; + +INSERT IGNORE INTO reference_sequences (seq_name, next_val) VALUES ('patient_registration', 250044); + +CREATE TABLE IF NOT EXISTS registration_sessions ( + id CHAR(36) NOT NULL PRIMARY KEY, + expires_at DATETIME NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS captcha_challenges ( + id CHAR(36) NOT NULL PRIMARY KEY, + session_id CHAR(36) NOT NULL, + answer_hash CHAR(64) NOT NULL, + expires_at DATETIME NOT NULL, + consumed TINYINT(1) NOT NULL DEFAULT 0, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + INDEX idx_captcha_session (session_id) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS idempotency_records ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + session_id CHAR(36) NOT NULL, + idempotency_key VARCHAR(128) NOT NULL, + payload_fingerprint CHAR(64) NOT NULL, + status ENUM('IN_PROGRESS', 'COMPLETED') NOT NULL DEFAULT 'IN_PROGRESS', + http_status SMALLINT NULL, + response_json JSON NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY uq_session_idem (session_id, idempotency_key) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS patient_identifiers ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + reference_form_id VARCHAR(20) NOT NULL, + id_type ENUM('PAN', 'AADHAAR') NOT NULL, + encrypted_value VARBINARY(512) NOT NULL, + masked_value VARCHAR(32) NOT NULL, + match_token CHAR(64) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY uq_ref_id_type (reference_form_id, id_type), + INDEX idx_match_token (id_type, match_token), + CONSTRAINT fk_ident_ref FOREIGN KEY (reference_form_id) REFERENCES patient_registration(reference_form_id) ON DELETE CASCADE +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS patient_documents ( + id CHAR(36) NOT NULL PRIMARY KEY, + session_id CHAR(36) NOT NULL, + patient_id BIGINT UNSIGNED NULL, + doc_category ENUM('PHOTO', 'KYC') NOT NULL, + doc_type_id INT NULL, + storage_key VARCHAR(255) NOT NULL, + mime_type VARCHAR(100) NOT NULL, + size_bytes INT NOT NULL, + scan_status ENUM('PENDING', 'CLEAN', 'REJECTED', 'ATTACHED') NOT NULL DEFAULT 'PENDING', + expires_at DATETIME NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + INDEX idx_doc_session (session_id), + INDEX idx_doc_patient (patient_id), + CONSTRAINT fk_doc_patient FOREIGN KEY (patient_id) REFERENCES patient_registration(id) ON DELETE CASCADE +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS consent_records ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + patient_id BIGINT UNSIGNED NOT NULL, + privacy_notice_version VARCHAR(32) NOT NULL, + lawful_basis VARCHAR(64) NOT NULL, + consented_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_consent_patient FOREIGN KEY (patient_id) REFERENCES patient_registration(id) ON DELETE CASCADE +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS outbox_events ( + id CHAR(36) NOT NULL PRIMARY KEY, + registration_id BIGINT UNSIGNED NOT NULL, + event_type ENUM('DUPLICATE_CHECK', 'HIS_CREATE', 'EMAIL_CONFIRMATION') NOT NULL, + status ENUM('PENDING', 'LOCKED', 'DONE', 'FAILED') NOT NULL DEFAULT 'PENDING', + attempts INT NOT NULL DEFAULT 0, + next_run_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + locked_until DATETIME NULL, + correlation_id CHAR(36) NOT NULL, + last_error VARCHAR(500) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + INDEX idx_outbox_poll (status, next_run_at), + CONSTRAINT fk_outbox_reg FOREIGN KEY (registration_id) REFERENCES patient_registration(id) ON DELETE CASCADE +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS audit_logs ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + registration_id BIGINT UNSIGNED NULL, + actor VARCHAR(100) NOT NULL, + action VARCHAR(100) NOT NULL, + from_status VARCHAR(32) NULL, + to_status VARCHAR(32) NULL, + reason VARCHAR(255) NULL, + correlation_id CHAR(36) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + INDEX idx_audit_reg (registration_id, created_at) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS admin_users ( + id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + sso_subject VARCHAR(150) NOT NULL UNIQUE, + role ENUM('REG_STAFF', 'SUPERVISOR', 'SYS_ADMIN') NOT NULL, + is_active TINYINT(1) NOT NULL DEFAULT 1, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB; diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e797ee8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +Flask>=3.0.0 +PyMySQL>=1.1.0 +cryptography>=42.0.0 +Pillow>=10.0.0 +pytest>=8.0.0 +python-dotenv>=1.0.0 diff --git a/schema.sql b/schema.sql new file mode 100644 index 0000000..44ed912 --- /dev/null +++ b/schema.sql @@ -0,0 +1,395 @@ +-- DMH Patient Registration Database Schema (MySQL 8.0+) +-- Includes v1.0 & v2.0 modernization tables while preserving exact legacy dropdown IDs. + +CREATE DATABASE IF NOT EXISTS dmh_registration + CHARACTER SET utf8mb4 + COLLATE utf8mb4_unicode_ci; + +USE dmh_registration; + +-- ============================================================ +-- 1. Lookup Master Tables (with is_active flags) +-- ============================================================ + +CREATE TABLE IF NOT EXISTS lookup_genders ( + id INT NOT NULL PRIMARY KEY, + name VARCHAR(30) NOT NULL, + is_active TINYINT(1) NOT NULL DEFAULT 1 +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS lookup_titles ( + id INT NOT NULL PRIMARY KEY, + name VARCHAR(50) NOT NULL, + default_gender_id INT NULL, + is_active TINYINT(1) NOT NULL DEFAULT 1, + CONSTRAINT fk_title_gender FOREIGN KEY (default_gender_id) REFERENCES lookup_genders(id) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS lookup_relations ( + id INT NOT NULL PRIMARY KEY, + name VARCHAR(50) NOT NULL, + is_active TINYINT(1) NOT NULL DEFAULT 1 +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS lookup_doc_types ( + id INT NOT NULL PRIMARY KEY, + name VARCHAR(100) NOT NULL, + is_active TINYINT(1) NOT NULL DEFAULT 1 +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS lookup_countries ( + id INT NOT NULL PRIMARY KEY, + name VARCHAR(100) NOT NULL, + is_active TINYINT(1) NOT NULL DEFAULT 1, + INDEX idx_country_name (name) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS lookup_states ( + id INT NOT NULL PRIMARY KEY, + country_id INT NOT NULL, + name VARCHAR(100) NOT NULL, + is_active TINYINT(1) NOT NULL DEFAULT 1, + INDEX idx_state_country (country_id), + CONSTRAINT fk_state_country FOREIGN KEY (country_id) REFERENCES lookup_countries(id) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS lookup_cities ( + id INT NOT NULL PRIMARY KEY, + state_id INT NOT NULL, + name VARCHAR(100) NOT NULL, + is_active TINYINT(1) NOT NULL DEFAULT 1, + INDEX idx_city_state (state_id), + CONSTRAINT fk_city_state FOREIGN KEY (state_id) REFERENCES lookup_states(id) +) ENGINE=InnoDB; + +-- ============================================================ +-- 2. Atomic Reference ID Sequence & Session / CAPTCHA / Idempotency +-- ============================================================ + +CREATE TABLE IF NOT EXISTS reference_sequences ( + seq_name VARCHAR(50) NOT NULL PRIMARY KEY, + next_val BIGINT NOT NULL +) ENGINE=InnoDB; + +INSERT IGNORE INTO reference_sequences (seq_name, next_val) VALUES ('patient_registration', 250044); + +CREATE TABLE IF NOT EXISTS registration_sessions ( + id CHAR(36) NOT NULL PRIMARY KEY, + expires_at DATETIME NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS captcha_challenges ( + id CHAR(36) NOT NULL PRIMARY KEY, + session_id CHAR(36) NOT NULL, + answer_hash CHAR(64) NOT NULL, + expires_at DATETIME NOT NULL, + consumed TINYINT(1) NOT NULL DEFAULT 0, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + INDEX idx_captcha_session (session_id) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS idempotency_records ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + session_id CHAR(36) NOT NULL, + idempotency_key VARCHAR(128) NOT NULL, + payload_fingerprint CHAR(64) NOT NULL, + status ENUM('IN_PROGRESS', 'COMPLETED') NOT NULL DEFAULT 'IN_PROGRESS', + http_status SMALLINT NULL, + response_json JSON NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY uq_session_idem (session_id, idempotency_key) +) ENGINE=InnoDB; + +-- ============================================================ +-- 3. Core Patient Registration, Addresses, Encrypted IDs & Documents +-- ============================================================ + +CREATE TABLE IF NOT EXISTS patient_registration ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + reference_form_id VARCHAR(20) NOT NULL, + session_id CHAR(36) NULL, + hospital_patient_id VARCHAR(50) NULL, + status ENUM( + 'SUBMITTED', + 'CHECKING_DUPLICATES', + 'PENDING_REVIEW', + 'PENDING_HIS_SYNC', + 'REGISTERED', + 'SYNC_FAILED', + 'LINKED_EXISTING', + 'REJECTED' + ) NOT NULL DEFAULT 'SUBMITTED', + version INT NOT NULL DEFAULT 1, + title_id INT NOT NULL, + lname VARCHAR(100) NOT NULL, + fname VARCHAR(100) NOT NULL, + mname VARCHAR(100) NULL, + gender_id INT NOT NULL, + father_husband_name VARCHAR(150) NULL, + dob DATE NOT NULL, + age INT NOT NULL, + age_unit TINYINT NOT NULL DEFAULT 0 COMMENT '0=Years, 1=Months, 2=Days, 3=Weeks', + approx_dob TINYINT(1) NOT NULL DEFAULT 0, + age_recorded_at DATETIME NULL, + marital_status ENUM('Single', 'Married', 'Divorced', 'Widowed') NULL, + dom DATE NULL, + before_marriage_name VARCHAR(150) NULL, + monthly_income DECIMAL(12, 2) NULL, + email VARCHAR(150) NOT NULL, + cell_phone VARCHAR(15) NULL, + phone VARCHAR(30) NULL, + office_phone VARCHAR(30) NULL, + emg_lname VARCHAR(100) NOT NULL, + emg_fname VARCHAR(100) NOT NULL, + emg_mname VARCHAR(100) NULL, + emg_relation_id INT NOT NULL, + emg_no VARCHAR(30) NOT NULL, + rep_name VARCHAR(150) NOT NULL, + rep_relation_id INT NOT NULL, + doc_type_id INT NOT NULL, + ptn_photo_path VARCHAR(255) NOT NULL, + id_file_path VARCHAR(255) NOT NULL, + email_status ENUM('PENDING', 'SENT', 'FAILED') NOT NULL DEFAULT 'PENDING', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + status_updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + + UNIQUE KEY uq_reference_form_id (reference_form_id), + INDEX idx_hospital_patient_id (hospital_patient_id), + INDEX idx_patient_session (session_id), + INDEX idx_patient_status (status, created_at), + INDEX idx_patient_email (email), + INDEX idx_patient_created (created_at), + + CONSTRAINT chk_age_positive CHECK (age > 0), + CONSTRAINT chk_age_unit CHECK (age_unit IN (0, 1, 2, 3)), + CONSTRAINT chk_approx_dob CHECK (approx_dob IN (0, 1)), + CONSTRAINT fk_patient_title FOREIGN KEY (title_id) REFERENCES lookup_titles(id), + CONSTRAINT fk_patient_gender FOREIGN KEY (gender_id) REFERENCES lookup_genders(id), + CONSTRAINT fk_patient_emg_rel FOREIGN KEY (emg_relation_id) REFERENCES lookup_relations(id), + CONSTRAINT fk_patient_rep_rel FOREIGN KEY (rep_relation_id) REFERENCES lookup_relations(id), + CONSTRAINT fk_patient_doc_type FOREIGN KEY (doc_type_id) REFERENCES lookup_doc_types(id) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS patient_address ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + patient_id BIGINT UNSIGNED NOT NULL, + address_type ENUM('LOCAL', 'PERMANENT') NOT NULL, + address1 VARCHAR(255) NULL, + address2 VARCHAR(255) NULL, + post_office VARCHAR(150) NULL, + country_id INT NOT NULL, + state_id INT NULL, + other_state VARCHAR(150) NULL, + city_id INT NULL, + other_city VARCHAR(150) NULL, + pincode VARCHAR(20) NULL, + phone VARCHAR(30) NULL, + + UNIQUE KEY uq_patient_address_type (patient_id, address_type), + INDEX idx_addr_country (country_id), + INDEX idx_addr_state (state_id), + INDEX idx_addr_city (city_id), + + CONSTRAINT fk_addr_patient FOREIGN KEY (patient_id) REFERENCES patient_registration(id) ON DELETE CASCADE, + CONSTRAINT fk_addr_country FOREIGN KEY (country_id) REFERENCES lookup_countries(id), + CONSTRAINT fk_addr_state FOREIGN KEY (state_id) REFERENCES lookup_states(id), + CONSTRAINT fk_addr_city FOREIGN KEY (city_id) REFERENCES lookup_cities(id) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS patient_identifiers ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + reference_form_id VARCHAR(20) NOT NULL, + id_type ENUM('PAN', 'AADHAAR') NOT NULL, + encrypted_value VARBINARY(512) NOT NULL, + masked_value VARCHAR(32) NOT NULL, + match_token CHAR(64) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + + UNIQUE KEY uq_ref_id_type (reference_form_id, id_type), + INDEX idx_match_token (id_type, match_token), + CONSTRAINT fk_ident_ref FOREIGN KEY (reference_form_id) REFERENCES patient_registration(reference_form_id) ON DELETE CASCADE +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS patient_documents ( + id CHAR(36) NOT NULL PRIMARY KEY, + session_id CHAR(36) NOT NULL, + patient_id BIGINT UNSIGNED NULL, + doc_category ENUM('PHOTO', 'KYC') NOT NULL, + doc_type_id INT NULL, + storage_key VARCHAR(255) NOT NULL, + mime_type VARCHAR(100) NOT NULL, + size_bytes INT NOT NULL, + scan_status ENUM('PENDING', 'CLEAN', 'REJECTED', 'ATTACHED') NOT NULL DEFAULT 'PENDING', + expires_at DATETIME NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + + INDEX idx_doc_session (session_id), + INDEX idx_doc_patient (patient_id), + CONSTRAINT fk_doc_patient FOREIGN KEY (patient_id) REFERENCES patient_registration(id) ON DELETE CASCADE +) ENGINE=InnoDB; + +-- ============================================================ +-- 4. Consent, Outbox, Audit & Admin Tables +-- ============================================================ + +CREATE TABLE IF NOT EXISTS consent_records ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + patient_id BIGINT UNSIGNED NOT NULL, + privacy_notice_version VARCHAR(32) NOT NULL, + lawful_basis VARCHAR(64) NOT NULL, + consented_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_consent_patient FOREIGN KEY (patient_id) REFERENCES patient_registration(id) ON DELETE CASCADE +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS outbox_events ( + id CHAR(36) NOT NULL PRIMARY KEY, + registration_id BIGINT UNSIGNED NOT NULL, + event_type ENUM('DUPLICATE_CHECK', 'HIS_CREATE', 'EMAIL_CONFIRMATION') NOT NULL, + status ENUM('PENDING', 'LOCKED', 'DONE', 'FAILED') NOT NULL DEFAULT 'PENDING', + attempts INT NOT NULL DEFAULT 0, + next_run_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + locked_until DATETIME NULL, + correlation_id CHAR(36) NOT NULL, + last_error VARCHAR(500) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + + INDEX idx_outbox_poll (status, next_run_at), + CONSTRAINT fk_outbox_reg FOREIGN KEY (registration_id) REFERENCES patient_registration(id) ON DELETE CASCADE +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS audit_logs ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + registration_id BIGINT UNSIGNED NULL, + actor VARCHAR(100) NOT NULL, + action VARCHAR(100) NOT NULL, + from_status VARCHAR(32) NULL, + to_status VARCHAR(32) NULL, + reason VARCHAR(255) NULL, + correlation_id CHAR(36) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + INDEX idx_audit_reg (registration_id, created_at) +) ENGINE=InnoDB; + +CREATE TABLE IF NOT EXISTS admin_users ( + id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + sso_subject VARCHAR(150) NOT NULL UNIQUE, + role ENUM('REG_STAFF', 'SUPERVISOR', 'SYS_ADMIN') NOT NULL, + is_active TINYINT(1) NOT NULL DEFAULT 1, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP +) ENGINE=InnoDB; + +-- ============================================================ +-- 5. Seed Data (Exact IDs from original HTML) +-- ============================================================ + +INSERT IGNORE INTO lookup_genders (id, name) VALUES +(1, 'Male'), (2, 'Female'), (3, 'Unisex'), (4, 'Other'), (5, 'Foetus'); + +INSERT IGNORE INTO lookup_titles (id, name, default_gender_id) VALUES +(1, 'Mr.', 1), (2, 'Miss.', 2), (3, 'Mrs.', 2), (4, 'Ms.', 2), +(5, 'Prof.', NULL), (6, 'Dr.', NULL), (7, 'Sr.', NULL), (8, 'B/O ', NULL), +(9, 'Col.', NULL), (10, 'MB/O ', 1), (11, 'FB/O ', 2), (12, 'M/s', 2), +(13, 'Smt.', 2), (14, 'Mast ', 1), (15, 'Fetus Of. ', 5), (16, 'Mx.', 4), +(17, 'Major ', NULL); + +INSERT IGNORE INTO lookup_relations (id, name) VALUES +(1, 'Self'), (2, 'Spouse'), (3, 'Brother'), (4, 'Sister'), (5, 'Friend'), +(6, 'Father'), (7, 'Mother'), (8, 'Relative'), (9, 'Son'), (10, 'Daughter'), +(11, 'Father in law'), (12, 'Grand father'), (13, 'Grand mother'), (14, 'Husband'), +(15, 'Mother in law'), (16, 'Wife'), (17, 'Uncle'), (18, 'Aunty'), +(19, 'Brother In Law'), (20, 'Sister In Law'), (21, 'Nephew'), (22, 'Niece'), +(23, 'Son In Law'), (24, 'Daughter In Law'), (25, 'Grand Daughter'), (26, 'Grand Son'), +(27, 'Major Brother'), (28, 'Major Sister'), (29, 'Major Son'), (30, 'Major Daughter'); + +INSERT IGNORE INTO lookup_doc_types (id, name) VALUES +(539, 'Driver''s License Frontside'), (540, 'Driver''s License Backside'), +(573, 'Passport Book'), (1570, 'Aadhar card'), (1571, 'Election card'), +(1572, 'Pan card'), (1573, 'Birth certificate'), (1576, 'Affidavit'), +(1578, 'Marriage certificate'), (1636, 'Visa Details'); + +INSERT IGNORE INTO lookup_countries (id, name) VALUES +(109, 'Afganisthan'), (1, 'Albania'), (2, 'Andorra'), (3, 'Argentina'), (4, 'Armenia'), +(100, 'Australia'), (5, 'Austria'), (6, 'Azerbaijan'), (7, 'Bahamas'), (95, 'Bahrain'), +(8, 'Bangladesh'), (9, 'Barbados'), (10, 'Belarus'), (11, 'Belgium'), (12, 'Bosnia & Herzegovina'), +(13, 'Brunei'), (14, 'Bulgaria'), (96, 'Burundi'), (15, 'Canada'), (16, 'Chile'), +(17, 'China'), (18, 'Colombia'), (104, 'Congo (East Africa)'), (19, 'Costa Rica'), (20, 'Croatia'), +(21, 'Cyprus'), (22, 'Czech Republic'), (23, 'Denmark'), (120, 'Djibouti'), (24, 'Dominica'), +(25, 'El Salvador'), (26, 'Estonia'), (27, 'Faeroe Islands'), (123, 'Fiji'), (28, 'Finland'), +(29, 'France'), (30, 'Germany'), (122, 'Ghana'), (31, 'Gibraltar'), (32, 'Greece'), +(33, 'Guatemala'), (35, 'Honduras'), (111, 'HongKong'), (36, 'Hungary'), (37, 'Iceland'), +(38, 'India'), (106, 'Indonesia'), (39, 'Iran'), (110, 'IRAQ'), (40, 'Ireland'), +(41, 'Israel'), (42, 'Italy'), (117, 'Jamaica'), (88, 'Japan'), (116, 'Kazakhstan'), +(91, 'Kenya'), (44, 'Kuwait'), (45, 'Latvia'), (46, 'Lesotho'), (47, 'Liechtenstein'), +(48, 'Lithuania'), (49, 'Luxembourg'), (50, 'Malaysia'), (89, 'Maldievs'), (51, 'Malta'), +(52, 'Mauritius'), (53, 'Mexico'), (54, 'Moldova'), (55, 'Monaco'), (112, 'Mozambia'), +(94, 'Nepal'), (56, 'Netherlands'), (57, 'New Zealand'), (108, 'Nigeria'), (59, 'Norway'), +(90, 'Oman'), (114, 'OTHER'), (60, 'Pakistan'), (61, 'Peru'), (115, 'PHILIPINES'), +(62, 'Poland'), (63, 'Portugal'), (64, 'Republic of Georgia'), (65, 'Republic of Macedonia'), +(66, 'Romania'), (67, 'Russia'), (105, 'Rwanda'), (68, 'San Marino'), (87, 'Saudi Arabia'), +(69, 'Serbia & Montenegro'), (113, 'SIERRA LEONEAN'), (70, 'Singapore'), (71, 'Slovakia'), +(72, 'Slovenia'), (118, 'Somalia'), (98, 'South Africa'), (73, 'Spain'), (93, 'SriLanka'), +(103, 'Sudan'), (74, 'Surinam'), (75, 'Svalbard'), (76, 'Sweden'), (77, 'Switzerland'), +(78, 'Syria'), (97, 'Tanzania'), (119, 'Thailand'), (79, 'Tunisia'), (121, 'Turkestan'), +(80, 'Turkey'), (81, 'U.S.A'), (101, 'Uganda'), (82, 'Ukraine'), (92, 'United Arab Emirates'), +(83, 'United Kingdom'), (84, 'Uruguay'), (85, 'Vatican City'), (102, 'Vietnam'), (107, 'Yemen'), +(86, 'Yugoslavia'), (99, 'Zambia'); + +INSERT IGNORE INTO lookup_states (id, country_id, name) VALUES +(32, 38, 'Andaman & Nicobar'), (1, 38, 'Andhra Pradesh'), (3, 38, 'Arunachal Pradesh'), +(2, 38, 'Assam'), (5, 38, 'Bihar'), (31, 38, 'Chandigarh'), (35, 38, 'Chattisgarh'), +(30, 38, 'Dadra & Nagar'), (29, 38, 'Daman & Diu'), (25, 38, 'Delhi'), (26, 38, 'Goa'), +(4, 38, 'Gujrat'), (6, 38, 'Haryana'), (7, 38, 'Himachal Pradesh'), (8, 38, 'Jammu & Kashmir'), +(34, 38, 'Jharkhand'), (9, 38, 'Karnataka'), (10, 38, 'Kerala'), (28, 38, 'Lakshdweep'), +(11, 38, 'Madhya Pradesh'), (12, 38, 'Maharashtra'), (13, 38, 'Manipur'), (14, 38, 'Meghalaya'), +(15, 38, 'Mizoram'), (16, 38, 'Nagaland'), (17, 38, 'Orissa'), (27, 38, 'Pondichery'), +(18, 38, 'Punjab'), (19, 38, 'Rajasthan'), (20, 38, 'Sikkim'), (21, 38, 'Tamil Nadu'), +(87, 38, 'Telangana'), (22, 38, 'Tripura'), (23, 38, 'Uttar Pradesh'), (33, 38, 'Uttaranchal'), +(24, 38, 'West Bengal'); + +INSERT IGNORE INTO lookup_cities (id, state_id, name) VALUES +(306, 12, 'Ahilya Nagar'), (290, 12, 'Akola'), (303, 12, 'Amravati'), +(287, 12, 'Bandra(Mumbai Suburban district)'), (307, 12, 'Beed'), (308, 12, 'Bhandara'), +(298, 12, 'Buldhana'), (291, 12, 'Chandrapur'), (311, 12, 'Dharashiv'), (299, 12, 'Dhule'), +(309, 12, 'Gadchiroli'), (319, 12, 'Gondia'), (320, 12, 'Hingoli'), (292, 12, 'Jalgaon'), +(310, 12, 'Jalna'), (300, 12, 'Kolhapur'), (296, 12, 'Latur'), (297, 12, 'Mumbai-City'), +(288, 12, 'Nagpur'), (301, 12, 'Nanded'), (317, 12, 'Nandurbar'), (304, 12, 'Nashik'), +(606, 12, 'Palghar'), (293, 12, 'Parbhani'), (289, 12, 'Pune'), (302, 12, 'Raigad'), +(312, 12, 'Ratnagiri'), (286, 12, 'Sambhaji Nagar'), (313, 12, 'Sangli'), (314, 12, 'Satara'), +(315, 12, 'Sindudurg'), (294, 12, 'Solapur'), (295, 12, 'Thane'), (305, 12, 'Wardha'), +(318, 12, 'Washim'), (316, 12, 'Yavatmal'), +(1001, 9, 'Bengaluru'), (1002, 9, 'Mysuru'), (1067, 9, 'Mangaluru'), (1068, 9, 'Hubballi-Dharwad'), (1069, 9, 'Belagavi'), (1070, 9, 'Kalaburagi'), (1071, 9, 'Davanagere'), (1072, 9, 'Ballari'), (1073, 9, 'Shivamogga'), (1074, 9, 'Udupi'), +(1003, 4, 'Ahmedabad'), (1004, 4, 'Surat'), (1031, 4, 'Vadodara'), (1032, 4, 'Rajkot'), (1033, 4, 'Bhavnagar'), (1034, 4, 'Jamnagar'), (1035, 4, 'Junagadh'), (1036, 4, 'Gandhinagar'), (1037, 4, 'Anand'), +(1005, 25, 'New Delhi'), (1162, 25, 'Central Delhi'), (1163, 25, 'North Delhi'), (1164, 25, 'South Delhi'), (1165, 25, 'East Delhi'), (1166, 25, 'West Delhi'), (1167, 25, 'Dwarka'), +(1006, 21, 'Chennai'), (1134, 21, 'Coimbatore'), (1135, 21, 'Madurai'), (1136, 21, 'Tiruchirappalli'), (1137, 21, 'Salem'), (1138, 21, 'Tirunelveli'), (1139, 21, 'Erode'), (1140, 21, 'Vellore'), (1141, 21, 'Thanjavur'), +(1007, 87, 'Hyderabad'), (1210, 87, 'Warangal'), (1211, 87, 'Nizamabad'), (1212, 87, 'Karimnagar'), (1213, 87, 'Khammam'), (1214, 87, 'Ramagundam'), +(1008, 24, 'Kolkata'), (1156, 24, 'Howrah'), (1157, 24, 'Durgapur'), (1158, 24, 'Asansol'), (1159, 24, 'Siliguri'), (1160, 24, 'Bardhaman'), (1161, 24, 'Darjeeling'), +(1009, 26, 'Panaji'), (1168, 26, 'Margao'), (1169, 26, 'Vasco da Gama'), (1170, 26, 'Mapusa'), (1171, 26, 'Ponda'), +(1010, 10, 'Kochi'), (1075, 10, 'Thiruvananthapuram'), (1076, 10, 'Kozhikode'), (1077, 10, 'Thrissur'), (1078, 10, 'Kollam'), (1079, 10, 'Kannur'), (1080, 10, 'Alappuzha'), (1081, 10, 'Palakkad'), (1082, 10, 'Kottayam'), +(1011, 1, 'Visakhapatnam'), (1012, 1, 'Vijayawada'), (1013, 1, 'Guntur'), (1014, 1, 'Nellore'), (1015, 1, 'Kurnool'), (1016, 1, 'Tirupati'), (1017, 1, 'Rajahmundry'), (1018, 1, 'Kakinada'), +(1019, 2, 'Guwahati'), (1020, 2, 'Silchar'), (1021, 2, 'Dibrugarh'), (1022, 2, 'Jorhat'), (1023, 2, 'Nagaon'), (1024, 2, 'Tinsukia'), (1025, 2, 'Tezpur'), +(1026, 3, 'Itanagar'), (1027, 3, 'Naharlagun'), (1028, 3, 'Pasighat'), (1029, 3, 'Tawang'), (1030, 3, 'Ziro'), +(1038, 5, 'Patna'), (1039, 5, 'Gaya'), (1040, 5, 'Bhagalpur'), (1041, 5, 'Muzaffarpur'), (1042, 5, 'Darbhanga'), (1043, 5, 'Purnia'), (1044, 5, 'Arrah'), (1045, 5, 'Begusarai'), +(1046, 6, 'Gurugram'), (1047, 6, 'Faridabad'), (1048, 6, 'Panipat'), (1049, 6, 'Ambala'), (1050, 6, 'Hisar'), (1051, 6, 'Karnal'), (1052, 6, 'Rohtak'), (1053, 6, 'Sonipat'), +(1054, 7, 'Shimla'), (1055, 7, 'Dharamshala'), (1056, 7, 'Mandi'), (1057, 7, 'Solan'), (1058, 7, 'Kullu'), (1059, 7, 'Bilaspur'), (1060, 7, 'Hamirpur'), +(1061, 8, 'Srinagar'), (1062, 8, 'Jammu'), (1063, 8, 'Anantnag'), (1064, 8, 'Baramulla'), (1065, 8, 'Udhampur'), (1066, 8, 'Kathua'), +(1083, 11, 'Indore'), (1084, 11, 'Bhopal'), (1085, 11, 'Jabalpur'), (1086, 11, 'Gwalior'), (1087, 11, 'Ujjain'), (1088, 11, 'Sagar'), (1089, 11, 'Rewa'), (1090, 11, 'Satna'), +(1091, 13, 'Imphal'), (1092, 13, 'Thoubal'), (1093, 13, 'Bishnupur'), (1094, 13, 'Churachandpur'), +(1095, 14, 'Shillong'), (1096, 14, 'Tura'), (1097, 14, 'Jowai'), (1098, 14, 'Nongpoh'), +(1099, 15, 'Aizawl'), (1100, 15, 'Lunglei'), (1101, 15, 'Champhai'), (1102, 15, 'Serchhip'), +(1103, 16, 'Kohima'), (1104, 16, 'Dimapur'), (1105, 16, 'Mokokchung'), (1106, 16, 'Tuensang'), +(1107, 17, 'Bhubaneswar'), (1108, 17, 'Cuttack'), (1109, 17, 'Rourkela'), (1110, 17, 'Berhampur'), (1111, 17, 'Sambalpur'), (1112, 17, 'Puri'), (1113, 17, 'Balasore'), +(1114, 18, 'Ludhiana'), (1115, 18, 'Amritsar'), (1116, 18, 'Jalandhar'), (1117, 18, 'Patiala'), (1118, 18, 'Bathinda'), (1119, 18, 'Mohali'), (1120, 18, 'Pathankot'), (1121, 18, 'Hoshiarpur'), +(1122, 19, 'Jaipur'), (1123, 19, 'Jodhpur'), (1124, 19, 'Udaipur'), (1125, 19, 'Kota'), (1126, 19, 'Ajmer'), (1127, 19, 'Bikaner'), (1128, 19, 'Alwar'), (1129, 19, 'Bhilwara'), +(1130, 20, 'Gangtok'), (1131, 20, 'Namchi'), (1132, 20, 'Gyalshing'), (1133, 20, 'Mangan'), +(1142, 22, 'Agartala'), (1143, 22, 'Udaipur'), (1144, 22, 'Dharmanagar'), (1145, 22, 'Kailashahar'), +(1146, 23, 'Lucknow'), (1147, 23, 'Kanpur'), (1148, 23, 'Ghaziabad'), (1149, 23, 'Agra'), (1150, 23, 'Varanasi'), (1151, 23, 'Meerut'), (1152, 23, 'Prayagraj'), (1153, 23, 'Noida'), (1154, 23, 'Bareilly'), (1155, 23, 'Gorakhpur'), +(1172, 27, 'Puducherry'), (1173, 27, 'Karaikal'), (1174, 27, 'Mahe'), (1175, 27, 'Yanam'), +(1176, 28, 'Kavaratti'), (1177, 28, 'Agatti'), (1178, 28, 'Minicoy'), (1179, 28, 'Amini'), +(1180, 29, 'Daman'), (1181, 29, 'Diu'), +(1182, 30, 'Silvassa'), (1183, 30, 'Amli'), (1184, 30, 'Khanvel'), +(1185, 31, 'Chandigarh'), +(1186, 32, 'Port Blair'), (1187, 32, 'Diglipur'), (1188, 32, 'Mayabunder'), (1189, 32, 'Car Nicobar'), +(1190, 33, 'Dehradun'), (1191, 33, 'Haridwar'), (1192, 33, 'Roorkee'), (1193, 33, 'Haldwani'), (1194, 33, 'Nainital'), (1195, 33, 'Rishikesh'), (1196, 33, 'Rudrapur'), +(1197, 34, 'Ranchi'), (1198, 34, 'Jamshedpur'), (1199, 34, 'Dhanbad'), (1200, 34, 'Bokaro'), (1201, 34, 'Deoghar'), (1202, 34, 'Hazaribagh'), +(1203, 35, 'Raipur'), (1204, 35, 'Bhilai'), (1205, 35, 'Bilaspur'), (1206, 35, 'Korba'), (1207, 35, 'Durg'), (1208, 35, 'Rajnandgaon'), (1209, 35, 'Jagdalpur'); diff --git a/static/calender-touch/jquery-1.10.2.js b/static/calender-touch/jquery-1.10.2.js new file mode 100644 index 0000000..f7bf8c6 --- /dev/null +++ b/static/calender-touch/jquery-1.10.2.js @@ -0,0 +1,70 @@ +/* Minimal DOM helper compatible with the registration form's jQuery usage */ +(function(global) { + function selectElements(sel) { + if (!sel) return []; + if (typeof sel === "function") { + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", sel); + } else { + sel(); + } + return []; + } + if (typeof sel === "string") { + return Array.prototype.slice.call(document.querySelectorAll(sel)); + } + if (sel === document || sel === window || sel.nodeType) { + return [sel]; + } + return []; + } + + function MiniQuery(sel) { + if (!(this instanceof MiniQuery)) return new MiniQuery(sel); + this.els = selectElements(sel); + } + + MiniQuery.prototype.ready = function(fn) { + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", fn); + } else { + fn(); + } + return this; + }; + MiniQuery.prototype.show = function() { + this.els.forEach(function(el) { el.style.display = ""; }); + return this; + }; + MiniQuery.prototype.hide = function() { + this.els.forEach(function(el) { el.style.display = "none"; }); + return this; + }; + MiniQuery.prototype.html = function(val) { + if (val === undefined) return this.els[0] ? this.els[0].innerHTML : ""; + this.els.forEach(function(el) { el.innerHTML = val; }); + return this; + }; + MiniQuery.prototype.append = function(htmlStr) { + this.els.forEach(function(el) { el.insertAdjacentHTML("beforeend", htmlStr); }); + return this; + }; + MiniQuery.prototype.bind = function(events, fn) { + var evList = events.split(/\s+/); + this.els.forEach(function(el) { + evList.forEach(function(ev) { el.addEventListener(ev, fn); }); + }); + return this; + }; + MiniQuery.prototype.keydown = function(fn) { + return this.bind("keydown", fn); + }; + + MiniQuery.noConflict = function() { + return MiniQuery; + }; + MiniQuery.fn = MiniQuery.prototype; + + global.$ = MiniQuery; + global.jQuery = MiniQuery; +})(window); diff --git a/static/calender-touch/jquery-ui.css b/static/calender-touch/jquery-ui.css new file mode 100644 index 0000000..7f01310 --- /dev/null +++ b/static/calender-touch/jquery-ui.css @@ -0,0 +1,32 @@ +.dmh-datepicker-popup { + position: absolute; + z-index: 9999; + background: #fff; + border: 1px solid #ccc; + border-radius: 4px; + padding: 8px; + box-shadow: 0 4px 12px rgba(0,0,0,0.15); + width: 240px; +} +.dmh-dp-header { + display: flex; + justify-content: space-between; + margin-bottom: 6px; + gap: 6px; +} +.dmh-dp-header select { flex: 1; padding: 2px; } +.dmh-dp-grid { + display: grid; + grid-template-columns: repeat(7, 1fr); + gap: 3px; +} +.dmh-dp-grid button { + border: 1px solid #e0e0e0; + background: #f8f9fa; + padding: 4px 0; + cursor: pointer; + border-radius: 2px; + font-size: 12px; +} +.dmh-dp-grid button:hover:not(:disabled) { background: #007bff; color: #fff; } +.dmh-dp-grid button:disabled { opacity: 0.4; cursor: not-allowed; } diff --git a/static/calender-touch/jquery-ui.js b/static/calender-touch/jquery-ui.js new file mode 100644 index 0000000..c4fb45f --- /dev/null +++ b/static/calender-touch/jquery-ui.js @@ -0,0 +1,100 @@ +/* Lightweight dd/mm/yyyy datepicker compatible with $(selector).datepicker(opts) */ +(function($) { + if (!$ || !$.fn) return; + + function pad(n) { return n < 10 ? "0" + n : "" + n; } + + $.fn.datepicker = function(opts) { + opts = opts || {}; + this.els.forEach(function(input) { + var popup = null; + + function closePopup() { + if (popup && popup.parentNode) { + popup.parentNode.removeChild(popup); + popup = null; + } + } + + function renderCalendar(year, month) { + closePopup(); + popup = document.createElement("div"); + popup.className = "dmh-datepicker-popup"; + var rect = input.getBoundingClientRect(); + popup.style.top = (window.scrollY + rect.bottom + 2) + "px"; + popup.style.left = (window.scrollX + rect.left) + "px"; + + var header = document.createElement("div"); + header.className = "dmh-dp-header"; + + var monthSel = document.createElement("select"); + var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; + months.forEach(function(m, idx) { + var o = document.createElement("option"); + o.value = idx; + o.textContent = m; + if (idx === month) o.selected = true; + monthSel.appendChild(o); + }); + + var yearSel = document.createElement("select"); + var curYear = new Date().getFullYear(); + for (var y = curYear; y >= curYear - 100; y--) { + var oy = document.createElement("option"); + oy.value = y; + oy.textContent = y; + if (y === year) oy.selected = true; + yearSel.appendChild(oy); + } + + monthSel.onchange = function() { renderCalendar(parseInt(yearSel.value, 10), parseInt(monthSel.value, 10)); }; + yearSel.onchange = function() { renderCalendar(parseInt(yearSel.value, 10), parseInt(monthSel.value, 10)); }; + header.appendChild(monthSel); + header.appendChild(yearSel); + popup.appendChild(header); + + var grid = document.createElement("div"); + grid.className = "dmh-dp-grid"; + var daysInMonth = new Date(year, month + 1, 0).getDate(); + var today = new Date(); + today.setHours(0, 0, 0, 0); + + for (var d = 1; d <= daysInMonth; d++) { + (function(dayNum) { + var btn = document.createElement("button"); + btn.type = "button"; + btn.textContent = dayNum; + var candidate = new Date(year, month, dayNum); + if (opts.maxDate === "0" && candidate > today) { + btn.disabled = true; + } + btn.onclick = function() { + var formatted = pad(dayNum) + "/" + pad(month + 1) + "/" + year; + input.value = formatted; + closePopup(); + if (typeof opts.onSelect === "function") { + opts.onSelect(formatted); + } + }; + grid.appendChild(btn); + })(d); + } + popup.appendChild(grid); + document.body.appendChild(popup); + } + + input.addEventListener("click", function() { + if (input.readOnly) return; + var now = new Date(); + renderCalendar(now.getFullYear(), now.getMonth()); + }); + + document.addEventListener("click", function(ev) { + if (popup && ev.target !== input && !popup.contains(ev.target)) { + closePopup(); + } + }); + }); + return this; + }; +})(window.$); diff --git a/static/calender-touch/style.css b/static/calender-touch/style.css new file mode 100644 index 0000000..c0c8e9e --- /dev/null +++ b/static/calender-touch/style.css @@ -0,0 +1 @@ +/* Calendar touch style placeholder */ diff --git a/static/css/bootstrap.min.css b/static/css/bootstrap.min.css new file mode 100644 index 0000000..8e7a006 --- /dev/null +++ b/static/css/bootstrap.min.css @@ -0,0 +1,45 @@ +*, *::before, *::after { box-sizing: border-box; } +body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; font-size: 1rem; line-height: 1.5; color: #212529; } +.bg-light { background-color: #f8f9fa !important; } +.container { width: 100%; max-width: 1140px; padding: 0 15px; margin: 0 auto; } +.py-5 { padding-top: 3rem !important; padding-bottom: 3rem !important; } +.pt-5 { padding-top: 3rem !important; } +.my-5 { margin-top: 3rem !important; margin-bottom: 3rem !important; } +.mb-1 { margin-bottom: .25rem !important; } +.mb-3 { margin-bottom: 1rem !important; } +.mb-4 { margin-bottom: 1.5rem !important; } +.mt-4 { margin-top: 1.5rem !important; } +.mx-auto { margin-left: auto !important; margin-right: auto !important; } +.d-block { display: block !important; } +.w-100 { width: 100% !important; } +.text-center { text-align: center !important; } +.text-muted { color: #6c757d !important; } +.text-small { font-size: 80%; } +.row { display: flex; flex-wrap: wrap; margin: 0 -15px; } +[class*="col-md-"] { position: relative; width: 100%; padding: 0 15px; } +@media (min-width: 768px) { + .col-md-2 { flex: 0 0 16.666667%; max-width: 16.666667%; } + .col-md-3 { flex: 0 0 25%; max-width: 25%; } + .col-md-6 { flex: 0 0 50%; max-width: 50%; } + .col-md-10 { flex: 0 0 83.333333%; max-width: 83.333333%; } + .col-md-12 { flex: 0 0 100%; max-width: 100%; } +} +h1 { font-size: 2.5rem; margin-bottom: .5rem; font-weight: 500; } +h4 { font-size: 1.5rem; margin-bottom: .5rem; font-weight: 500; } +label { display: inline-block; margin-bottom: .5rem; } +.form-group { margin-bottom: 1rem; } +.form-text { display: block; margin-top: .25rem; } +.form-control, .custom-select { + display: block; width: 100%; height: calc(1.5em + .75rem + 2px); + padding: .375rem .75rem; font-size: 1rem; line-height: 1.5; color: #495057; + background-color: #fff; border: 1px solid #ced4da; border-radius: .25rem; +} +.form-control:focus, .custom-select:focus { border-color: #80bdff; outline: 0; box-shadow: 0 0 0 .2rem rgba(0,123,255,.25); } +.btn { display: inline-block; font-weight: 400; text-align: center; border: 1px solid transparent; padding: .375rem .75rem; font-size: 1rem; line-height: 1.5; border-radius: .25rem; cursor: pointer; text-decoration: none; } +.btn-lg { padding: .5rem 1rem; font-size: 1.25rem; border-radius: .3rem; } +.btn-block { display: block; width: 100%; } +.btn-success { color: #fff; background-color: #28a745; border-color: #28a745; } +.btn-primary { color: #fff; background-color: #007bff; border-color: #007bff; } +.btn-secondary { color: #fff; background-color: #6c757d; border-color: #6c757d; } +.alert { padding: .75rem 1.25rem; margin-bottom: 1rem; border: 1px solid transparent; border-radius: .25rem; } +.alert-danger { color: #721c24; background-color: #f8d7da; border-color: #f5c6cb; } diff --git a/static/images/no_image.png b/static/images/no_image.png new file mode 100644 index 0000000000000000000000000000000000000000..0b864fe8f9fe3c90861832575738cd9d737c5f11 GIT binary patch literal 1859 zcmaJ?X*3&%7FKI0rPU$IjERV9f{CSQg}z2m(L|9%wIx!eB_lJol(7uLAkv!gETgEg zwyAAui+wA#3$X`dUs6RSwQG&{e!Md?Ki-df?>YC}bI-lsz32PlZegutq%KGa2?@zq z-$2=)M9PUp0)$VzW|J3QNJv7;8g(5Pn6aLD_m;dPFkChr_0}?mE(^`Mw-{yp~D>Yjj_tE1L-gctL4YsMN#i8N zUx|v~BO{gyFJIVyTQ(Oo@)TMbj0<$Q#CHQM8(^>mnv??qeojz zl?rzZeoc0PoPPb<;>{JUOZc*ZIvPhR*%GqWt4&}=(TfwmAZOhP$x73@i~%;OKkIhtvU~PE1=fx}R+Cw;we7GvVcJxqw}B=fu7Ml85b$tA{0U zDATdaUMUgVV8lSz;>*s*TS`Kp%yhf{Mo05Prs+LVyxpH>U)2F4XK!o@gPtlHNtjdHU&!^O`kqvD_4w~nY-sUtNcXMAiHwVr;RH)6`6Xk%IGYZ`g%1(bf5vPh>UO)7IPg>-+ipU?+ zH{dP$dK`3rCQFOd)6H7+fF+}mvG&ZV#D9m*-A|itj5u{FGxIS3ByOHC!(T$~4-5>< z4h$%h6a8x~k)7>j{9cBC+D%Ji@QHg9h6sG?5wG)ggNQZ>h9_q zzV&>NLae+qQZ$wzR_0PlD2(EJgxVC{SzlNXuxS!19n*CWKMK<2OdoGdC0ygafir@a zVfsTu{VC5)j5mf;1_$lt=SVDcF`Zdd|Lpk=mQ23OuQiJ1*B*$|TE1UD*tSaeiZydI zgwShEO(nj1SvqDK#$T*k=m3CJI+m6c`S^*6v}_QlZ3J&=X$hAeIzYffQ}?L>0Wm*e z5w{&3cgx%xsV4pDMr_(v;P?zXMw$4?Fnx3PkK^T4QrN@@&)+6Ri^r=`K3}00;D+YB zYg;#=Vi1h<;$%b`&oe(?9#%kgc*i5M5y3kQIXyW1mVd$CI?M2vOR@Mudc2L+kC&!v zw^N&%RFAJ95JgTiWz_X&i5x%h!fU6XC8$jKWZc6+uv+Vq@5F}>a1bh=&fDB%!!&W4 z=T$nqZ)d4|`Q>GN$6j^ye0hFHqnTRL@Q4x0ln6tZnl{we6GX*Fy^O0Hfs-$Z?L$JtmKz8zS^iSRm ziJw~`0;Np}-g`ImM`D=bi+;ZZ?MEL9WZzF5TAS1QDc>~896N+DBdb>@u`~-aJ9$+{ zpBi5b#|zmxJ3C8@`E-hWD5rWH&V+r7t4`<8_u4Dlf6u8sVeNA9i zMaA2vFM5i&#sAxONoTU<-rknd6kNb)%;ei#-tvLuulV_u6?lOe%|25P4+Z;dQg${N z46b^z-?i4lSby-ITl1#Mk%CoNhB+(uI<}fGs6Nt>`ahiiSN?g4K9Loql)Mk1$DvW) zF3#{p#E2*Fwa73bpfesESm6TGhW&ipj!xZv3g)U0EfI-9dUG>k!xJasC}eGcMU^03 GBmV>|sf@Y+ literal 0 HcmV?d00001 diff --git a/static/images/refresh.png b/static/images/refresh.png new file mode 100644 index 0000000000000000000000000000000000000000..ffffddf28d12d7e518451ba8ba48fef8c76f8314 GIT binary patch literal 216 zcmV;}04M*6P)P000>X1^@s6#OZ}&0001=Nklw8*A{8P)x_S?v}{B@_>{avkU|>g(Tk_=bUOF-Ft>{WpVmD8FL*(Ua} zm9U%ySsgtc|BDhTc~{F-w&2Y!?D4LlE)2=bv^U;D2Ce(89|^1dyGT5-PshL9U};TI S<9(I@0000"; + ajax3.requestFile = 'p_getState.php?countryId='+country+'&stateId='+state+'&other_state='+other_state+'&cityId='+city+'&other_city='+other_city; + ajax3.onCompletion = p_showState; + ajax3.runAJAX(); + p_getCity(country,state,other_state,city,other_city); + } + function p_showState() + { + document.getElementById("p_statediv").innerHTML=ajax3.response; + } + + var ajax4 = new sack(); + function p_getCity(country,state,other_state,city,other_city) + { + ajax4.requestFile = 'p_getCity.php?countryId='+country+'&stateId='+state+'&other_state='+other_state+'&cityId='+city+'&other_city='+other_city; + ajax4.onCompletion = p_showCity; + ajax4.runAJAX(); + } + function p_showCity() + { + document.getElementById("p_citydiv").innerHTML=ajax4.response + } + + function setDOB() + { + var age = document.getElementById("age").value; + var e = document.getElementById("ageUnit"); + var ageUnit = e.options[e.selectedIndex].value; + if(ageUnit == 0) { + ageUnit = "years"; + } else if(ageUnit == 1) { + ageUnit = "months"; + } else if(ageUnit == 2) { + ageUnit = "days"; + } else if(ageUnit == 3) { + ageUnit = "weeks"; + } + age= parseInt(age); + + if(age <= 0 || isNaN(age) ) + { + $.alert("Patient age should be greater than zero."); + document.getElementById("age").value = ''; + return false; + } + if( age >= 100 && ageUnit == "years" ) + { + var confirmStatus = confirm("Patient's age is more than 100 Years. Do you want to proceed?"); + if(confirmStatus == false) + { + document.getElementById("age").value = ''; + return false; + } + } + + var ajaxDOB = new sack(); + ajaxDOB.requestFile = 'getDOB.php?age='+age+'&ageUnit='+ageUnit; + ajaxDOB.onCompletion = showDOB; + ajaxDOB.runAJAX(); + function showDOB() + { + document.getElementById("dob").value=ajaxDOB.response; + document.getElementById("approx_dob").value = 1; + } + } + + function validateForm(e, docum) + { + if(docum.title.value.trim() == '') + { + //alert("Please Select Title"); + $.alert('Please Select Title'); + docum.title.focus(); + return false; + } + if(docum.lname.value.trim() == '') + { + $.alert("Please Enter Last Name"); + docum.lname.select(); + docum.lname.focus(); + return false; + } + if(docum.fname.value.trim() == '') + { + $.alert("Please Enter First Name"); + docum.fname.select(); + docum.fname.focus(); + return false; + } + if( docum.pan_no.value.trim() != '' ) + { + var panVal = docum.pan_no.value.trim(); + var regpan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/; + if(regpan.test(panVal)) + { + //return true; + } else { + $.alert("Enter Valid Pan Card Number"); + return false; + } + } + + if(docum.aadhar_no.value.trim() != '') + { + if( isNaN(docum.aadhar_no.value.trim()) ) + { + $.alert("Please Enter Numbers In Aadhar Number"); + docum.aadhar_no.select(); + docum.aadhar_no.focus(); + return false; + } else { + var adhr = docum.aadhar_no.value.trim(); + if(adhr.length < 12) + { + $.alert("Please Enter 12 Digit Aadhar Number"); + docum.aadhar_no.select(); + docum.aadhar_no.focus(); + return false; + } + } + } + + if( docum.dob.value.trim() == '' || docum.age.value.trim() == '' ) + { + $.alert("Please Enter Date Of Birth Or Age."); + return false; + } + + if( docum.gender.value.trim() == 2 ) + { + if( docum.marital_status.value.trim() == '' ) + { + $.alert("Please Choose Marital Status."); + return false; + } + + if( docum.marital_status.value.trim() != 'Single' ) + { + if( docum.dom.value.trim() == '' ) + { + $.alert("Please Enter Date Of Marriage."); + return false; + } + if( docum.bmname.value.trim() == '' ) + { + $.alert("Please Enter Before Marriage Name."); + return false; + } + } + } + + if(docum.patient_income.value.trim() != '') + { + if( isNaN(docum.patient_income.value.trim()) ) + { + $.alert("Please Enter Numbers In Monthly Income"); + docum.patient_income.select(); + docum.patient_income.focus(); + return false; + } + } + + if(docum.address1.value.trim() == '') + { + $.alert("Please Enter House Name/Appt.No Details"); + docum.address1.select(); + docum.address1.focus(); + return false; + } + + if(docum.country.value.trim() == '') + { + $.alert("Please Select Country"); + docum.country.focus(); + return false; + } + + var stateField = docum.state || docum.other_state; + if(!stateField || stateField.value.trim() == '') + { + $.alert("Please Select State"); + if(stateField) stateField.focus(); + return false; + } + + var cityField = docum.city || docum.other_city; + if(!cityField || cityField.value.trim() == '') + { + $.alert("Please Select City"); + if(cityField) cityField.focus(); + return false; + } + + if(docum.pincode.value.trim() != '') + { + if( isNaN(docum.pincode.value.trim()) ) + { + $.alert("Please Enter Numbers In Pin Number"); + docum.pincode.select(); + docum.pincode.focus(); + return false; + } + } + + if(docum.cell_phone.value.trim() != '') + { + if( isNaN(docum.cell_phone.value.trim()) ) + { + $.alert("Please Enter Numbers In Cell Number"); + docum.cell_phone.select(); + docum.cell_phone.focus(); + return false; + } else { + var adhr1 = docum.cell_phone.value.trim(); + if(adhr1.length != 10) + { + $.alert("Please Enter 10 Digit Cell Number"); + docum.cell_phone.select(); + docum.cell_phone.focus(); + return false; + } + } + } + + if(docum.email.value.trim() != '') + { + if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(docum.email.value.trim())) + { + + } else { + $.alert("You have entered an invalid email address!") + return false; + } + } + + if(docum.emg_person.value.trim() == '' || docum.emg_person1.value.trim() == '') + { + $.alert("Please Enter Emergency Contact Person"); + docum.emg_person.select(); + docum.emg_person.focus(); + return false; + } + + if(docum.relation.value.trim() == '') + { + $.alert("Please Select Relation With Patient"); + docum.relation.focus(); + return false; + } + + if(docum.emg_no.value.trim() == '') + { + $.alert("Please Enter Emergency Contact Number"); + docum.emg_no.select(); + docum.emg_no.focus(); + return false; + } + + // --- + + if(docum.re_persone.value.trim() == '') + { + $.alert("Please Enter Name Of Representative"); + docum.re_persone.select(); + docum.re_persone.focus(); + return false; + } + + if(docum.re_relation.value.trim() == '') + { + $.alert("Please Select Representative Relation To Patient"); + docum.re_relation.focus(); + return false; + } + + if(docum.id_file.value.trim() == '') + { + $.alert("Please Upload Identity Proof"); + docum.id_file.focus(); + return false; + } else + { + var fileInput = document.getElementById('id_file'); + var filePath = fileInput.value; + var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif|\.pdf)$/i; + if (!allowedExtensions.exec(filePath)) { + alert('Invalid file type'); + fileInput.value = ''; + return false; + } + } + + if(document.getElementById("txtcaptcha").value.trim()=="") + { + document.getElementById("txtcaptcha").focus(); + $.alert("Enter captcha text."); + return false; + } + var mainCaptchaEl = document.getElementById('mainCaptcha'); + if(mainCaptchaEl) + { + var string1 = mainCaptchaEl.value.split(' ').join(''); + var string2 = document.getElementById('txtcaptcha').value.split(' ').join(''); + if(string1 !== string2) + { + document.getElementById('txtcaptcha').value = ''; + $.alert("Invalid Captcha Text!"); + return false; + } + } + + $.confirm('Do you want to save the details..?',function(a){ if( a == true ) { + //document.getElementById("SaveDB").value = 'Save'; + document.getElementById("vm").focus(); + document.getElementById("vm").select(); + document.getElementById("loader").style.display = "block"; + document.getElementById("SaveData").style.display = "none"; + document.getElementById("form").submit(); + } } ); + /*if( !confirm('Do you want to save the details..?') ) + { + return false; + }*/ + document.getElementById("vm").focus(); + document.getElementById("vm").select(); + return false; + } + + function selGender(val) + { + if(val == 1 || val == 10 || val == 14) + document.getElementById("gender").selectedIndex = 1; + else if( val == 16 ) + document.getElementById("gender").selectedIndex = 4; + else if( val == 15 ) + document.getElementById("gender").selectedIndex = 5; + else if( val == 2 || val == 3 || val == 4 || val == 11 || val == 12 || val == 13 ) + document.getElementById("gender").selectedIndex = 2; + else + document.getElementById("gender").selectedIndex = 0; + + if( val == 2 || val == 3 || val == 4 || val == 11 || val == 12 || val == 13 ) + $("#divMarried1,#divMarried2").show(); + else + $("#divMarried1,#divMarried2").hide(); + } + + //alert(getAge('15/05/2019')); + function getAge(dateString) + { + document.getElementById("approx_dob").value = 0; + var now = new Date(); + var today = new Date(now.getYear(),now.getMonth(),now.getDate()); + + var yearNow = now.getYear(); + var monthNow = now.getMonth(); + var dateNow = now.getDate(); + + var tempDate = dateString.split("/"); + var y = tempDate[2]; //dateString.substring(6,10); + var m = tempDate[1]-1; //dateString.substring(0,2)-1; + var d = tempDate[0]; //dateString.substring(3,5); + + var dob = new Date( y, m, d ); + + var yearDob = dob.getYear(); + var monthDob = dob.getMonth(); + var dateDob = dob.getDate(); + var age = {}; + var ageString = ""; + var yearString = ""; + var monthString = ""; + var dayString = ""; + + + yearAge = yearNow - yearDob; + + if (monthNow >= monthDob) + var monthAge = monthNow - monthDob; + else { + yearAge--; + var monthAge = 12 + monthNow -monthDob; + } + + if (dateNow >= dateDob) + var dateAge = dateNow - dateDob; + else { + monthAge--; + var dateAge = 31 + dateNow - dateDob; + + if (monthAge < 0) { + monthAge = 11; + yearAge--; + } + } + + age = { years:yearAge, months:monthAge, days:dateAge }; + + if ( age.years > 1 ) yearString = " years"; + else yearString = " year"; + if ( age.months> 1 ) monthString = " months"; + else monthString = " month"; + if ( age.days > 1 ) dayString = " days"; + else dayString = " day"; + + if ( (age.years > 0) && (age.months > 0) && (age.days > 0) ) + { document.getElementById('age').value = age.years; document.getElementById("ageUnit").selectedIndex = 0; } + else if ( (age.years == 0) && (age.months == 0) && (age.days > 0) ) + { document.getElementById('age').value = age.days; document.getElementById("ageUnit").selectedIndex = 2; } + else if ( (age.years > 0) && (age.months == 0) && (age.days == 0) ) + { document.getElementById('age').value = age.years; document.getElementById("ageUnit").selectedIndex = 0; } + else if ( (age.years > 0) && (age.months > 0) && (age.days == 0) ) + { document.getElementById('age').value = age.years; document.getElementById("ageUnit").selectedIndex = 0; } + else if ( (age.years == 0) && (age.months > 0) && (age.days > 0) ) + { document.getElementById('age').value = age.months; document.getElementById("ageUnit").selectedIndex = 1; } + else if ( (age.years > 0) && (age.months == 0) && (age.days > 0) ) + { document.getElementById('age').value = age.years; document.getElementById("ageUnit").selectedIndex = 0; } + else if ( (age.years == 0) && (age.months > 0) && (age.days == 0) ) + { document.getElementById('age').value = age.months; document.getElementById("ageUnit").selectedIndex = 1; } + else ageString = "Oops! Could not calculate age!"; + + return ageString; + } + + function FillBilling(f) + { + if(f.copy.checked == true) + { + f.p_address1.value = f.address1.value; + f.p_address2.value = f.address2.value; + f.p_post_office.value = f.post_office.value; + f.p_pincode.value = f.pincode.value; + f.p_phone.value = f.phone.value; + + $('#p_country').html($('#country').html()); + f.p_country.value = f.country.value; + if(document.getElementById("country").value == 38) + { + document.getElementById("p_statediv").innerHTML = ""; + document.getElementById("p_citydiv").innerHTML = ""; + $('#p_state').html($('#state').html()); + $('#p_city').html($('#city').html()); + f.p_state.value = f.state.value; + f.p_city.value = f.city.value; + } else + { + p_getState(f.country.value, '', f.other_state.value, '', f.other_city.value); + } + } else { + f.p_address1.value = ''; + f.p_address2.value = ''; + f.p_post_office.value = ''; + f.p_pincode.value = ''; + f.p_phone.value = ''; + f.p_country.value = '38'; + p_getState('38', '', '', '', ''); + } + } diff --git a/static/logo.png b/static/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..3b6fd68018c5be1633ca6d8a0d6e9daa06f5450c GIT binary patch literal 2990 zcmV;f3sLlmP)R@XCNN!mcm!kzg)1{|Zw`G9xJkll1lE^%Mmz zC+Vj_4r8UVV(m%ofYKm{uxn4DFMCYaUF5YX-Xx`9a{Lvun@gc{=@%tk#<>NIDg~|A zP;6s5PqIV)2|lO)0Z2JTESO~KS;v`3yBmBAmVitU?ZnfH+1*hzTXYROp%Pdt`G309 zy&f`M5xV@JhoQyhv9n?>XKZSMVdOQ=Yejxe8!>-;Mx`(V98N+zhXOj$mSf4)0Byl^ z#>)v(fi{$Mx#|unRYai2ZAJV93NBwLbDT-+h&LH8$M5a*SJ973#O#1@33|2hw~w|Q z=nQ5e>jkO<_8D4nsIXuR^bETUhmElLCAbBAi{(}i3i#nD0MZj#zf_Y-8A z%qceCWc(}`h|lx1t&p9eT?3*~Yht1&%>>Rg_{U==FIsdfDjc zj5k2GiSZHIXtaug$0FPZJmRo>7T#T89JXVC>j?@r_%4smB;>lod%*q^<7x2AIc%-55W5@>Jd5 z=%y%;S7*Eto!aEs+=xtMEVO$WXHefNhrkW#?1rgDbVcwtF{T~HJykgr=;`v?0$(o^ z4CxgRHs$DM<8vhfJqru%DR?FEyM=xh{d{uWR`7J0uFGe{-r_qAjaPtRw~}@W%XBn+ zJ;@5KuB5qQOc~_eiM0xyLSj4{%+VRv>*HRPz|gy*ff!&fe_^AuqM~3pjxH}fZY?^! z2|NyrL1`B_#}4dA>k;zObiM#j0*~M|BQafidKRz4I33*R2_tNfm4Lkn8=bk{nRE)Fn6tEfGLjpm^D&udU+kha8XqDQdR~J+w zfk&`Cr_2Btp8$Gk!!)1Ecn!M01CQcoEEtMp9fc2}-G-vB3SFipn7zsP?n*IJ(Ely+ zP`U+%-Y=|1uJ#P0lS8m=1X80=tpNlgwoGB;B~YO7AngIL6bQ*50lR>n1C*5zusdFW zv*fY_<1^&*5-~IBZzYHOL4S&QfN>C^qgRuKFpq&gARc+kZ6$$PU>tM|k;Fy$R0(@(7=LGQ1U!dx(7(SVFNi;lBhgh{#uOVzSBaS_GNsd`cUa z927sovEJ!S$4T%rtLy%OfM@YC09id+y#W}7jb4u#CZF(qfY}_uBxKS)W<>UcMj@9H z*q6g@wLst1i7Z{)g<<3N|>4vv|rI9vys;Ak)Wu{hOP*1M*$@Luq2QoJFK z?&!!-9A^v@(G{#?r-WUPBOB#&y@GLm4nsZTO=QpN?Vd{Wbi;Trj`cFs2fb{M7h%H= z>IXJ}WeH*_`f4|yHZ6kda8~}Clt~DVVABTZvSt{cyn+L26r`v9AJOXUZoyGiX1FQx zp78X&6x}G~IQ3ZxdMES?+C*?S`i=403HVB!T;64Z2BJTK{PbSAEqz}URB%KK*VSdb zI-)F?S$HiEX8RuPNAn!;O%$$6Is=2KkC(`TC}zPp+y`=kEdCD%Z7IzBmW|t&&zSFSBa-4;w)|J<*Wk}Q z=r~z*T(@0BM}C;bh~(y0k=a=@Y>ys`ZMSX!Oy5@ZTE`Clnpq&s8(OEZqI2aSy}C5-nQ8XLpdZXTxI~(}hRZ`-r9Q*l7Hb6GKhkC&v({K%_Gr4Uxm`gRQ?&(fFfS1^e^x z^=fe}B$mMCUT|X7qFr1tJK>6^;u*f8rO!wNoT)docz{DVS_6uN%od@f0}Y9Od9o=!fvcqg=4KsDfV+ zsW?xh#R8GxOGO?SEmHHih_8YdiB$WmNXI22Bk=v{%W>i~avao%tvPku) zhDjFqE_j?sdUKI?8d*EMx-r#C8)Njetf*p4TADF|t4mml6x+L{$cBd2_Wd@xoRvkP z?^mlbF3T%gW;x6*6%1bm|B>0r5P6G2Z;qD)*OwrluZnc(Xw0+<#^{%GG0idLbP!YJ zl7+;G?Std&YG!tHWn*+wVk;vpDRR{)TBXND>ZXf4=l9}DwYp%`G-Yt&dFJ4%Q%6Mq zn@;@dmzu+gCASFdo8oN zNu+)k5l-f+9gOxOqh?xrPmZ-4j$8Y=+8)Jrm$h40T03l&$WQS9TCi2>M*jr>0RR8k kpFJl4000I_L_t&o0MC^OV07*qoM6N<$f-Q)Y?f?J) literal 0 HcmV?d00001 diff --git a/templates/error.html b/templates/error.html new file mode 100644 index 0000000..6a6005b --- /dev/null +++ b/templates/error.html @@ -0,0 +1,27 @@ + + + + + + Validation Error | Deenanath Mangeshkar Hospital + + + +
+
+ DMH Logo +

Patient Registration Form

+
+
+

Please fix the following errors:

+
    + {% for err in errors %} +
  • {{ err }}
  • + {% endfor %} +
+
+ + Start Over +
+ + diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..b4f7f3b --- /dev/null +++ b/templates/index.html @@ -0,0 +1,797 @@ + +New Patient Registration Form | Deenanath Mangeshkar Hospital + + + + + + + + + + + + + + + + +Registration Form + + + + +
+
+

Patient Registration Form

+ +
+
+ +
+
+
+
+
+ + This facility is to be used only by patient coming first time to this hospital.
+

Patient Particulars

+
+
+ + + +
+
+
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+
+
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ +   + + +
+
+ + + +
+ +
+ + +
+
+ +

Local Address

+ +
+
+ + +
+
+ + +
+
+ + + +
+
+ +
+
+
+ +
+
+
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + + Confirmation email will be send on this email id +
+
+    Copy to Permanent Address +
+

Permanent Address

+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ +
+
+ +
+
+
+ +
+
+
+ +
+
+ + +
+
+ + +
+
+ +

Emergency Contact

+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+
+
* + + CAPTCHA code + Refresh image + +
+
+ + +
+ +
+ +
+
+
+ + + +
+
+ +
+
+
+
+
+ +
+

© 2020-2021 Deenanath Mangeshkar Hospital

+

227

+
+ + + + + +
+ + +
diff --git a/templates/success.html b/templates/success.html new file mode 100644 index 0000000..58b64c2 --- /dev/null +++ b/templates/success.html @@ -0,0 +1,32 @@ + + + + + + New Patient Registration Form | Deenanath Mangeshkar Hospital + + + +
+
+ DMH Logo +

Patient Registration Form

+

+ Registration Form Saved Successfully.. Your Reference Form ID : {{ reference_form_id }} +

+

+ We've received your request and support team is working on it, we will get back to you as soon as possible.. +

+
+ +
+ + This facility is to be used only by patient coming first time to this hospital. +
+ + +
+ + diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..2cb4ddc --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,234 @@ +import io +from datetime import date, timedelta +from unittest.mock import patch + +import pytest +from PIL import Image + +from app import app + + +def _valid_png_bytes() -> bytes: + buf = io.BytesIO() + Image.new("RGB", (10, 10), color=(0, 128, 255)).save(buf, format="PNG") + return buf.getvalue() + + +@pytest.fixture +def client(tmp_path): + app.config["TESTING"] = True + app.config["UPLOAD_FOLDER"] = str(tmp_path / "uploads") + with app.test_client() as c: + yield c + + +def _valid_payload(): + """Return a complete, valid fake registration payload.""" + return { + "title": "1", + "lname": "DOE", + "fname": "JOHN", + "mname": "A", + "pan_no": "ABCDE1234F", + "aadhar_no": "123456789012", + "gender": "1", + "father": "RICHARD DOE", + "dob": "15/05/1990", + "age": "36", + "ageUnit": "0", + "approx_dob": "0", + "marital_status": "", + "dom": "", + "bmname": "", + "patient_income": "25000", + "address1": "123 FAKE STREET", + "address2": "NEAR PARK", + "post_office": "PUNE", + "country": "38", + "state": "12", + "city": "289", + "pincode": "411004", + "phone": "0201234567", + "office_phone": "0207654321", + "cell_phone": "9876543210", + "email": "john.doe@example.com", + "p_address1": "123 FAKE STREET", + "p_address2": "NEAR PARK", + "p_post_office": "PUNE", + "p_country": "38", + "p_state": "12", + "p_city": "289", + "p_pincode": "411004", + "p_phone": "0201234567", + "emg_person": "DOE", + "emg_person1": "JANE", + "emg_person2": "", + "relation": "2", + "emg_no": "9876500000", + "re_persone": "JANE DOE", + "re_relation": "2", + "doc_type": "1570", + "txtcaptcha": "AbCd", + "SaveDB": "Save", + "honeypot": "", + "ptnPhoto": (io.BytesIO(_valid_png_bytes()), "photo.png"), + "id_file": (io.BytesIO(b"%PDF-1.4\n1 0 obj\n<<>>\nendobj\ntrailer\n<<>>\n%%EOF"), "aadhar.pdf"), + } + + +def test_index_routes(client): + for path in ("/", "/index.php"): + resp = client.get(path) + assert resp.status_code == 200 + assert b"Patient Registration Form" in resp.data + + +def test_state_and_city_endpoints_india(client): + r1 = client.post("/getState.php?countryId=38&stateId=12") + assert r1.status_code == 200 + assert b'name="state"' in r1.data + assert b"Maharashtra" in r1.data + + r2 = client.post("/getCity.php?countryId=38&stateId=12&cityId=289") + assert r2.status_code == 200 + assert b'name="city"' in r2.data + assert b"Pune" in r2.data + + r3 = client.post("/p_getState.php?countryId=38&stateId=12") + assert r3.status_code == 200 + assert b'name="p_state"' in r3.data + + r4 = client.post("/p_getCity.php?countryId=38&stateId=12&cityId=289") + assert r4.status_code == 200 + assert b'name="p_city"' in r4.data + + +def test_state_and_city_endpoints_non_india(client): + r1 = client.post("/getState.php?countryId=81&other_state=California") + assert r1.status_code == 200 + assert b'name="other_state"' in r1.data + assert b'value="California"' in r1.data + + r2 = client.post("/getCity.php?countryId=81&other_city=San%20Jose") + assert r2.status_code == 200 + assert b'name="other_city"' in r2.data + assert b'value="San Jose"' in r2.data + + r3 = client.post("/p_getState.php?countryId=81&other_state=Texas") + assert r3.status_code == 200 + assert b'name="other_p_state"' in r3.data + + r4 = client.post("/p_getCity.php?countryId=81&other_city=Austin") + assert r4.status_code == 200 + assert b'name="other_p_city"' in r4.data + + +def test_get_dob_endpoint(client): + r_days = client.post("/getDOB.php?age=10&ageUnit=days") + assert r_days.status_code == 200 + expected = (date.today() - timedelta(days=10)).strftime("%d/%m/%Y").encode() + assert r_days.data == expected + + r_weeks = client.post("/getDOB.php?age=2&ageUnit=weeks") + assert r_weeks.status_code == 200 + expected_w = (date.today() - timedelta(weeks=2)).strftime("%d/%m/%Y").encode() + assert r_weeks.data == expected_w + + +def test_valid_submission_saves_and_shows_reference_id(client): + with patch("db.save_registration", return_value="250043") as mock_save: + resp = client.post( + "/uploadProxy.php", + data=_valid_payload(), + content_type="multipart/form-data", + ) + assert resp.status_code == 200 + assert b"Registration Form Saved Successfully.. Your Reference Form ID : 250043" in resp.data + mock_save.assert_called_once() + + +def test_honeypot_rejected(client): + data = _valid_payload() + data["honeypot"] = "bot-filled" + resp = client.post("/uploadProxy.php", data=data, content_type="multipart/form-data") + assert resp.status_code == 400 + assert b"Invalid submission detected." in resp.data + + +@pytest.mark.parametrize( + "field,bad_val,expected_msg", + [ + ("title", "", b"Please Select Title"), + ("lname", "", b"Please Enter Last Name"), + ("fname", "", b"Please Enter First Name"), + ("pan_no", "INVALID123", b"Enter Valid Pan Card Number"), + ("aadhar_no", "12345abc", b"Please Enter Numbers In Aadhar Number"), + ("aadhar_no", "12345678901", b"Please Enter 12 Digit Aadhar Number"), + ("patient_income", "abc", b"Please Enter Numbers In Monthly Income"), + ("address1", "", b"Please Enter House Name/Appt.No Details"), + ("country", "", b"Please Select Country"), + ("state", "", b"Please Select State"), + ("city", "", b"Please Select City"), + ("pincode", "41100A", b"Please Enter Numbers In Pin Number"), + ("cell_phone", "987654321a", b"Please Enter Numbers In Cell Number"), + ("cell_phone", "98765", b"Please Enter 10 Digit Cell Number"), + ("email", "bad-email", b"You have entered an invalid email address!"), + ("email", "user@domain.info", b"You have entered an invalid email address!"), + ("emg_person", "", b"Please Enter Emergency Contact Person"), + ("emg_person1", "", b"Please Enter Emergency Contact Person"), + ("relation", "", b"Please Select Relation With Patient"), + ("emg_no", "", b"Please Enter Emergency Contact Number"), + ("re_persone", "", b"Please Enter Name Of Representative"), + ("re_relation", "", b"Please Select Representative Relation To Patient"), + ("txtcaptcha", "", b"Enter captcha text."), + ("txtcaptcha", "12", b"Invalid Captcha Text!"), + ], +) +def test_field_validations(client, field, bad_val, expected_msg): + data = _valid_payload() + data[field] = bad_val + resp = client.post("/uploadProxy.php", data=data, content_type="multipart/form-data") + assert resp.status_code == 400 + assert expected_msg in resp.data + + +def test_female_marital_status_rules(client): + data = _valid_payload() + data["title"] = "3" + data["gender"] = "2" + data["marital_status"] = "" + resp = client.post("/uploadProxy.php", data=data, content_type="multipart/form-data") + assert resp.status_code == 400 + assert b"Please Choose Marital Status." in resp.data + + data2 = _valid_payload() + data2["title"] = "3" + data2["gender"] = "2" + data2["marital_status"] = "Married" + data2["dom"] = "" + data2["bmname"] = "" + resp2 = client.post("/uploadProxy.php", data=data2, content_type="multipart/form-data") + assert resp2.status_code == 400 + assert b"Please Enter Date Of Marriage." in resp2.data + assert b"Please Enter Before Marriage Name." in resp2.data + + +def test_non_india_free_text_state_city_accepted(client): + data = _valid_payload() + data["country"] = "81" + data.pop("state") + data.pop("city") + data["other_state"] = "California" + data["other_city"] = "San Jose" + with patch("db.save_registration", return_value="250099"): + resp = client.post("/uploadProxy.php", data=data, content_type="multipart/form-data") + assert resp.status_code == 200 + assert b"250099" in resp.data + + +def test_invalid_id_file_type_rejected(client): + data = _valid_payload() + data["id_file"] = (io.BytesIO(b"bad"), "malware.exe") + resp = client.post("/uploadProxy.php", data=data, content_type="multipart/form-data") + assert resp.status_code == 400 + assert b"Invalid file type" in resp.data diff --git a/tests/test_v2_features.py b/tests/test_v2_features.py new file mode 100644 index 0000000..ed60c26 --- /dev/null +++ b/tests/test_v2_features.py @@ -0,0 +1,256 @@ +import io +import logging +from contextlib import contextmanager +from unittest.mock import MagicMock, patch + +import pytest +from PIL import Image + +from app import app +from crypto_utils import ( + PiiRedactingFilter, + compute_match_token, + decrypt_pii, + encrypt_pii, + mask_aadhaar, + mask_pan, + validate_production_secrets, +) +from his_adapter import BaseHISAdapter, HISCreateResult, HISReconcileResult, HISSearchResult, get_his_adapter +from upload_service import UploadValidationError, detect_mime_from_magic_bytes, process_staged_upload +from validators import validate_core_fields +from worker import process_outbox_event + + +def _make_png_bytes(width=10, height=10, mode="RGB") -> bytes: + buf = io.BytesIO() + img = Image.new("RGB", (width, height), color=(255, 0, 0)) + if mode == "P": + img = img.convert("P") + img.save(buf, format="PNG") + return buf.getvalue() + + +def _make_animated_gif_bytes() -> bytes: + buf = io.BytesIO() + f1 = Image.new("RGB", (10, 10), color=(255, 0, 0)) + f2 = Image.new("RGB", (10, 10), color=(0, 255, 0)) + f1.save(buf, format="GIF", save_all=True, append_images=[f2], duration=100, loop=0) + return buf.getvalue() + + +@pytest.fixture +def client(tmp_path): + app.config["TESTING"] = True + app.config["UPLOAD_FOLDER"] = str(tmp_path / "uploads") + with app.test_client() as c: + yield c + + +# ============================================================ +# 1. Secrets Guard, HIS_MODE Guard, Encryption & Masking +# ============================================================ + +def test_production_guards(monkeypatch): + monkeypatch.setenv("FLASK_ENV", "production") + monkeypatch.setenv("HIS_MODE", "mock") + with pytest.raises(RuntimeError): + get_his_adapter() + + monkeypatch.setenv("FLASK_SECRET_KEY", "dev-secret-change-me") + with pytest.raises(RuntimeError): + validate_production_secrets() + + +def test_pii_encryption_masking_and_log_redaction(): + raw_aadhar = "123456789012" + raw_pan = "ABCDE1234F" + + enc_a = encrypt_pii(raw_aadhar) + enc_p = encrypt_pii(raw_pan) + assert enc_a != raw_aadhar.encode() + assert decrypt_pii(enc_a) == raw_aadhar + assert decrypt_pii(enc_p) == raw_pan + assert mask_aadhaar(raw_aadhar) == "XXXX-XXXX-9012" + assert mask_pan(raw_pan) == "XXXXXX234F" + assert compute_match_token("PAN", "abcde1234f") == compute_match_token("PAN", "ABCDE1234F") + + rec = logging.LogRecord("test", logging.INFO, "", 0, "Aadhaar 123456789012 PAN ABCDE1234F", (), None) + assert PiiRedactingFilter().filter(rec) + assert "123456789012" not in rec.msg + assert "ABCDE1234F" not in rec.msg + + +# ============================================================ +# 2. Image Service: Palette PNG, Animated GIF, Magic Bytes & Legacy Upload Guard +# ============================================================ + +def test_palette_png_and_animated_gif_preserved(tmp_path): + pal_png = _make_png_bytes(mode="P") + meta = process_staged_upload(raw_bytes=pal_png, category="PHOTO", upload_root=str(tmp_path), session_id="s1") + out_img = Image.open(tmp_path / meta["storage_key"]) + assert out_img.getpixel((0, 0))[:3] == (255, 0, 0) # Not turned black + + gif_bytes = _make_animated_gif_bytes() + meta_gif = process_staged_upload(raw_bytes=gif_bytes, category="PHOTO", upload_root=str(tmp_path), session_id="s1") + out_gif = Image.open(tmp_path / meta_gif["storage_key"]) + assert getattr(out_gif, "n_frames", 1) == 2 + + +def test_magic_bytes_and_upload_security(tmp_path): + png = _make_png_bytes() + assert detect_mime_from_magic_bytes(png) == "image/png" + assert detect_mime_from_magic_bytes(b"%PDF-1.4\n...") == "application/pdf" + assert detect_mime_from_magic_bytes(b"MZ\x90\x00exe-spoof") is None + + with pytest.raises(UploadValidationError) as exc: + process_staged_upload(raw_bytes=b"MZ\x90\x00not-a-jpg", category="KYC", upload_root=str(tmp_path), session_id="s1") + assert exc.value.status_code == 422 + + with pytest.raises(UploadValidationError) as exc_size: + process_staged_upload(raw_bytes=b"\xff\xd8\xff" + b"0" * (2 * 1024 * 1024 + 10), category="PHOTO", upload_root=str(tmp_path), session_id="s1") + assert exc_size.value.status_code == 413 + + eicar_pdf = b"%PDF-1.4\nX5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*" + with pytest.raises(UploadValidationError): + process_staged_upload(raw_bytes=eicar_pdf, category="KYC", upload_root=str(tmp_path), session_id="s1") + + +def test_legacy_upload_proxy_rejects_spoofed_exe_pdf(client): + from tests.test_app import _valid_payload + + data = _valid_payload() + data["id_file"] = (io.BytesIO(b"MZ\x90\x00spoofed-exe"), "fake.pdf") + resp = client.post("/uploadProxy.php", data=data, content_type="multipart/form-data") + assert resp.status_code == 400 + assert b"magic-byte check failed" in resp.data + + +# ============================================================ +# 3. Max-Length, Date Quality, /getDOB.php Bounds & Address Copy +# ============================================================ + +def test_max_length_and_date_quality_checks(): + base = { + "title": "1", "lname": "D" * 101, "fname": "JOHN", "gender": "1", + "dob": "15/05/1800", "age": "36", "ageUnit": "0", + "address1": "123 LOCAL ST", "country": "38", "state": "12", "city": "289", + "pincode": "411004", "email": "john@example.com", "copy": "true", + "emg_person": "DOE", "emg_person1": "JANE", "relation": "2", "emg_no": "9876500000", + "re_persone": "JANE DOE", "re_relation": "2", "doc_type": "1570", + } + _, errors = validate_core_fields(base, skip_captcha=True) + assert any("100 characters" in e for e in errors) + assert any("120 years" in e for e in errors) + + +def test_get_dob_huge_age_returns_400_not_500(client): + resp = client.post("/getDOB.php?age=3000&ageUnit=years") + assert resp.status_code == 400 + + +def test_server_derives_permanent_address_when_copy_true(): + payload = { + "title": "1", "lname": "DOE", "fname": "JOHN", "gender": "1", + "dob": "15/05/1990", "age": "36", "ageUnit": "0", + "address1": "123 LOCAL ST", "country": "38", "state": "12", "city": "289", + "pincode": "411004", "email": "john@example.com", "copy": "true", + "p_address1": "999 WRONG ST", "p_country": "81", "p_pincode": "999999", + "emg_person": "DOE", "emg_person1": "JANE", "relation": "2", "emg_no": "9876500000", + "re_persone": "JANE DOE", "re_relation": "2", "doc_type": "1570", + } + cleaned, errors = validate_core_fields(payload, skip_captcha=True) + assert errors == [] + assert cleaned["p_address1"] == "123 LOCAL ST" + assert cleaned["p_country"] == 38 + assert cleaned["p_pincode"] == "411004" + + +# ============================================================ +# 4. v1 API Idempotency, Status Ownership, DB-Backed Admin RBAC & Audit Filter +# ============================================================ + +@contextmanager +def _fake_db_conn(cur): + conn = MagicMock() + conn.cursor.return_value.__enter__.return_value = cur + yield conn + + +def test_v1_registration_idempotency_and_conflict(client): + cur = MagicMock() + cached_resp = {"success": True, "data": {"registrationReference": "250044", "status": "SUBMITTED", "hospitalPatientId": None}} + + with patch("db.get_connection", return_value=_fake_db_conn(cur).__enter__()), \ + patch("db.check_or_reserve_idempotency", return_value={"state": "COMPLETED", "http_status": 201, "response": cached_resp}): + r = client.post( + "/api/v1/registrations", + json={"sessionId": "s1", "captcha": {"challengeId": "c1", "answer": "wrong"}}, + headers={"Idempotency-Key": "k1"}, + ) + assert r.status_code == 201 + assert r.get_json()["data"]["registrationReference"] == "250044" + + with patch("db.get_connection", return_value=_fake_db_conn(cur).__enter__()), \ + patch("db.check_or_reserve_idempotency", return_value={"state": "CONFLICT"}): + r2 = client.post( + "/api/v1/registrations", + json={"sessionId": "s1", "fname": "OTHER"}, + headers={"Idempotency-Key": "k1"}, + ) + assert r2.status_code == 409 + + +def test_status_ownership_and_admin_db_rbac(client): + assert client.get("/api/v1/registrations/250044/status").status_code == 401 + + with patch("db.get_registration_status_by_ref", return_value={"reference_form_id": "250044", "session_id": "owner-sess", "status": "SUBMITTED", "hospital_patient_id": None, "email_status": "PENDING"}): + assert client.get("/api/v1/registrations/250044/status", headers={"X-Session-Id": "other-sess"}).status_code == 403 + assert client.get("/api/v1/registrations/250044/status", headers={"X-Session-Id": "owner-sess"}).status_code == 200 + + # Admin RBAC uses DB lookup, not client X-Admin-Role header + with patch("db.get_admin_user", return_value={"id": 1, "sso_subject": "staff1", "role": "REG_STAFF"}): + assert client.post( + "/api/v1/admin/registrations/1/review", + json={"decision": "APPROVE_NEW", "reason": "ok"}, + headers={"X-Admin-Token": "dev-admin-sso-token", "X-Admin-Subject": "staff1", "X-Admin-Role": "SUPERVISOR"}, + ).status_code == 403 + + with patch("db.get_admin_user", return_value={"id": 2, "sso_subject": "sup1", "role": "SUPERVISOR"}): + assert client.get( + "/api/v1/admin/audit-logs?registrationId=abc", + headers={"X-Admin-Token": "dev-admin-sso-token", "X-Admin-Subject": "sup1"}, + ).status_code == 400 + + +# ============================================================ +# 5. Outbox Worker: Timeout Reconciliation & Error Recovery +# ============================================================ + +def test_worker_timeout_reconciliation(): + class TimeoutThenFoundHIS(BaseHISAdapter): + def search_patient(self, **kwargs): + return HISSearchResult(outcome="NONE") + + def create_patient(self, **kwargs): + return HISCreateResult(outcome="TIMEOUT", reason="Socket timeout") + + def reconcile_registration(self, **kwargs): + return HISReconcileResult(outcome="FOUND", uhid="UHID-RECONCILED-1") + + cur = MagicMock() + cur.fetchone.return_value = { + "id": 1, "reference_form_id": "250044", "status": "PENDING_HIS_SYNC", + "fname": "JOHN", "lname": "DOE", "dob": "1990-05-15", "cell_phone": "9876543210", + "email": "john@example.com", + } + with patch("db.transition_registration_status") as mock_trans: + process_outbox_event( + cur, + {"id": "ev-1", "registration_id": 1, "event_type": "HIS_CREATE", "correlation_id": "corr-1"}, + TimeoutThenFoundHIS(), + ) + mock_trans.assert_called_once() + args, kwargs = mock_trans.call_args + assert args[2] == "REGISTERED" + assert kwargs["hospital_patient_id"] == "UHID-RECONCILED-1" diff --git a/upload_service.py b/upload_service.py new file mode 100644 index 0000000..3ed1bfd --- /dev/null +++ b/upload_service.py @@ -0,0 +1,162 @@ +""" +Secure document upload service: +- Magic-byte inspection (JPEG, PNG, GIF, WebP, PDF) +- Per-category size limits (2 MB photo, 5 MB KYC document) +- Decompression-bomb guard (MAX_IMAGE_PIXELS) +- Palette PNG & animated GIF safe handling + fast metadata stripping +- Quarantine -> Clean scan lifecycle + session ownership +""" + +import io +import os +import uuid +from datetime import datetime, timedelta, timezone + +from PIL import Image, ImageOps, UnidentifiedImageError + +PHOTO_MAX_BYTES = 2 * 1024 * 1024 # 2 MB +KYC_MAX_BYTES = 5 * 1024 * 1024 # 5 MB +MAX_IMAGE_DIM = 5000 +Image.MAX_IMAGE_PIXELS = 25_000_000 + +PHOTO_ALLOWED_MIMES = {"image/jpeg", "image/png", "image/gif", "image/webp"} +KYC_ALLOWED_MIMES = {"image/jpeg", "image/png", "image/gif", "application/pdf"} + + +class UploadValidationError(Exception): + def __init__(self, message: str, status_code: int = 422): + super().__init__(message) + self.message = message + self.status_code = status_code + + +def detect_mime_from_magic_bytes(data: bytes) -> str | None: + """Inspect file header magic bytes instead of trusting filename extensions.""" + if len(data) < 4: + return None + if data[:3] == b"\xff\xd8\xff": + return "image/jpeg" + if data[:8] == b"\x89PNG\r\n\x1a\n": + return "image/png" + if data[:6] in (b"GIF87a", b"GIF89a"): + return "image/gif" + if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return "image/webp" + if data[:5] == b"%PDF-": + return "application/pdf" + return None + + +def strip_image_metadata_and_validate(data: bytes, mime_type: str) -> bytes: + """ + Decode image via Pillow to validate dimensions and strip EXIF/metadata + in C-speed without materializing pixel tuples in Python RAM. + """ + if mime_type == "application/pdf": + return data + try: + with Image.open(io.BytesIO(data)) as img: + img.verify() + with Image.open(io.BytesIO(data)) as img: + w, h = img.size + if w <= 0 or h <= 0 or w > MAX_IMAGE_DIM or h > MAX_IMAGE_DIM: + raise UploadValidationError("Invalid image dimensions (max 5000x5000).", 422) + + fmt = (img.format or "JPEG").upper() + out = io.BytesIO() + + if fmt == "GIF": + is_animated = getattr(img, "is_animated", False) and getattr(img, "n_frames", 1) > 1 + if is_animated: + img.save(out, format="GIF", save_all=True) + else: + img.save(out, format="GIF") + return out.getvalue() + + # Normalize orientation from EXIF, then drop all EXIF/text chunks + img = ImageOps.exif_transpose(img) + if fmt == "JPEG" and img.mode not in ("RGB", "L"): + img = img.convert("RGB") + elif fmt == "PNG" and img.mode == "P": + # Convert palette PNGs safely so transparency/colors are preserved + img = img.convert("RGBA" if "transparency" in img.info else "RGB") + + img.save(out, format=fmt) + return out.getvalue() + except UploadValidationError: + raise + except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError) as exc: + raise UploadValidationError(f"Corrupted or invalid image content: {exc}", 422) from exc + + +def scan_quarantined_bytes(data: bytes) -> str: + """Hook for malware scanner; flags EICAR test signature as REJECTED.""" + if b"X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*" in data: + return "REJECTED" + return "CLEAN" + + +def process_staged_upload( + *, + raw_bytes: bytes, + category: str, + upload_root: str, + session_id: str, + doc_type_id: int | None = None, +) -> dict: + """Validate, strip metadata, quarantine, scan, and store a staged upload.""" + cat = (category or "").upper() + if cat not in ("PHOTO", "KYC"): + raise UploadValidationError("Invalid upload category. Must be PHOTO or KYC.", 422) + + max_bytes = PHOTO_MAX_BYTES if cat == "PHOTO" else KYC_MAX_BYTES + if len(raw_bytes) == 0: + raise UploadValidationError("Uploaded file is empty.", 422) + if len(raw_bytes) > max_bytes: + limit_mb = max_bytes // (1024 * 1024) + raise UploadValidationError(f"File exceeds maximum allowed size of {limit_mb} MB.", 413) + + mime = detect_mime_from_magic_bytes(raw_bytes) + allowed = PHOTO_ALLOWED_MIMES if cat == "PHOTO" else KYC_ALLOWED_MIMES + if mime not in allowed: + raise UploadValidationError("Invalid file type (magic-byte check failed).", 422) + + clean_bytes = strip_image_metadata_and_validate(raw_bytes, mime) + + upload_id = str(uuid.uuid4()) + ext_map = { + "image/jpeg": ".jpg", + "image/png": ".png", + "image/gif": ".gif", + "image/webp": ".webp", + "application/pdf": ".pdf", + } + ext = ext_map[mime] + quarantine_dir = os.path.join(upload_root, "quarantine") + clean_dir = os.path.join(upload_root, "clean") + os.makedirs(quarantine_dir, exist_ok=True) + os.makedirs(clean_dir, exist_ok=True) + + q_path = os.path.join(quarantine_dir, f"{upload_id}{ext}") + with open(q_path, "wb") as f: + f.write(clean_bytes) + + scan_status = scan_quarantined_bytes(clean_bytes) + if scan_status != "CLEAN": + os.remove(q_path) + raise UploadValidationError("File failed security/malware scan.", 422) + + storage_key = f"clean/{upload_id}{ext}" + os.replace(q_path, os.path.join(upload_root, storage_key)) + + return { + "id": upload_id, + "session_id": session_id, + "doc_category": cat, + "doc_type_id": doc_type_id, + "storage_key": storage_key, + "mime_type": mime, + "size_bytes": len(clean_bytes), + "scan_status": "CLEAN", + "expires_at": datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(hours=2), + } diff --git a/validators.py b/validators.py new file mode 100644 index 0000000..558c448 --- /dev/null +++ b/validators.py @@ -0,0 +1,412 @@ +""" +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 diff --git a/worker.py b/worker.py new file mode 100644 index 0000000..a8739e8 --- /dev/null +++ b/worker.py @@ -0,0 +1,225 @@ +""" +Transactional Outbox Worker & Scheduled Upload Cleanup: +Processes DUPLICATE_CHECK, HIS_CREATE (with reconcileRegistration on timeout), +and EMAIL_CONFIRMATION events outside the HTTP intake transaction. +Run continuously (`python worker.py`) or once (`python worker.py --once`). +""" + +import argparse +import logging +import os +import signal +import time +import uuid +from datetime import datetime, timedelta, timezone + +import db +from email_service import send_confirmation_email +from his_adapter import BaseHISAdapter, get_his_adapter + +logger = logging.getLogger("dmh.worker") +_STOP = False + + +def _utcnow() -> datetime: + return datetime.now(timezone.utc).replace(tzinfo=None) + + +def process_outbox_event(cur, event: dict, his_adapter: BaseHISAdapter) -> None: + reg_id = event["registration_id"] + ev_type = event["event_type"] + corr_id = event["correlation_id"] + + cur.execute("SELECT * FROM patient_registration WHERE id = %s", (reg_id,)) + reg = cur.fetchone() + if not reg: + cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],)) + return + + if ev_type == "DUPLICATE_CHECK": + if reg["status"] == "SUBMITTED": + db.transition_registration_status(cur, reg_id, "CHECKING_DUPLICATES", "OUTBOX_WORKER", correlation_id=corr_id) + cur.execute( + "SELECT match_token FROM patient_identifiers WHERE reference_form_id = %s AND match_token IS NOT NULL", + (reg["reference_form_id"],), + ) + tokens = [r["match_token"] for r in cur.fetchall()] + res = his_adapter.search_patient( + match_tokens=tokens, + fname=reg["fname"], + lname=reg["lname"], + dob=str(reg["dob"]), + mobile=reg["cell_phone"], + ) + if res.outcome == "CANDIDATE": + db.transition_registration_status( + cur, reg_id, "PENDING_REVIEW", "OUTBOX_WORKER", + reason=res.reason or "Possible HIS duplicate", correlation_id=corr_id, + ) + elif res.outcome == "NONE": + db.transition_registration_status(cur, reg_id, "PENDING_HIS_SYNC", "OUTBOX_WORKER", correlation_id=corr_id) + cur.execute( + """ + INSERT INTO outbox_events (id, registration_id, event_type, status, correlation_id) + VALUES (%s, %s, 'HIS_CREATE', 'PENDING', %s) + """, + (str(uuid.uuid4()), reg_id, corr_id), + ) + else: + raise RuntimeError(res.reason or "HIS search error") + cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],)) + + elif ev_type == "HIS_CREATE": + create_res = his_adapter.create_patient(correlation_id=corr_id, payload=reg) + if create_res.outcome == "SUCCESS" and create_res.uhid: + db.transition_registration_status( + cur, reg_id, "REGISTERED", "OUTBOX_WORKER", + hospital_patient_id=create_res.uhid, correlation_id=corr_id, + ) + cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],)) + elif create_res.outcome == "TIMEOUT": + rec = his_adapter.reconcile_registration(correlation_id=corr_id, reference_form_id=reg["reference_form_id"]) + if rec.outcome == "FOUND" and rec.uhid: + db.transition_registration_status( + cur, reg_id, "REGISTERED", "OUTBOX_WORKER", + hospital_patient_id=rec.uhid, reason="Reconciled after timeout", correlation_id=corr_id, + ) + cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],)) + elif rec.outcome == "ABSENT": + raise RuntimeError("HIS timeout reconciled as absent; safe to retry") + else: + db.transition_registration_status( + cur, reg_id, "SYNC_FAILED", "OUTBOX_WORKER", + reason=rec.reason or "Unresolved HIS timeout", correlation_id=corr_id, + ) + cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],)) + else: + db.transition_registration_status( + cur, reg_id, "SYNC_FAILED", "OUTBOX_WORKER", + reason=create_res.reason or "HIS rejected patient creation", correlation_id=corr_id, + ) + cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],)) + + elif ev_type == "EMAIL_CONFIRMATION": + try: + send_confirmation_email( + to_email=reg["email"], + reference_form_id=reg["reference_form_id"], + status=reg["status"], + ) + cur.execute("UPDATE patient_registration SET email_status = 'SENT' WHERE id = %s", (reg_id,)) + cur.execute("UPDATE outbox_events SET status = 'DONE' WHERE id = %s", (event["id"],)) + except Exception as exc: + cur.execute("UPDATE patient_registration SET email_status = 'FAILED' WHERE id = %s", (reg_id,)) + raise RuntimeError(f"Email delivery failed: {exc}") from exc + + +def cleanup_expired_uploads(upload_root: str) -> int: + """Delete expired unattached staged uploads from DB and disk.""" + removed = 0 + conn = db.get_connection() + try: + with conn.cursor() as cur: + now = _utcnow() + cur.execute( + "SELECT id, storage_key FROM patient_documents WHERE patient_id IS NULL AND expires_at < %s LIMIT 100 FOR UPDATE", + (now,), + ) + rows = cur.fetchall() + for r in rows: + path = os.path.join(upload_root, r["storage_key"]) + if os.path.exists(path): + try: + os.remove(path) + except OSError: + pass + cur.execute("DELETE FROM patient_documents WHERE id = %s", (r["id"],)) + removed += 1 + conn.commit() + except Exception: + conn.rollback() + raise + finally: + conn.close() + return removed + + +def run_once(his_adapter: BaseHISAdapter | None = None, batch_size: int = 10) -> int: + """Process one batch of pending outbox events.""" + adapter = his_adapter or get_his_adapter() + processed = 0 + conn = db.get_connection() + try: + with conn.cursor() as cur: + now = _utcnow() + cur.execute( + """ + SELECT * FROM outbox_events + WHERE status = 'PENDING' AND next_run_at <= %s + ORDER BY created_at ASC + LIMIT %s + FOR UPDATE SKIP LOCKED + """, + (now, batch_size), + ) + events = cur.fetchall() + for ev in events: + try: + process_outbox_event(cur, ev, adapter) + processed += 1 + except Exception as exc: + attempts = ev["attempts"] + 1 + status = "FAILED" if attempts >= 5 else "PENDING" + backoff = now + timedelta(seconds=min(300, 2 ** attempts * 5)) + cur.execute( + """ + UPDATE outbox_events + SET status = %s, attempts = %s, next_run_at = %s, last_error = %s + WHERE id = %s + """, + (status, attempts, backoff, str(exc)[:490], ev["id"]), + ) + conn.commit() + except Exception: + conn.rollback() + raise + finally: + conn.close() + return processed + + +def main() -> None: + parser = argparse.ArgumentParser(description="DMH Outbox Worker") + parser.add_argument("--once", action="store_true", help="Process one batch and exit") + args = parser.parse_args() + + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") + upload_root = os.getenv("UPLOAD_FOLDER", "uploads") + poll_sec = float(os.getenv("WORKER_POLL_INTERVAL", "5")) + + def _handle_sig(_sig, _frame): + global _STOP + _STOP = True + + signal.signal(signal.SIGINT, _handle_sig) + signal.signal(signal.SIGTERM, _handle_sig) + + adapter = get_his_adapter() + if args.once: + count = run_once(adapter) + cleaned = cleanup_expired_uploads(upload_root) + logger.info("Processed %d outbox events, cleaned %d expired uploads.", count, cleaned) + return + + logger.info("Starting DMH outbox worker (poll=%ss, mode=%s)", poll_sec, os.getenv("HIS_MODE", "disabled")) + while not _STOP: + try: + run_once(adapter) + cleanup_expired_uploads(upload_root) + except Exception as exc: + logger.error("Worker iteration error: %s", exc) + time.sleep(poll_sec) + + +if __name__ == "__main__": + main()