diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..90717ccbd6ec49beaa97e296f4994feeb2229ee1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,14 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +static/vendor/font-awesome/webfonts/fa-brands-400.ttf filter=lfs diff=lfs merge=lfs -text +static/vendor/font-awesome/webfonts/fa-brands-400.woff2 filter=lfs diff=lfs merge=lfs -text +static/vendor/font-awesome/webfonts/fa-solid-900.ttf filter=lfs diff=lfs merge=lfs -text +static/vendor/font-awesome/webfonts/fa-solid-900.woff2 filter=lfs diff=lfs merge=lfs -text +static/vendor/fonts/Inter-300.ttf filter=lfs diff=lfs merge=lfs -text +static/vendor/fonts/Inter-400.ttf filter=lfs diff=lfs merge=lfs -text +static/vendor/fonts/Inter-500.ttf filter=lfs diff=lfs merge=lfs -text +static/vendor/fonts/Inter-600.ttf filter=lfs diff=lfs merge=lfs -text +static/vendor/fonts/Inter-700.ttf filter=lfs diff=lfs merge=lfs -text +uploads/attachments/14_e8137e8fb27f236b.pdf filter=lfs diff=lfs merge=lfs -text +uploads/chat_media/1ff26a15-52ee-4896-b8a9-1b2fd8f87d86.png filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..34ebfe8ab5ef86bb51f8a27a8a0b7848bba1c421 --- /dev/null +++ b/.gitignore @@ -0,0 +1,59 @@ +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +*.egg-info/ +dist/ +build/ +*.egg + +# Virtual Environment +venv/ +.venv/ +ENV/ + +# IDE +.idea/ +.vscode/ +*.swp +*.swo +*~ + +# Database files +*.db +*.db-journal +*.db-shm +*.db-wal + +# Uploads & temp files +uploads/ +tmp/ + +# OS +.DS_Store +Thumbs.db +desktop.ini + +# Environment variables (SECRETS!) +.env +.env.local + +# Logs +*.log + +# Published output +NexLab_Published/ + +# Backups +backups/ + +# Binary archives +*.rar +*.zip + +# Test/scratch files +test_*.py +test_*.html +scratch/ +scratch.txt diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fa4f15cd47b60a1b4f4e5ee8b90113433c803976 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,55 @@ +# Use the official Python 3.11 slim image +FROM python:3.11-slim + +# Install system dependencies required for Playwright (Chromium) and PDF generation +RUN apt-get update && apt-get install -y --no-install-recommends \ + wget \ + gnupg \ + libnss3 \ + libatk1.0-0 \ + libatk-bridge2.0-0 \ + libcups2 \ + libdrm2 \ + libxkbcommon0 \ + libxcomposite1 \ + libxdamage1 \ + libxext6 \ + libxfixes3 \ + librandr2 \ + libgbm1 \ + libpango-1.0-0 \ + libcairo2 \ + libasound2 \ + && rm -rf /var/lib/apt/lists/* + +# Create a non-root user (required by Hugging Face Spaces and best practice for security) +RUN useradd -m -u 1000 user +WORKDIR /home/user/app + +# Copy requirements first to leverage Docker cache +COPY --chown=user:user requirements.txt . + +# Install Python packages and Playwright browsers +RUN pip install --no-cache-dir -r requirements.txt && \ + playwright install chromium + +# Copy the rest of the application files +COPY --chown=user:user . . + +# Ensure directory permissions are correct for temporary files and uploads +RUN mkdir -p tmp uploads/attachments uploads/chat_media backups && \ + chown -R user:user /home/user/app + +# Switch to the non-root user +USER user + +# Set environment variables +ENV PORT=7860 +ENV DATABASE_URL=sqlite:///home/user/app/lab_database.db +ENV PYTHONUNBUFFERED=1 + +# Expose the port (Hugging Face Spaces uses 7860 by default) +EXPOSE 7860 + +# Command to run the application +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"] diff --git a/System_Update_Guide.md b/System_Update_Guide.md new file mode 100644 index 0000000000000000000000000000000000000000..d4a4353bd85db06ab97b92491a87237c03b88a61 --- /dev/null +++ b/System_Update_Guide.md @@ -0,0 +1,53 @@ +# NexLab System Update Guide + +This guide ensures you can update your NexLab Laboratory Information System (LIS) without losing any patient data or system settings. + +## 🕒 Best Practices +- Always update when the lab is quiet (e.g., end of the day). +- Ensure no one is currently using the system before starting. +- Keep a backup of your `lab_database.db` file in a safe location. + +--- + +## 🚀 The Automatic Way (Recommended) +We have provided an automated tool to handle backups and database migrations for you. + +1. **Close the System**: Stop the server (close the window opened by `start_nexlab.bat`). +2. **Run the Update Tool**: Double-click `update_system.bat`. +3. **Follow the Prompts**: + * The tool will automatically create a backup in the `backups/` folder. + * It will ask you to confirm that you have replaced the system files with the new version. + * It will automatically run all database migrations (`migrate_*.py`). +4. **Restart**: Once completed, run `start_nexlab.bat` as usual. + +--- + +## 🛠️ The Manual Way (Step-by-Step) +If you prefer to perform the update manually, follow these steps exactly: + +### 1. Backup your Database +- Go to your system folder (`lab_system`). +- Locate the file `lab_database.db`. +- Copy this file and paste it into a folder named `backups`. Rename it to something like `lab_database_backup_DATE.db`. + +### 2. Replace System Files +- Delete the old files (except for `lab_database.db`, `backups/`, and `venv/`). +- Copy the new files from the update package into the `lab_system` folder. + +### 3. Run Database Migrations +- If the new system version includes new database columns or features, you must run the migration scripts. +- Open a Command Prompt in the folder. +- Type: `venv\Scripts\python.exe run_all_migrations.py` +- Press Enter. + +### 4. Restart the Server +- Double-click `start_nexlab.bat` to bring the system back online. + +--- + +## 🆘 Troubleshooting +- **Error: "Column already exists"**: This is normal if you have already run the migration before. The scripts are designed to skip columns that already exist. +- **System Won't Start**: Check the `update_debug.log` if it exists, or restore your backup by renaming your latest backup file back to `lab_database.db`. + +> [!WARNING] +> DO NOT delete or overwrite `lab_database.db` during an update. This file contains all your data. diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7303b25107b0be0dc34e58c3fdb364b9def0c007 --- /dev/null +++ b/app/__init__.py @@ -0,0 +1,2 @@ +# app/__init__.py +# NexLab LIS Application Package diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000000000000000000000000000000000000..62e56e11f54cde6fefedf603c14799429807135f --- /dev/null +++ b/app/config.py @@ -0,0 +1,68 @@ +# app/config.py +# Centralised configuration — single source of truth for all settings. + +import os +import logging + +# Load .env file if python-dotenv is available +try: + from dotenv import load_dotenv + # Look for .env in project root (parent of app/) + _project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + _env_path = os.path.join(_project_root, ".env") + if os.path.exists(_env_path): + load_dotenv(_env_path) +except ImportError: + pass + +PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +# =========================== +# SECRET KEY +# =========================== +_env_secret = os.environ.get("NEXLAB_SECRET_KEY") +if _env_secret: + SECRET_KEY = _env_secret +else: + import uuid + SECRET_KEY = uuid.uuid4().hex + uuid.uuid4().hex + logging.getLogger("nexlab.security").warning( + "NEXLAB_SECRET_KEY not set! Using auto-generated key. " + "Sessions will NOT persist across restarts. " + "Set NEXLAB_SECRET_KEY in .env for production use." + ) + +# =========================== +# DATABASE +# =========================== +DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///./lab_database.db") + +# If it is a relative sqlite URL, make it absolute relative to PROJECT_ROOT +if DATABASE_URL.startswith("sqlite:///"): + db_path = DATABASE_URL[10:] + if not (db_path.startswith("/") or db_path.startswith("\\") or (len(db_path) > 1 and db_path[1] == ":")): + if db_path.startswith("./") or db_path.startswith(".\\"): + db_path = db_path[2:] + abs_db_path = os.path.abspath(os.path.join(PROJECT_ROOT, db_path)) + DATABASE_URL = f"sqlite:///{abs_db_path}" + + +# =========================== +# PATHS +# =========================== +TEMPLATE_DIR = os.path.join(PROJECT_ROOT, "templates") +STATIC_DIR = os.path.join(PROJECT_ROOT, "static") +UPLOAD_DIR = os.path.join(PROJECT_ROOT, "uploads") +TMP_DIR = os.path.join(PROJECT_ROOT, "tmp") +BACKUP_DIR = os.path.join(PROJECT_ROOT, "backups") + +# =========================== +# SERVER +# =========================== +PORT = int(os.environ.get("PORT", 8000)) + +# =========================== +# PASSWORD HASHING +# =========================== +from passlib.context import CryptContext +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") diff --git a/app/database.py b/app/database.py new file mode 100644 index 0000000000000000000000000000000000000000..9e18a5e320b28cd130f3ae37d4ac7b8222674fcf --- /dev/null +++ b/app/database.py @@ -0,0 +1,51 @@ +# app/database.py +# Database engine, session factory, and SQLite performance pragmas. +# Hardened for multi-user concurrent access (4+ PCs). + +from sqlmodel import create_engine, SQLModel, Session +from sqlalchemy import event +from sqlalchemy.pool import StaticPool + +from app.config import DATABASE_URL + +# Create engine with StaticPool — optimal for SQLite with multi-threaded access. +# StaticPool uses a single connection that is reused across all threads, +# which is the safest strategy for SQLite + FastAPI (single worker). +engine = create_engine( + DATABASE_URL, + echo=False, + connect_args={"check_same_thread": False}, + poolclass=StaticPool, +) + + +# Enable performance & concurrency PRAGMAs for every SQLite connection +@event.listens_for(engine, "connect") +def _set_sqlite_pragma(dbapi_connection, connection_record): + cursor = dbapi_connection.cursor() + cursor.execute("PRAGMA foreign_keys=ON") + # WAL mode: allows concurrent reads during writes (critical for multi-user) + cursor.execute("PRAGMA journal_mode=WAL") + # Busy timeout: wait up to 10 seconds instead of failing immediately on lock + # Increased from 5s for multi-PC environments + cursor.execute("PRAGMA busy_timeout=10000") + # Synchronous NORMAL: safe with WAL, faster than FULL + cursor.execute("PRAGMA synchronous=NORMAL") + # Cache size: ~32MB in memory for faster reads + cursor.execute("PRAGMA cache_size=-32000") + # Store temp tables in memory (faster joins and sorts) + cursor.execute("PRAGMA temp_store=MEMORY") + # Memory-mapped I/O: 256 MB for faster large reads + cursor.execute("PRAGMA mmap_size=268435456") + cursor.close() + + +def create_db_and_tables(): + """Create all tables defined by SQLModel metadata. Runs once at startup.""" + SQLModel.metadata.create_all(engine) + + +def get_session(): + """Yield a database session for FastAPI dependency injection.""" + with Session(engine) as session: + yield session diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000000000000000000000000000000000000..4e4b831dd3320cd26a0bc8d35d490630a288b622 --- /dev/null +++ b/app/main.py @@ -0,0 +1,146 @@ +# app/main.py +# NexLab LIS — FastAPI Application Entry Point +# Slim entry point: registers routers, lifecycle, middleware, error handling. + +from fastapi import FastAPI, Request +from fastapi.staticfiles import StaticFiles +from fastapi.responses import JSONResponse, HTMLResponse +from sqlmodel import Session, select +from contextlib import asynccontextmanager +import os +import logging + +from app.config import SECRET_KEY, pwd_context +from app.database import create_db_and_tables, engine +from app.models import User +from app.middleware import auth_middleware + +# Import routers (from original routes/ directory — they still work via bridges) +from routes.auth import router as auth_router +from routes.departments import router as departments_router +from routes.tests import router as tests_router +from routes.geography import router as geography_router +from routes.patients import router as patients_router +from routes.printing import router as printing_router +from routes.api import router as api_router +from routes.results import router as results_router +from routes.double_auth import router as double_auth_router +from routes.call_centre import router as call_centre_router +from routes.history import router as history_router +from routes.patient_status import router as patient_status_router +from routes.users import router as users_router +from routes.attachments import router as attachments_router +from routes.expenses import router as expenses_router +from routes.reports import router as reports_router +from routes.messages import router as messages_router +from routes.websockets import router as websockets_router +from routes.supplies import router as supplies_router +from routes.inventory import router as inventory_router +from routes.cal_control import router as cal_control_router +from routes.hr import router as hr_router + + +# =========================== +# APP LIFESPAN (Startup/Shutdown) +# =========================== +@asynccontextmanager +async def lifespan(app: FastAPI): + # Startup: create tables + create_db_and_tables() + + # Ensure required directories exist + for d in ["tmp", "uploads", "uploads/attachments", "uploads/chat_media"]: + os.makedirs(d, exist_ok=True) + + # Seed admin user if none exists + with Session(engine) as session: + existing = session.exec(select(User).where(User.username == "admin")).first() + if not existing: + admin = User( + username="admin", + full_name="Administrator", + role="admin", + hashed_password=pwd_context.hash("admin123"), + is_active=True + ) + session.add(admin) + session.commit() + print("WARNING: Default admin user created with password 'admin123'. Change this immediately in production!") + else: + print("[OK] Admin user already exists") + + yield + + +app = FastAPI(title="NexLab LIS", lifespan=lifespan) + + +# =========================== +# GLOBAL ERROR HANDLERS — Crash-proof +# =========================== +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + """Catch all unhandled exceptions so the server NEVER crashes.""" + logging.error(f"Unhandled error on {request.url.path}: {exc}", exc_info=True) + if request.url.path.startswith("/api/"): + return JSONResponse( + status_code=500, + content={"error": "Internal server error", "detail": str(exc)} + ) + return HTMLResponse( + content=f"
An internal error occurred. The system is still running.
", + status_code=500 + ) + + +@app.exception_handler(404) +async def not_found_handler(request: Request, exc): + if request.url.path.startswith("/api/"): + return JSONResponse(status_code=404, content={"error": "Not found"}) + return HTMLResponse( + content=f"The page you requested does not exist.
", + status_code=404 + ) + + +# =========================== +# AUTH MIDDLEWARE +# =========================== +@app.middleware("http") +async def _auth_middleware(request, call_next): + return await auth_middleware(request, call_next) + + +# =========================== +# STATIC FILES +# =========================== +app.mount("/static", StaticFiles(directory="static"), name="static") +app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads") +app.mount("/tmp", StaticFiles(directory="tmp"), name="tmp") + + +# =========================== +# INCLUDE ROUTERS +# =========================== +app.include_router(auth_router) +app.include_router(departments_router) +app.include_router(tests_router) +app.include_router(geography_router) +app.include_router(patients_router) +app.include_router(printing_router) +app.include_router(api_router) +app.include_router(results_router) +app.include_router(double_auth_router) +app.include_router(call_centre_router) +app.include_router(history_router) +app.include_router(patient_status_router) +app.include_router(users_router) +app.include_router(attachments_router) +app.include_router(expenses_router) +app.include_router(reports_router) +app.include_router(messages_router) +app.include_router(websockets_router) +app.include_router(supplies_router) +app.include_router(inventory_router) +app.include_router(cal_control_router) +app.include_router(hr_router) diff --git a/app/middleware.py b/app/middleware.py new file mode 100644 index 0000000000000000000000000000000000000000..a0e4af3e29914209d6c83e54bff18adfea872364 --- /dev/null +++ b/app/middleware.py @@ -0,0 +1,45 @@ +# app/middleware.py +# Auth middleware — protects all routes, extracted from main.py for clean SoC. + +import hashlib +from starlette.responses import RedirectResponse as StarletteRedirect + +from app.config import SECRET_KEY +from sqlmodel import Session +from app.database import engine +from app.services.auth_service import get_current_user + +# Pre-compute the print token once at import time (not per-request) +PRINT_TOKEN = hashlib.sha256(SECRET_KEY.encode()).hexdigest()[:16] + +# Paths that don't require authentication +PUBLIC_PATHS = ["/login", "/static/", "/tmp/", "/favicon.ico"] + + +async def auth_middleware(request, call_next): + """HTTP middleware that enforces authentication on all non-public routes.""" + path = request.url.path + is_public = any(path.startswith(p) for p in PUBLIC_PATHS) + + # Allow local Headless Chrome to load assets for PDF generation + user_agent = request.headers.get("user-agent", "") + if "HeadlessChrome" in user_agent and request.client.host == "127.0.0.1": + is_public = True + + # NexPrint token bypass for barcode/receipt printing + if path.startswith("/print-barcode/") or path.startswith("/print-receipt/") or path.startswith("/api/print-barcode-pdf/") or path.startswith("/api/print-barcode-image/"): + token = request.query_params.get("print_token", "") + if token == PRINT_TOKEN: + is_public = True + + if not is_public: + with Session(engine) as session: + user = get_current_user(request, session) + if not user: + response = StarletteRedirect(url="/login", status_code=303) + response.delete_cookie("nexlab_session") + return response + request.state.user_id = user.id + + response = await call_next(request) + return response diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..50a874baa322ea47e3cb5f77af2e497bad813ebf --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1,35 @@ +# app/models/__init__.py +# Central re-export of all models. +# Usage: from app.models import Patient, Order, User, ... + +from app.models.user import User, UserPermission +from app.models.audit import AuditLog, ActivityLog, DeletedRecord +from app.models.department import Parameter, Department, Device, SampleType, ReportNote +from app.models.geography import Province, Region +from app.models.test import TestDefinition, TestDevice, TestParameter, TestRange, TestResultType +from app.models.patient import Patient, PatientVisit, Attachment +from app.models.order import Order, Result, ResultDetail +from app.models.formula import Formula, FormulaItem +from app.models.package import Partner, Package, PackageTest +from app.models.lab import LabInfo, PrintTemplate +from app.models.finance import Payment, ExpenseType, Expense +from app.models.messaging import Chat, ChatMember, Message, MessageReceipt +from app.models.inventory import Supply, Inventory, CalControl +from app.models.hr import Employee, EmployeeAttachment + +__all__ = [ + "User", "UserPermission", + "AuditLog", "ActivityLog", "DeletedRecord", + "Parameter", "Department", "Device", "SampleType", "ReportNote", + "Province", "Region", + "TestDefinition", "TestDevice", "TestParameter", "TestRange", "TestResultType", + "Patient", "PatientVisit", "Attachment", + "Order", "Result", "ResultDetail", + "Formula", "FormulaItem", + "Partner", "Package", "PackageTest", + "LabInfo", "PrintTemplate", + "Payment", "ExpenseType", "Expense", + "Chat", "ChatMember", "Message", "MessageReceipt", + "Supply", "Inventory", "CalControl", + "Employee", "EmployeeAttachment", +] diff --git a/app/models/audit.py b/app/models/audit.py new file mode 100644 index 0000000000000000000000000000000000000000..3537888b651aef601607ed6eee6eedc876e77d29 --- /dev/null +++ b/app/models/audit.py @@ -0,0 +1,39 @@ +# app/models/audit.py +# Audit logging, activity tracking, and archival models. + +from typing import Optional +from datetime import datetime +from sqlmodel import SQLModel, Field + + +class AuditLog(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + table_name: str + record_id: int + action: str + user_id: int = Field(foreign_key="user.id") + username: str + old_values: Optional[str] = None + new_values: Optional[str] = None + created_at: datetime = Field(default_factory=datetime.now) + + +class ActivityLog(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + action_type: str = Field(index=True) + description: str + target_type: Optional[str] = None + target_id: Optional[int] = None + user_id: Optional[int] = Field(default=None, foreign_key="user.id") + username: Optional[str] = None + created_at: datetime = Field(default_factory=datetime.now) + + +class DeletedRecord(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + source_table: str = Field(index=True) + record_id: int + record_data: str # Full JSON snapshot + deleted_reason: Optional[str] = None + deleted_by: int = Field(foreign_key="user.id") + deleted_at: datetime = Field(default_factory=datetime.now) diff --git a/app/models/department.py b/app/models/department.py new file mode 100644 index 0000000000000000000000000000000000000000..02ccaf2cba5793e9b05b47aef59b713fcaa4a21f --- /dev/null +++ b/app/models/department.py @@ -0,0 +1,92 @@ +# app/models/department.py +# Department, SampleType, Device, Parameter, and ReportNote models. + +from typing import Optional +from datetime import datetime +from sqlmodel import SQLModel, Field + + +class Parameter(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + parameter_name: str = Field(unique=True, index=True) + parameter_short_name: str + is_header: bool = Field(default=False) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + + +class Department(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + department_name: str = Field(unique=True, index=True) + department_note: Optional[str] = None + is_active: bool = Field(default=True) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + activated_by: Optional[int] = Field(default=None, foreign_key="user.id") + activated_at: Optional[datetime] = None + deactivated_by: Optional[int] = Field(default=None, foreign_key="user.id") + deactivated_at: Optional[datetime] = None + + +class Device(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + device_name: str = Field(unique=True, index=True) + serial_number: str + install_date: datetime + installer_name: str + installer_phone: str + note: Optional[str] = None + is_active: bool = Field(default=True) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + activated_by: Optional[int] = Field(default=None, foreign_key="user.id") + activated_at: Optional[datetime] = None + deactivated_by: Optional[int] = Field(default=None, foreign_key="user.id") + deactivated_at: Optional[datetime] = None + + +class SampleType(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + sample_name: str = Field(unique=True, index=True) + sample_note: Optional[str] = None + is_active: bool = Field(default=True) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + activated_by: Optional[int] = Field(default=None, foreign_key="user.id") + activated_at: Optional[datetime] = None + deactivated_by: Optional[int] = Field(default=None, foreign_key="user.id") + deactivated_at: Optional[datetime] = None + + +class ReportNote(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + note_name: str = Field(unique=True, index=True) + note_content: str + is_active: bool = Field(default=True) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None diff --git a/app/models/finance.py b/app/models/finance.py new file mode 100644 index 0000000000000000000000000000000000000000..d160aec47f3bfc0f3d204220deb57ebba7e9132f --- /dev/null +++ b/app/models/finance.py @@ -0,0 +1,42 @@ +# app/models/finance.py +# Payment, Expense, and ExpenseType models. + +from typing import Optional +from datetime import datetime +from sqlmodel import SQLModel, Field, Relationship + + +class Payment(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + visit_id: int = Field(foreign_key="patientvisit.id", index=True) + patient_id: int = Field(foreign_key="patient.id", index=True) + amount: float + payment_method: str = Field(default="cash") + payment_date: datetime = Field(default_factory=datetime.now) + note: Optional[str] = None + recorded_by: int = Field(foreign_key="user.id") + is_refund: bool = Field(default=False) + + +class ExpenseType(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + type_name: str = Field(unique=True, index=True) + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + + +class Expense(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + type_id: int = Field(foreign_key="expensetype.id", index=True) + expense_date: datetime = Field(default_factory=datetime.now) + amount: float = Field(default=0.0) + note: Optional[str] = None + file_path: Optional[str] = None + file_name: Optional[str] = None + created_by: int = Field(foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + expense_type: "ExpenseType" = Relationship() diff --git a/app/models/formula.py b/app/models/formula.py new file mode 100644 index 0000000000000000000000000000000000000000..47acfc34035836adabb2e3511524fd5327251ac3 --- /dev/null +++ b/app/models/formula.py @@ -0,0 +1,43 @@ +# app/models/formula.py +# Formula and FormulaItem models. + +from typing import Optional, List +from datetime import datetime +from sqlmodel import SQLModel, Field, Relationship + +from app.models.department import Parameter + + +class Formula(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + formula_name: str + main_test_id: int = Field(foreign_key="testdefinition.id") + main_parameter_id: Optional[int] = Field(default=None, foreign_key="parameter.id") + gender_type: str = Field(default="both") + formula_expression: str = Field(default="") + formula_description: Optional[str] = None + is_active: bool = Field(default=True) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + + main_test: "TestDefinition" = Relationship() + main_parameter: Optional[Parameter] = Relationship() + items: List["FormulaItem"] = Relationship(back_populates="formula") + + +class FormulaItem(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + formula_id: int = Field(foreign_key="formula.id") + operation: str = Field(default="+") + source_type: str = Field(default="parameter") + source_test_id: Optional[int] = Field(default=None, foreign_key="testdefinition.id") + source_parameter_id: Optional[int] = Field(default=None, foreign_key="parameter.id") + weight_value: float = Field(default=1.0) + order_index: int = Field(default=0) + + formula: Formula = Relationship(back_populates="items") diff --git a/app/models/geography.py b/app/models/geography.py new file mode 100644 index 0000000000000000000000000000000000000000..9ebaeac71a1401769b40dacd1040ef8c071941d0 --- /dev/null +++ b/app/models/geography.py @@ -0,0 +1,35 @@ +# app/models/geography.py +# Province and Region models. + +from typing import Optional +from datetime import datetime +from sqlmodel import SQLModel, Field, Relationship + + +class Province(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + province_name: str = Field(unique=True, index=True) + is_active: bool = Field(default=True) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + + +class Region(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + region_name: str = Field(unique=True, index=True) + province_id: int = Field(foreign_key="province.id") + is_active: bool = Field(default=True) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + + province: Province = Relationship() diff --git a/app/models/hr.py b/app/models/hr.py new file mode 100644 index 0000000000000000000000000000000000000000..261b42574740a7e4646563f68e9988e6725084f8 --- /dev/null +++ b/app/models/hr.py @@ -0,0 +1,48 @@ +# app/models/hr.py +# Employee and EmployeeAttachment models for HR management. + +from typing import Optional, List +from datetime import datetime +from sqlmodel import SQLModel, Field, Relationship + +class Employee(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + full_name: str = Field(index=True) + age: Optional[int] = None + phone: Optional[str] = None + address: Optional[str] = None + photo_path: Optional[str] = None + start_date: datetime = Field(default_factory=datetime.now) + + # Store working days as a comma-separated string or JSON string (e.g. "Monday, Tuesday, Wednesday") + working_days: Optional[str] = None + + # Store hours as "09:00" and "17:00" for simplicity + working_hours_start: Optional[str] = None + working_hours_end: Optional[str] = None + + salary: Optional[float] = None + username: Optional[str] = None + is_active: bool = Field(default=True) + + created_at: datetime = Field(default_factory=datetime.now) + + attachments: List["EmployeeAttachment"] = Relationship(back_populates="employee", cascade_delete=True) + + @property + def working_life_months(self) -> int: + if not self.start_date: + return 0 + now = datetime.now() + delta = now.year * 12 + now.month - (self.start_date.year * 12 + self.start_date.month) + return delta if delta > 0 else 0 + + +class EmployeeAttachment(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + employee_id: int = Field(foreign_key="employee.id", index=True) + file_name: str + file_path: str + uploaded_at: datetime = Field(default_factory=datetime.now) + + employee: Optional["Employee"] = Relationship(back_populates="attachments") diff --git a/app/models/inventory.py b/app/models/inventory.py new file mode 100644 index 0000000000000000000000000000000000000000..65f520ddf286ca9217b7012305e78615eefb92a5 --- /dev/null +++ b/app/models/inventory.py @@ -0,0 +1,48 @@ +# app/models/inventory.py +# Supply, Inventory, and CalControl models. + +from typing import Optional +from datetime import datetime +from sqlmodel import SQLModel, Field, Relationship + + +class Supply(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + name: str = Field(index=True) + note: Optional[str] = None + is_active: bool = Field(default=True) + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + + +class Inventory(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + material_type: str = Field(index=True) + test_id: Optional[int] = Field(default=None, foreign_key="testdefinition.id") + supply_id: Optional[int] = Field(default=None, foreign_key="supply.id") + test: Optional["TestDefinition"] = Relationship() + supply: Optional["Supply"] = Relationship() + quantity: float = Field(default=0.0) + unit: str = Field(default="Test") + expiration_date: datetime + note: Optional[str] = None + is_active: bool = Field(default=True) + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + + +class CalControl(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + test_id: int = Field(foreign_key="testdefinition.id", index=True) + device_id: int = Field(foreign_key="device.id", index=True) + process_type: str = Field(index=True) + quantity: float + note: Optional[str] = None + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + test: "TestDefinition" = Relationship() + device: "Device" = Relationship() diff --git a/app/models/lab.py b/app/models/lab.py new file mode 100644 index 0000000000000000000000000000000000000000..d5f2f224448ee604bbe67886d9a30433d195f172 --- /dev/null +++ b/app/models/lab.py @@ -0,0 +1,61 @@ +# app/models/lab.py +# LabInfo and PrintTemplate models. + +from typing import Optional +from datetime import datetime +from sqlmodel import SQLModel, Field + + +class LabInfo(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + lab_name: str = Field(default="") + lab_title: Optional[str] = Field(default=None) + first_doctor_name: Optional[str] = Field(default=None) + second_doctor_name: Optional[str] = Field(default=None) + lab_address: Optional[str] = Field(default=None) + lab_phone_1: str = Field(default="") + lab_phone_2: Optional[str] = Field(default=None) + whatsapp_api: Optional[str] = Field(default=None) + whatsapp_token: Optional[str] = Field(default=None) + telegram_api: Optional[str] = Field(default=None) + telegram_token: Optional[str] = Field(default=None) + lab_qr_1: Optional[str] = Field(default=None) + lab_qr_2: Optional[str] = Field(default=None) + lab_stamp_1: Optional[str] = Field(default=None) + lab_stamp_2: Optional[str] = Field(default=None) + lab_logo: Optional[str] = Field(default=None) + lab_signature_1: Optional[str] = Field(default=None) + lab_signature_2: Optional[str] = Field(default=None) + lab_image_1: Optional[str] = Field(default=None) + lab_image_2: Optional[str] = Field(default=None) + lab_email: Optional[str] = Field(default=None) + lab_note_1: Optional[str] = Field(default=None) + lab_note_2: Optional[str] = Field(default=None) + lab_website: Optional[str] = Field(default=None) + welcome_message: Optional[str] = Field(default=None) + welcome_template_name: Optional[str] = Field(default=None) + province_id: Optional[int] = Field(default=None, foreign_key="province.id") + lab_currency: str = Field(default="$") + tax_percentage: float = Field(default=0.0) + phone_country_code: str = Field(default="964") + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + + +class PrintTemplate(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + template_name: str = Field(unique=True, index=True) + template_type: str = Field(default="receipt") + paper_width: str = Field(default="80mm") + paper_height: str = Field(default="auto") + margin: str = Field(default="0") + elements: str = Field(default="") + is_active: bool = Field(default=True) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None diff --git a/app/models/messaging.py b/app/models/messaging.py new file mode 100644 index 0000000000000000000000000000000000000000..00c98d4e0ef8aa419320e500df327a302746d312 --- /dev/null +++ b/app/models/messaging.py @@ -0,0 +1,52 @@ +# app/models/messaging.py +# Chat, ChatMember, Message, MessageReceipt models. + +from typing import Optional +from datetime import datetime +from sqlmodel import SQLModel, Field + + +class Chat(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + is_group: bool = Field(default=False) + name: Optional[str] = None + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_at: Optional[datetime] = None + + +class ChatMember(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + chat_id: int = Field(foreign_key="chat.id", index=True) + user_id: int = Field(foreign_key="user.id", index=True) + joined_at: datetime = Field(default_factory=datetime.now) + is_admin: bool = Field(default=False) + last_read_message_id: Optional[int] = None + + +class Message(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + chat_id: int = Field(foreign_key="chat.id", index=True) + sender_id: Optional[int] = Field(default=None, foreign_key="user.id", index=True) + text: Optional[str] = None + attachment_path: Optional[str] = None + attachment_name: Optional[str] = None + attachment_type: Optional[str] = None + voice_note_path: Optional[str] = None + voice_note_duration: Optional[int] = None + reply_to_id: Optional[int] = Field(default=None, foreign_key="message.id") + created_at: datetime = Field(default_factory=datetime.now) + is_deleted: bool = Field(default=False) + is_call: bool = Field(default=False) + call_type: Optional[str] = None + call_status: Optional[str] = None + call_duration: Optional[int] = None + + +class MessageReceipt(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + message_id: int = Field(foreign_key="message.id", index=True) + user_id: int = Field(foreign_key="user.id", index=True) + chat_id: int = Field(foreign_key="chat.id", index=True) + status: str = Field(default="delivered") + updated_at: datetime = Field(default_factory=datetime.now) diff --git a/app/models/order.py b/app/models/order.py new file mode 100644 index 0000000000000000000000000000000000000000..47eb3d4ca66a87a8e43ab6d12205b4914abfbd23 --- /dev/null +++ b/app/models/order.py @@ -0,0 +1,71 @@ +# app/models/order.py +# Order, Result, and ResultDetail models. + +from typing import Optional, List +from datetime import datetime +from sqlmodel import SQLModel, Field, Relationship + +from app.models.department import Parameter + + +class Order(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + order_number: str = Field(unique=True, index=True) + patient_id: int = Field(foreign_key="patient.id") + test_id: int = Field(foreign_key="testdefinition.id") + status: str = Field(default="ordered") + ordered_by: int = Field(foreign_key="user.id") + collected_by: Optional[int] = Field(default=None, foreign_key="user.id") + verified_by: Optional[int] = Field(default=None, foreign_key="user.id") + order_date: datetime = Field(default_factory=datetime.now) + collection_date: Optional[datetime] = None + verified_date: Optional[datetime] = None + visit_id: Optional[int] = Field(default=None, foreign_key="patientvisit.id") + package_name: Optional[str] = Field(default=None) + # Price snapshot at order time + unit_price: float = Field(default=0.0) + discount_amount: float = Field(default=0.0) + final_price: float = Field(default=0.0) + no_sample_reason: Optional[str] = Field(default=None) + + # Relationships — use string references for cross-module models + patient: "Patient" = Relationship(back_populates="orders") + test: "TestDefinition" = Relationship() + result: Optional["Result"] = Relationship(back_populates="order") + visit: Optional["PatientVisit"] = Relationship(back_populates="orders") + + +class Result(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + order_id: int = Field(foreign_key="order.id", unique=True) + result_value: Optional[str] = Field(default=None) + rerun_result: Optional[str] = Field(default=None) + flag: Optional[str] = None + note: Optional[str] = None + device_id: Optional[int] = Field(default=None, foreign_key="device.id") + entered_by: int = Field(foreign_key="user.id") + entered_at: datetime = Field(default_factory=datetime.now) + authorized: bool = Field(default=False) + authorized_by: Optional[int] = Field(default=None, foreign_key="user.id") + authorized_at: Optional[datetime] = None + double_authorized: bool = Field(default=False) + double_authorized_by: Optional[int] = Field(default=None, foreign_key="user.id") + double_authorized_at: Optional[datetime] = None + unauth_reason: Optional[str] = Field(default=None) + + order: Order = Relationship(back_populates="result") + details: List["ResultDetail"] = Relationship(back_populates="result") + + +class ResultDetail(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + result_id: int = Field(foreign_key="result.id") + parameter_id: int = Field(foreign_key="parameter.id") + result_value: Optional[str] = Field(default=None) + rerun_result: Optional[str] = Field(default=None) + flag: Optional[str] = None + device_id: Optional[int] = Field(default=None, foreign_key="device.id") + remark: Optional[str] = Field(default=None) + + result: Result = Relationship(back_populates="details") + parameter: Parameter = Relationship() diff --git a/app/models/package.py b/app/models/package.py new file mode 100644 index 0000000000000000000000000000000000000000..2355a85248adbb60c9b69dd733a4ca67efaca4a3 --- /dev/null +++ b/app/models/package.py @@ -0,0 +1,49 @@ +# app/models/package.py +# Package, PackageTest, and Partner models. + +from typing import Optional, List +from datetime import datetime +from sqlmodel import SQLModel, Field, Relationship + + +class Partner(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + partner_name: str = Field(unique=True, index=True) + partner_note: Optional[str] = None + partner_contact: Optional[str] = None + partner_weight: Optional[float] = Field(default=None) + is_active: bool = Field(default=True) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + + +class Package(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + package_name: str = Field(unique=True, index=True) + package_short_name: str + price: float + package_note: Optional[str] = None + is_active: bool = Field(default=True) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + + package_tests: List["PackageTest"] = Relationship(back_populates="package") + + +class PackageTest(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + package_id: int = Field(foreign_key="package.id") + test_id: int = Field(foreign_key="testdefinition.id") + + package: Package = Relationship(back_populates="package_tests") + test: "TestDefinition" = Relationship() diff --git a/app/models/patient.py b/app/models/patient.py new file mode 100644 index 0000000000000000000000000000000000000000..e6faa4854f7c4cec33fb7adf81adc5aaeb044faf --- /dev/null +++ b/app/models/patient.py @@ -0,0 +1,93 @@ +# app/models/patient.py +# Patient, PatientVisit, and Attachment models. + +from typing import Optional, List +from datetime import datetime +from sqlmodel import SQLModel, Field, Relationship + + +class Patient(SQLModel, table=True): + __tablename__ = "patient" + + id: Optional[int] = Field(default=None, primary_key=True) + patient_id: str = Field(unique=True, index=True) + full_name: str = Field() + gender: str = Field() + age: Optional[int] = Field(default=None) + age_unit: Optional[str] = Field(default="year") + date_of_birth: Optional[datetime] = None + phone_key: str = Field() + phone_number: str = Field() + weight: Optional[float] = Field(default=None) + height: Optional[float] = Field(default=None) + province_id: Optional[int] = Field(default=None, foreign_key="province.id") + region_id: Optional[int] = Field(default=None, foreign_key="region.id") + fasting_time: Optional[int] = Field(default=None) + note: Optional[str] = Field(default=None) + email: Optional[str] = Field(default=None) + diagnosis: Optional[str] = Field(default=None) + symptoms: Optional[str] = Field(default=None) + therapy: Optional[str] = Field(default=None) + partner_id: Optional[int] = Field(default=None, foreign_key="partner.id") + doctor: Optional[str] = Field(default=None) + skin_colour: Optional[str] = Field(default=None) + agent_name: Optional[str] = Field(default=None) + is_outlab: bool = Field(default=False) + is_active: bool = Field(default=True) + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + deleted_reason: Optional[str] = Field(default=None) + + # Relationships + visits: List["PatientVisit"] = Relationship(back_populates="patient", cascade_delete=True) + orders: List["Order"] = Relationship(back_populates="patient") + + +class PatientVisit(SQLModel, table=True): + __tablename__ = "patientvisit" + + id: Optional[int] = Field(default=None, primary_key=True) + visit_id: str = Field(index=True) + patient_id: int = Field(foreign_key="patient.id") + visit_date: datetime = Field(default_factory=datetime.now) + is_active: bool = Field(default=True) + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + + # Payment fields + received_amount: float = Field(default=0.0) + discount_amount: float = Field(default=0.0) + discount_percentage: float = Field(default=0.0) + discount_note: Optional[str] = Field(default=None) + tax_applied: bool = Field(default=True) + tax_amount: float = Field(default=0.0) + remaining_amount: float = Field(default=0.0) + + # Call Centre fields + is_called: bool = Field(default=False) + is_whatsapp_sent: bool = Field(default=False) + is_printed: bool = Field(default=False) + + # Relationships + patient: Optional["Patient"] = Relationship(back_populates="visits") + orders: List["Order"] = Relationship(back_populates="visit") + + +class Attachment(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + patient_id: int = Field(foreign_key="patient.id", index=True) + visit_id: Optional[int] = Field(default=None, foreign_key="patientvisit.id", index=True) + file_name: str + file_path: str + file_type: str + description: Optional[str] = None + uploaded_by: int = Field(foreign_key="user.id") + uploaded_at: datetime = Field(default_factory=datetime.now) diff --git a/app/models/test.py b/app/models/test.py new file mode 100644 index 0000000000000000000000000000000000000000..79046a4753ddbfcabdd45d7d98adba969aaa9769 --- /dev/null +++ b/app/models/test.py @@ -0,0 +1,120 @@ +# app/models/test.py +# Test definition, test-device/parameter links, ranges, and result types. + +from typing import Optional, List +from datetime import datetime +from sqlmodel import SQLModel, Field, Relationship + +from app.models.department import Department, SampleType, ReportNote, Device, Parameter + + +class TestDefinition(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + test_name: str = Field(unique=True, index=True) + test_short_name: str + department_id: int = Field(foreign_key="department.id") + sample_type_id: int = Field(foreign_key="sampletype.id") + report_note_id: Optional[int] = Field(default=None, foreign_key="reportnote.id") + price: float + test_note: Optional[str] = None + test_condition: Optional[str] = None + is_available: bool = Field(default=True) + print_separately: bool = Field(default=False) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + + # Relationships + department: Department = Relationship() + sample_type: SampleType = Relationship() + report_note: Optional[ReportNote] = Relationship() + test_devices: List["TestDevice"] = Relationship(back_populates="test") + test_parameters: List["TestParameter"] = Relationship(back_populates="test") + + +class TestDevice(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + test_id: int = Field(foreign_key="testdefinition.id") + device_id: int = Field(foreign_key="device.id") + + test: TestDefinition = Relationship(back_populates="test_devices") + device: Device = Relationship() + + +class TestParameter(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + test_id: int = Field(foreign_key="testdefinition.id") + parameter_id: int = Field(foreign_key="parameter.id") + + test: TestDefinition = Relationship(back_populates="test_parameters") + parameter: Parameter = Relationship() + + +class TestRange(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + test_id: int = Field(foreign_key="testdefinition.id") + parameter_id: Optional[int] = Field(default=None, foreign_key="parameter.id") + device_id: Optional[int] = Field(default=None, foreign_key="device.id") + unit: str = Field(default="") + gender_type: str = Field(default="both") + age_from: int = Field(default=0) + age_from_unit: str = Field(default="year") + age_to: int = Field(default=999) + age_to_unit: str = Field(default="year") + age_unit: str = Field(default="year") + fasting_required: bool = Field(default=False) + range_type: str = Field(default="number") + + normal_from: Optional[float] = Field(default=None) + normal_to: Optional[float] = Field(default=None) + vlow_from: Optional[float] = Field(default=None) + vlow_to: Optional[float] = Field(default=None) + low_from: Optional[float] = Field(default=None) + low_to: Optional[float] = Field(default=None) + midlow_from: Optional[float] = Field(default=None) + midlow_to: Optional[float] = Field(default=None) + midhigh_from: Optional[float] = Field(default=None) + midhigh_to: Optional[float] = Field(default=None) + high_from: Optional[float] = Field(default=None) + high_to: Optional[float] = Field(default=None) + vhigh_from: Optional[float] = Field(default=None) + vhigh_to: Optional[float] = Field(default=None) + panic_less_than: Optional[float] = Field(default=None) + panic_more_than: Optional[float] = Field(default=None) + + text_range: Optional[str] = Field(default=None) + is_active: bool = Field(default=True) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + + test: TestDefinition = Relationship() + parameter: Optional[Parameter] = Relationship() + device: Optional[Device] = Relationship() + + +class TestResultType(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + test_id: int = Field(foreign_key="testdefinition.id") + parameter_id: Optional[int] = Field(default=None, foreign_key="parameter.id") + result_type: str = Field(default="number") + selection_options: Optional[str] = Field(default=None) + is_active: bool = Field(default=True) + + created_by: Optional[int] = Field(default=None, foreign_key="user.id") + created_at: datetime = Field(default_factory=datetime.now) + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + deleted_by: Optional[int] = Field(default=None, foreign_key="user.id") + deleted_at: Optional[datetime] = None + + test: TestDefinition = Relationship() + parameter: Optional[Parameter] = Relationship() diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000000000000000000000000000000000000..8fcf5d2b1154c89d58e41e417523ed42b47a5520 --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,39 @@ +# app/models/user.py +# User authentication and permission models. + +from typing import Optional +from datetime import datetime +from sqlmodel import SQLModel, Field + + +class User(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + username: str = Field(unique=True, index=True) + full_name: str + role: str = Field(default="receptionist") + hashed_password: str + is_active: bool = Field(default=True) + created_at: datetime = Field(default_factory=datetime.now) + last_seen: Optional[datetime] = None + is_online: bool = Field(default=False) + + # Security & Session Fields + failed_login_attempts: int = Field(default=0) + locked_until: Optional[datetime] = None + session_token: Optional[str] = None + + # Profile Fields + date_of_birth: Optional[datetime] = None + phone_number: Optional[str] = None + address: Optional[str] = None + + # Audit Fields + edited_by: Optional[int] = Field(default=None, foreign_key="user.id") + edited_at: Optional[datetime] = None + + +class UserPermission(SQLModel, table=True): + id: Optional[int] = Field(default=None, primary_key=True) + user_id: int = Field(foreign_key="user.id", index=True) + page_key: str = Field(index=True) + allowed_buttons: Optional[str] = Field(default=None) # JSON array of button keys diff --git a/app/routes/__init__.py b/app/routes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..405070a6cc3719e9f8b1cd6844f930f17f304bf5 --- /dev/null +++ b/app/routes/__init__.py @@ -0,0 +1,2 @@ +# app/routes/__init__.py +# Presentation layer routes package. diff --git a/app/routes/template_helpers.py b/app/routes/template_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..aa8126fa03c130f708eb3c9693b780f2970bb8f0 --- /dev/null +++ b/app/routes/template_helpers.py @@ -0,0 +1,94 @@ +# app/routes/template_helpers.py +# Template system with auto-injection of user context and permissions. + +import os +import json +from fastapi.templating import Jinja2Templates +from sqlmodel import Session, select + +from app.config import TEMPLATE_DIR +from app.database import engine +from app.models import UserPermission, LabInfo +from app.services.auth_service import get_current_user + + +_base_templates = Jinja2Templates(directory=TEMPLATE_DIR) + + +class AutoUserTemplates: + """Wrapper that auto-injects current_user, has_page(), has_button() into every template.""" + + def __init__(self, base): + self.base = base + self.env = base.env + + def TemplateResponse(self, name, context, **kwargs): + request = context.get("request") + + try: + with Session(engine) as sess: + # Resolve current_user + if "current_user" not in context and request: + user = get_current_user(request, sess) + if user: + sess.expunge(user) + context["current_user"] = user + else: + context["current_user"] = None + + if "current_user" not in context: + context["current_user"] = None + + # Load permissions + current_user = context.get("current_user") + is_admin = current_user and (current_user.role == "admin" or current_user.username == "admin") + + user_perms = {} + if current_user and not is_admin: + perms = sess.exec( + select(UserPermission).where(UserPermission.user_id == current_user.id) + ).all() + for p in perms: + buttons = [] + if p.allowed_buttons: + try: + buttons = json.loads(p.allowed_buttons) + except Exception: + buttons = [] + user_perms[p.page_key] = buttons + + # Inject global lab_name + if "global_lab_name" not in context: + lab_info_obj = sess.exec(select(LabInfo).limit(1)).first() + context["global_lab_name"] = lab_info_obj.lab_name if lab_info_obj and lab_info_obj.lab_name else "" + except Exception: + if "current_user" not in context: + context["current_user"] = None + current_user = context.get("current_user") + is_admin = current_user and (current_user.role == "admin" or current_user.username == "admin") + user_perms = {} + if "global_lab_name" not in context: + context["global_lab_name"] = "" + + # Permission helpers for Jinja templates + def has_page(page_key): + if is_admin: + return True + return page_key in user_perms + + def has_button(page_key, button_key): + if is_admin: + return True + if page_key not in user_perms: + return False + return button_key in user_perms[page_key] + + context["has_page"] = has_page + context["has_button"] = has_button + context["is_admin"] = is_admin + context["user_perms"] = user_perms + + return self.base.TemplateResponse(name, context, **kwargs) + + +templates = AutoUserTemplates(_base_templates) diff --git a/app/services/__init__.py b/app/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4ac75f0be529e5b524d000a3dbba9cb18fb046 --- /dev/null +++ b/app/services/__init__.py @@ -0,0 +1,2 @@ +# app/services/__init__.py +# Business logic services package. diff --git a/app/services/audit_service.py b/app/services/audit_service.py new file mode 100644 index 0000000000000000000000000000000000000000..2d230cb03571df39942f08521b0f32a49e30d841 --- /dev/null +++ b/app/services/audit_service.py @@ -0,0 +1,74 @@ +# app/services/audit_service.py +# Audit logging, activity logging, and archival services. + +from datetime import datetime +import json +from sqlmodel import Session + +from app.models import AuditLog, DeletedRecord, ActivityLog + + +def log_audit_action(session: Session, table_name: str, record_id: int, action: str, + current_user, old_values: dict = None, new_values: dict = None): + """Universal Audit Logger. Safely wraps in try/except to never crash the caller.""" + try: + username = "System" + user_id = None + if current_user: + user_id = current_user.id + username = getattr(current_user, 'full_name', current_user.username) + + log_entry = AuditLog( + table_name=table_name.lower(), + record_id=record_id, + action=action.upper(), + user_id=user_id, + username=username, + old_values=json.dumps(old_values) if old_values else None, + new_values=json.dumps(new_values) if new_values else None, + created_at=datetime.now() + ) + session.add(log_entry) + except Exception as e: + print(f"Warning: Audit Log Failure: {str(e)}") + + +# Backwards-compatible alias +create_audit_log = log_audit_action + + +def archive_deleted_record(session: Session, source_table: str, record_id: int, + record_data: dict, current_user, deleted_reason: str = None): + """Saves a JSON snapshot of a record before soft or hard deletion.""" + try: + user_id = current_user.id if hasattr(current_user, 'id') else 0 + archive = DeletedRecord( + source_table=source_table, + record_id=record_id, + record_data=json.dumps(record_data), + deleted_by=user_id, + deleted_reason=deleted_reason + ) + session.add(archive) + except Exception as e: + print(f"Warning: Failed to archive deleted record: {str(e)}") + + +def log_activity_action(session: Session, action_type: str, description: str, + current_user, target_type: str = None, target_id: int = None): + """Logs non-data operational events (logins, printing, etc.).""" + try: + user_id = current_user.id if hasattr(current_user, 'id') else None + username = getattr(current_user, 'full_name', getattr(current_user, 'username', "System")) + + activity = ActivityLog( + action_type=action_type.upper(), + description=description, + user_id=user_id, + username=username, + target_type=target_type, + target_id=target_id + ) + session.add(activity) + except Exception as e: + print(f"Warning: Activity Log Failure: {str(e)}") diff --git a/app/services/auth_service.py b/app/services/auth_service.py new file mode 100644 index 0000000000000000000000000000000000000000..c826c83fb5ba7e023c471167ebe062b56fcde41b --- /dev/null +++ b/app/services/auth_service.py @@ -0,0 +1,48 @@ +# app/services/auth_service.py +# Authentication helpers: session validation, user lookup, inactivity timeout. + +import logging +from fastapi import Request +from sqlmodel import Session +from datetime import datetime, timedelta +from typing import Optional +from itsdangerous import URLSafeSerializer + +from app.config import SECRET_KEY +from app.models import User + + +def get_current_user(request: Request, session: Session) -> Optional[User]: + """Get current logged-in user from session cookie.""" + try: + s = URLSafeSerializer(SECRET_KEY) + cookie = request.cookies.get("nexlab_session") + if not cookie: + return None + data = s.loads(cookie) + user_id = data.get("user_id") + session_token = data.get("session_token") + + if user_id and session_token: + user = session.get(User, user_id) + if user and user.session_token == session_token: + # Check inactivity timeout (2 hours) + if user.last_seen and (datetime.now() - user.last_seen) > timedelta(hours=2): + user.session_token = None + session.commit() + return None + + # Update last_seen if > 5 mins to avoid spamming DB + if not user.last_seen or (datetime.now() - user.last_seen) > timedelta(minutes=5): + user.last_seen = datetime.now() + session.commit() + + return user + except Exception as e: + logging.error(f"Auth error in get_current_user: {e}") + return None + + +def login_required(request: Request, session: Session) -> Optional[User]: + """Check if user is logged in, return user or None.""" + return get_current_user(request, session) diff --git a/app/services/barcode_image_service.py b/app/services/barcode_image_service.py new file mode 100644 index 0000000000000000000000000000000000000000..5423fd0e1ccdacd710387f7ffec183e7932ce3be --- /dev/null +++ b/app/services/barcode_image_service.py @@ -0,0 +1,206 @@ +# app/services/barcode_image_service.py +# Generates barcode label as a high-DPI PNG image (Pillow + python-barcode). +# Same approach as NaseemPrint (ZXing + System.Drawing) — +# renders directly as a bitmap at thermal printer DPI. + +import io +import json +import os +import re +from PIL import Image, ImageDraw, ImageFont +import barcode +from barcode.writer import ImageWriter + +import arabic_reshaper +from bidi.algorithm import get_display +from app.config import STATIC_DIR + + +PRINTER_DPI = 203 # Standard thermal label printer DPI + + +def parse_css_to_inches(dim_str): + """Convert CSS dimension string to inches.""" + if not dim_str: + return 0 + dim_str = str(dim_str).strip().lower() + match = re.match(r'^([\d\.]+)\s*([a-z]*)$', dim_str) + if not match: + return 0 + val, unit = float(match.group(1)), match.group(2) + if unit == 'mm': + return val / 25.4 + elif unit == 'cm': + return val / 2.54 + elif unit == 'in': + return val + elif unit == 'px': + return val / 96.0 + return val / 96.0 # assume px + + +def generate_barcode_label_image(patient, tests_by_sample_type, template, visit_id='', visit_date='', dpi=PRINTER_DPI): + """ + Generate barcode label as a high-DPI PNG image. + Returns: list of BytesIO objects (one PNG per sample type/page). + """ + # Label dimensions in pixels at target DPI + width_in = parse_css_to_inches(template.paper_width) or 4.0 + height_in = parse_css_to_inches(template.paper_height) or 2.0 + img_w = int(width_in * dpi) + img_h = int(height_in * dpi) + + # Scale factor: template coordinates are in CSS pixels (96 DPI) + scale = dpi / 96.0 + + elements = json.loads(template.elements) if template.elements else [] + + # Load font + font_path = os.path.join(STATIC_DIR, 'vendor', 'fonts', 'Cairo-600.ttf') + if not os.path.exists(font_path): + font_path = None + + # Arabic reshaper + try: + reshaper_config = arabic_reshaper.config_for_true_type_font(font_path) if font_path else None + except Exception: + reshaper_config = None + reshaper = arabic_reshaper.ArabicReshaper(configuration=reshaper_config) if reshaper_config else arabic_reshaper.ArabicReshaper() + + sample_types = list(tests_by_sample_type.keys()) or ['Unknown'] + pages = [] + + for sample_type in sample_types: + test_names = tests_by_sample_type.get(sample_type, []) + tests_str = ", ".join(test_names) if test_names else '' + + # Create blank white label + img = Image.new('1', (img_w, img_h), 1) # mode='1' = 1-bit B&W, 1=white + draw = ImageDraw.Draw(img) + + for el in elements: + el_type = el.get('type', '') + x = int(el.get('x', 0) * scale) + y = int(el.get('y', 0) * scale) + w = int(el.get('width', 100) * scale) + h = int(el.get('height', 20) * scale) + font_size = max(6, int(el.get('fontSize', 11) * scale)) + + if el_type == 'barcode_image': + # Generate Code128 barcode — bars only, text drawn separately for full control + try: + show_text = el.get('showBarcodeText', True) + code128 = barcode.get('code128', str(patient.patient_id), writer=ImageWriter()) + bc_buffer = io.BytesIO() + code128.write(bc_buffer, options={ + 'module_width': 0.5, # thick bars + 'module_height': 20, # tall bars in mm + 'write_text': False, + 'quiet_zone': 1, + 'dpi': dpi, + }) + bc_buffer.seek(0) + bc_img = Image.open(bc_buffer).convert('1') + + # Crop white padding so bars fill the element properly + crop_box = bc_img.getbbox() + if crop_box: + bc_img = bc_img.crop(crop_box) + + # Scale to fill element box + bc_ratio = min(w / bc_img.width, h / bc_img.height) + new_w = int(bc_img.width * bc_ratio) + new_h = int(bc_img.height * bc_ratio) + bc_img = bc_img.resize((new_w, new_h), Image.NEAREST) + + # Paste bars centered in element box + paste_x = x + (w - new_w) // 2 + paste_y = y + img.paste(bc_img, (paste_x, paste_y)) + + # Draw patient ID text BELOW the element box + if show_text: + try: + id_font = ImageFont.truetype(font_path, max(8, int(7 * scale))) if font_path else ImageFont.load_default() + except Exception: + id_font = ImageFont.load_default() + id_text = str(patient.patient_id) + bbox = draw.textbbox((0, 0), id_text, font=id_font) + tw = bbox[2] - bbox[0] + text_x = x + (w - tw) // 2 # centered under bars + text_y = y + h + 0.5 # minimal gap below bars + draw.text((text_x, text_y), id_text, fill=0, font=id_font) + except Exception as e: + # Fallback: draw placeholder + draw.rectangle([x, y, x + w, y + h], outline=0) + draw.text((x + 5, y + 5), f"BC:{patient.patient_id}", fill=0) + continue + + # Text elements + txt = '' + if el_type == 'patient_name': + txt = str(patient.full_name or '') + elif el_type == 'patient_id': + txt = str(patient.patient_id or '') + elif el_type == 'patient_gender': + txt = str(patient.gender or '') + elif el_type == 'patient_age': + txt = f"{patient.age or 0} {patient.age_unit or 'year'}" + elif el_type == 'patient_phone': + txt = f"{patient.phone_key or ''} {patient.phone_number or ''}".strip() + elif el_type == 'sample_type': + txt = sample_type + elif el_type == 'test_list': + txt = tests_str + elif el_type == 'test_name': + txt = test_names[0] if test_names else '' + elif el_type == 'visit_id': + txt = str(visit_id or '') + elif el_type == 'visit_date': + txt = str(visit_date or '') + elif el_type == 'lab_name': + txt = el.get('label', '') + elif el_type == 'custom_text': + txt = el.get('customText', el.get('label', '')) + else: + txt = el.get('label', '') + + if not txt: + continue + + # Arabic text reshaping + try: + reshaped = reshaper.reshape(txt) + display_txt = get_display(reshaped) + except Exception: + display_txt = txt + + # Load font at the correct size + try: + pil_font = ImageFont.truetype(font_path, font_size) if font_path else ImageFont.load_default() + except Exception: + pil_font = ImageFont.load_default() + + # Calculate text position based on alignment + align = el.get('align', 'left') + bbox = draw.textbbox((0, 0), display_txt, font=pil_font) + text_w = bbox[2] - bbox[0] + text_h = bbox[3] - bbox[1] + text_y = y + (h - text_h) // 2 + + if align == 'center': + text_x = x + (w - text_w) // 2 + elif align == 'right': + text_x = x + w - text_w + else: + text_x = x + 5 # small padding + + draw.text((text_x, text_y), display_txt, fill=0, font=pil_font) + + # Convert to PNG bytes + buf = io.BytesIO() + img.save(buf, format='PNG', dpi=(dpi, dpi)) + buf.seek(0) + pages.append(buf) + + return pages diff --git a/app/services/barcode_service.py b/app/services/barcode_service.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3ad5b57cbe9043e8b069f625a8dd6635201203 --- /dev/null +++ b/app/services/barcode_service.py @@ -0,0 +1,20 @@ +# app/services/barcode_service.py +# Barcode generation utilities. + +import io +import base64 + +import barcode +from barcode.writer import ImageWriter + + +def generate_barcode_base64(patient_id: str) -> str: + """Generate a Code128 barcode as a base64-encoded PNG string.""" + try: + code128 = barcode.get_barcode_class('code128') + rv = io.BytesIO() + code128(str(patient_id), writer=ImageWriter()).write(rv) + rv.seek(0) + return base64.b64encode(rv.read()).decode('utf-8') + except Exception: + return "" diff --git a/app/services/patient_service.py b/app/services/patient_service.py new file mode 100644 index 0000000000000000000000000000000000000000..da8d648a154f58a53024716138f7f28622337596 --- /dev/null +++ b/app/services/patient_service.py @@ -0,0 +1,180 @@ +# app/services/patient_service.py +# Patient-related business logic: query builders, data helpers. + +from datetime import datetime +from sqlmodel import Session, select +from sqlalchemy.orm import selectinload + +from app.models import Patient, PatientVisit, Order, TestDefinition + + +def calculate_age(dob: datetime) -> int: + """Calculate age from date of birth.""" + if dob is None: + return 0 + today = datetime.today() + return today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day)) + + +def age_to_days(age, unit: str) -> int: + """Convert age and unit to days for consistent comparison.""" + if age is None or age == "": + return 0 + age = int(age) + u = (unit or "year").lower() + if "year" in u: + return age * 365 + elif "month" in u: + return age * 30 + elif "day" in u: + return age + return age * 365 + + +def model_to_dict(model): + """Convert SQLModel object to dict.""" + if model is None: + return None + data = {} + for column in model.__table__.columns.keys(): + value = getattr(model, column) + if isinstance(value, datetime): + data[column] = value.isoformat() + else: + data[column] = value + return data + + +def build_patient_visit_data(session, request, status_filter=None, defaults_today=True): + """ + Shared helper to build patient_data list for patient list pages. + Eliminates N+1 queries by fetching visits directly with eager-loaded orders. + Supports pagination via ?page= query param. + + Returns: (patient_data, filters, page, total_pages, total_count) + """ + PAGE_SIZE = 50 + + today_str = datetime.today().strftime("%Y-%m-%d") if defaults_today else "" + start_date = request.query_params.get("start_date", today_str) + end_date = request.query_params.get("end_date", today_str) + name = request.query_params.get("name", "") + patient_id_q = request.query_params.get("patient_id", "") + test_q = request.query_params.get("test", "") + status_q = status_filter or request.query_params.get("status", "all") + + # Pagination + try: + page = max(1, int(request.query_params.get("page", 1))) + except (ValueError, TypeError): + page = 1 + + # Single query: fetch visits with eager-loaded patient and orders + visit_query = ( + select(PatientVisit) + .options( + selectinload(PatientVisit.patient), + selectinload(PatientVisit.orders).selectinload(Order.test) + ) + .join(Patient, PatientVisit.patient_id == Patient.id) + .where(Patient.is_active == True) + ) + + if start_date: + visit_query = visit_query.where(PatientVisit.visit_date >= datetime.strptime(f"{start_date} 00:00:00", "%Y-%m-%d %H:%M:%S")) + if end_date: + visit_query = visit_query.where(PatientVisit.visit_date <= datetime.strptime(f"{end_date} 23:59:59", "%Y-%m-%d %H:%M:%S")) + if name: + visit_query = visit_query.where(Patient.full_name.ilike(f"%{name}%")) + if patient_id_q: + visit_query = visit_query.where(Patient.patient_id.ilike(f"%{patient_id_q}%")) + + if test_q: + visit_query = visit_query.join(Order, Order.visit_id == PatientVisit.id).join( + TestDefinition, Order.test_id == TestDefinition.id + ).where( + (TestDefinition.test_name.ilike(f"%{test_q}%")) | + (TestDefinition.test_short_name.ilike(f"%{test_q}%")) + ) + + if status_q != "all": + if not test_q: + visit_query = visit_query.join(Order, Order.visit_id == PatientVisit.id) + if status_q == "pending": + visit_query = visit_query.where(Order.status == "ordered") + elif status_q in ("received", "resulted"): + visit_query = visit_query.where(Order.status == "resulted") + elif status_q in ("authorize", "authorized"): + visit_query = visit_query.where(Order.status == "authorized") + elif status_q == "double_authorized": + visit_query = visit_query.where(Order.status == "double_authorized") + elif status_q == "AD": + visit_query = visit_query.where(Order.status.in_(["authorized", "double_authorized"])) + + visits = session.exec( + visit_query.distinct().order_by(PatientVisit.visit_date.desc()) + ).all() + + # Build one row per visit (no deduplication — each visit is shown separately) + all_patient_data = [] + + for visit in visits: + patient = visit.patient + if not patient: + continue + + # Build tests data from orders + packages = {} + standalones = [] + + for order in visit.orders: + if not order.test or order.status == "no_sample": + continue + + status_color = "red" + if order.status == "resulted": + status_color = "blue" + elif order.status == "authorized": + status_color = "green" + elif order.status == "double_authorized": + status_color = "purple" + + test_info = {"name": order.test.test_name, "color": status_color} + + if order.package_name: + if order.package_name not in packages: + packages[order.package_name] = [] + packages[order.package_name].append(test_info) + else: + standalones.append(test_info) + + tests_data = [] + for pkg_name, pkg_tests in packages.items(): + tests_data.append({"is_package": True, "package_name": pkg_name, "tests": pkg_tests}) + for t in standalones: + tests_data.append({"is_package": False, "test": t}) + + all_patient_data.append({ + "patient": patient, + "visit": visit, + "registration_date": visit.visit_date, + "tests": tests_data + }) + + # Pagination + total_count = len(all_patient_data) + total_pages = max(1, (total_count + PAGE_SIZE - 1) // PAGE_SIZE) + page = min(page, total_pages) + offset = (page - 1) * PAGE_SIZE + patient_data = all_patient_data[offset:offset + PAGE_SIZE] + + filters = { + "start_date": start_date, + "end_date": end_date, + "name": name, + "patient_id": patient_id_q, + "test": test_q, + "status": status_q, + } + + return patient_data, filters, page, total_pages, total_count diff --git a/app/services/pdf_service.py b/app/services/pdf_service.py new file mode 100644 index 0000000000000000000000000000000000000000..0cdee708489c4a478a4124b99470779a63ad6dff --- /dev/null +++ b/app/services/pdf_service.py @@ -0,0 +1,172 @@ +# app/services/pdf_service.py +# Native PDF generation for barcode labels using ReportLab. + +import io +import os +import json +from reportlab.pdfgen import canvas +from reportlab.lib.units import inch, mm +from reportlab.graphics.barcode import code128 +from reportlab.pdfbase import pdfmetrics +from reportlab.pdfbase.ttfonts import TTFont +import arabic_reshaper +from bidi.algorithm import get_display + +from app.config import STATIC_DIR + + +def parse_pt(dim_str): + """Convert CSS dimension to PDF points.""" + if not dim_str: + return 0 + dim_str = str(dim_str).strip().lower() + import re + match = re.match(r'^([\d\.]+)\s*([a-z]*)$', dim_str) + if not match: + return 0 + val, unit = float(match.group(1)), match.group(2) + if unit == 'mm': + return val * 2.83465 + elif unit == 'cm': + return val * 28.3465 + elif unit == 'in': + return val * 72.0 + elif unit == 'px': + return val * 0.75 + return val + + +def generate_native_barcode_pdf(patient, tests_by_sample_type, template, visit_id='', visit_date=''): + """ + Generate a pure vector PDF using ReportLab natively. + Coordinates are converted from CSS screen pixels (96dpi) to PDF points (72dpi). + Returns: BytesIO object containing the PDF. + """ + buffer = io.BytesIO() + + width_pt = parse_pt(template.paper_width) or (2.0 * 72.0) + height_pt = parse_pt(template.paper_height) or (1.0 * 72.0) + margin_pt = parse_pt(template.margin) if template.margin else 0 + + c = canvas.Canvas(buffer, pagesize=(width_pt, height_pt)) + + # Font registry + font_path = os.path.join(STATIC_DIR, 'vendor', 'fonts', 'Cairo-600.ttf') + if os.path.exists(font_path): + try: + pdfmetrics.registerFont(TTFont('ArabicFont', font_path)) + font_name = 'ArabicFont' + except Exception: + font_name = 'Helvetica' + else: + font_name = 'Helvetica' + + elements = json.loads(template.elements) if template.elements else [] + + # Arabic reshaper + try: + reshaper_config = arabic_reshaper.config_for_true_type_font(font_path) if os.path.exists(font_path) else None + except Exception: + reshaper_config = None + reshaper = arabic_reshaper.ArabicReshaper(configuration=reshaper_config) if reshaper_config else arabic_reshaper.ArabicReshaper() + + PX_TO_PT = 72.0 / 96.0 + + sample_types = list(tests_by_sample_type.keys()) or ['Unknown'] + + for sample_type in sample_types: + test_names = tests_by_sample_type.get(sample_type, []) + tests_str = ", ".join(test_names) if test_names else '' + + for el in elements: + el_type = el.get('type', '') + + x_pt = el.get('x', 0) * PX_TO_PT + margin_pt + y_top_pt = el.get('y', 0) * PX_TO_PT + margin_pt + el_w_pt = el.get('width', 100) * PX_TO_PT + el_h_pt = el.get('height', 20) * PX_TO_PT + font_size_pt = el.get('fontSize', 11) * PX_TO_PT + align = el.get('align', 'left') + color_hex = el.get('color', '#000000').lstrip('#') + + try: + r = int(color_hex[0:2], 16) / 255.0 + g = int(color_hex[2:4], 16) / 255.0 + b = int(color_hex[4:6], 16) / 255.0 + c.setFillColorRGB(r, g, b) + except Exception: + c.setFillColorRGB(0, 0, 0) + + pdf_y = height_pt - y_top_pt - el_h_pt + + if el_type == 'barcode_image': + bc_height = el_h_pt * 0.85 + show_text = el.get('showBarcodeText', True) + bc = code128.Code128( + str(patient.patient_id), + barHeight=bc_height, + barWidth=max(0.5, el.get('barcodeScale', 3) * 0.2), + humanReadable=bool(show_text) + ) + bc_width = bc.width + if align == 'center': + draw_x = x_pt + (el_w_pt - bc_width) / 2 + elif align == 'right': + draw_x = x_pt + el_w_pt - bc_width + else: + draw_x = x_pt + bc.drawOn(c, draw_x, height_pt - y_top_pt - bc_height) + continue + + txt = '' + if el_type == 'patient_name': + txt = str(patient.full_name or '') + elif el_type == 'patient_id': + txt = str(patient.patient_id or '') + elif el_type == 'patient_gender': + txt = str(patient.gender or '') + elif el_type == 'patient_age': + txt = f"{patient.age or 0} {patient.age_unit or 'year'}" + elif el_type == 'patient_phone': + txt = f"{patient.phone_key or ''} {patient.phone_number or ''}".strip() + elif el_type == 'sample_type': + txt = sample_type + elif el_type == 'test_list': + txt = tests_str + elif el_type == 'test_name': + txt = test_names[0] if test_names else '' + elif el_type == 'visit_id': + txt = str(visit_id or '') + elif el_type == 'visit_date': + txt = str(visit_date or '') + elif el_type == 'lab_name': + txt = el.get('label', '') + elif el_type == 'custom_text': + txt = el.get('customText', el.get('label', '')) + else: + txt = el.get('label', '') + + if not txt: + continue + + try: + reshaped = reshaper.reshape(txt) + display_txt = get_display(reshaped) + except Exception: + display_txt = txt + + c.setFont(font_name, max(4, font_size_pt)) + text_y = pdf_y + (el_h_pt - font_size_pt) / 2 + + if align == 'center': + c.drawCentredString(x_pt + el_w_pt / 2, text_y, display_txt) + elif align == 'right': + c.drawRightString(x_pt + el_w_pt, text_y, display_txt) + else: + c.drawString(x_pt, text_y, display_txt) + + c.showPage() + + c.save() + buffer.seek(0) + return buffer diff --git a/app/services/permission_service.py b/app/services/permission_service.py new file mode 100644 index 0000000000000000000000000000000000000000..aa194b55e0455d8da514d6afebe14cb2b864447d --- /dev/null +++ b/app/services/permission_service.py @@ -0,0 +1,44 @@ +# app/services/permission_service.py +# Permission checking for page/button access control. + +from fastapi import Request +from sqlmodel import Session, select +import json + +from app.services.auth_service import get_current_user +from app.models import UserPermission + + +def require_permission(request: Request, session: Session, page_key: str, button_key: str = None) -> bool: + """Verifies if the current user has the specified page/button permission.""" + user = get_current_user(request, session) + if not user: + return False + + # Admins always have all permissions + if user.role == 'admin' or user.username == 'admin': + return True + + # Check page permission + perms = session.exec( + select(UserPermission).where( + UserPermission.user_id == user.id, + UserPermission.page_key == page_key + ) + ).first() + + if not perms: + return False + + # Check specific button permission if requested + if button_key: + if not perms.allowed_buttons: + return False + try: + buttons = json.loads(perms.allowed_buttons) + if button_key not in buttons: + return False + except Exception: + return False + + return True diff --git a/backup_db.py b/backup_db.py new file mode 100644 index 0000000000000000000000000000000000000000..2205bf77d45b5bc3c81970924c3f529b2965449b --- /dev/null +++ b/backup_db.py @@ -0,0 +1,63 @@ +import os +import sqlite3 +from datetime import datetime + +def backup_database(): + """ + Safe database backup using SQLite's built-in backup API. + Unlike shutil.copy2, this handles active connections and WAL mode correctly, + producing a consistent, non-corrupted backup every time. + """ + project_root = os.path.dirname(os.path.abspath(__file__)) + db_file = os.path.join(project_root, "lab_database.db") + backup_dir = os.path.join(project_root, "backups") + + if not os.path.exists(db_file): + print(f"❌ Error: Database file '{db_file}' not found.") + return False + + if not os.path.exists(backup_dir): + os.makedirs(backup_dir) + print(f"📁 Created backup directory: {backup_dir}") + + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + backup_file = os.path.join(backup_dir, f"lab_database_{timestamp}.db") + + try: + # Connect to the live database + source = sqlite3.connect(db_file) + # Connect to the backup destination + dest = sqlite3.connect(backup_file) + + # Use SQLite's built-in backup API — safe even during active writes + source.backup(dest) + + dest.close() + source.close() + + size_mb = os.path.getsize(backup_file) / (1024 * 1024) + print(f"✅ Success: Database backed up to {backup_file} ({size_mb:.2f} MB)") + + # Cleanup: keep only last 30 backups + cleanup_old_backups(backup_dir, keep=30) + + return True + except Exception as e: + print(f"❌ Error during backup: {e}") + return False + +def cleanup_old_backups(backup_dir, keep=30): + """Remove old backups, keeping only the most recent 'keep' files.""" + try: + backups = sorted( + [f for f in os.listdir(backup_dir) if f.startswith("lab_database_") and f.endswith(".db")], + reverse=True + ) + for old_backup in backups[keep:]: + os.remove(os.path.join(backup_dir, old_backup)) + print(f"🗑️ Removed old backup: {old_backup}") + except Exception as e: + print(f"⚠️ Cleanup warning: {e}") + +if __name__ == "__main__": + backup_database() diff --git a/database.py b/database.py new file mode 100644 index 0000000000000000000000000000000000000000..8039dcaa630b78e4a863a71dc3fefaa798c17aea --- /dev/null +++ b/database.py @@ -0,0 +1,7 @@ +# database.py +# =================================================================== +# BACKWARD-COMPATIBLE BRIDGE — re-exports from app/database.py. +# Existing code can continue to use: from database import get_session, engine +# =================================================================== + +from app.database import engine, get_session, create_db_and_tables \ No newline at end of file diff --git a/deployment_guide.md b/deployment_guide.md new file mode 100644 index 0000000000000000000000000000000000000000..8642bf25c824fbd11209af1697e5085fde7446a3 --- /dev/null +++ b/deployment_guide.md @@ -0,0 +1,43 @@ +# NexLab LIS Deployment Guide (Server PC) + +This guide helps you move the NexLab Laboratory System to a new PC and set it up as a server for other machines in the lab. + +## Step 1: Copying the System +1. Locate the `NexLab_Published` folder created by the packager. +2. Copy this entire folder to your target PC (e.g., using a USB Drive). +3. Place it in a safe location (e.g., `C:\NexLab_LIS`). + +## Step 2: One-Time Set Up (Target PC) +1. Open the `NexLab_Published` folder on the new PC. +2. Double-click `install_requirements.bat`. This will: + - Create the virtual environment. + - Install all Python libraries. + - Download the PDF generation components (Playwright Chrome). + - *Note: This requires internet access the first time.* + +## Step 3: Running the System +1. Double-click `start_nexlab.bat`. +2. A window will open showing that the server is running. +3. You can access the system on this PC at: `http://localhost:8000` (or your chosen port). + +## Extra: How to Change the Port +If you need to change the port (e.g. to 5000 or 80): +1. Open `start_nexlab.bat` in Notepad. +2. Change the line `set "PORT=8000"` to your preferred number. +3. Save the file and restart the system. + +## Step 4: Connecting from Other PCs +1. find the **IP Address** of the Server PC: + - Open Command Prompt and type `ipconfig`. + - Look for "IPv4 Address" (e.g., `192.168.1.50`). +2. On any other PC in the lab, open a browser and go to: `http://192.168.1.50:8000`. + +## Step 5: (Optional) Automatic Start +1. To make the server start automatically when you log into Windows: +2. Double-click `add_to_startup.bat` once. + +--- +### Requirements for the Server PC: +- Windows 10/11. +- Python 3.10 or higher installed (one-time requirement for the environment setup). +- Port 8000 allowed in Windows Firewall (if connecting from other PCs). diff --git a/device_interfacing/CBC/failed/alh.txt b/device_interfacing/CBC/failed/alh.txt new file mode 100644 index 0000000000000000000000000000000000000000..bff8b946843b42a3119db8d47678e98c581200ed --- /dev/null +++ b/device_interfacing/CBC/failed/alh.txt @@ -0,0 +1,23 @@ +PID=1010008 +8=4.33 +10=52.9 +12=44.6 +16=1.5 +14=0.7 +18=0.3 +9=2.29 +11=1.93 +15=0.06 +13=0.03 +17=0.02 +2=4.28 +1=12.3 +6=31.2 +5=28.8 +4=92.3 +7=12.6 +3=39.5 +19=223 +20=9.8 + + diff --git a/device_interfacing/CBC/processed/20260426_204913_alh.txt b/device_interfacing/CBC/processed/20260426_204913_alh.txt new file mode 100644 index 0000000000000000000000000000000000000000..bff8b946843b42a3119db8d47678e98c581200ed --- /dev/null +++ b/device_interfacing/CBC/processed/20260426_204913_alh.txt @@ -0,0 +1,23 @@ +PID=1010008 +8=4.33 +10=52.9 +12=44.6 +16=1.5 +14=0.7 +18=0.3 +9=2.29 +11=1.93 +15=0.06 +13=0.03 +17=0.02 +2=4.28 +1=12.3 +6=31.2 +5=28.8 +4=92.3 +7=12.6 +3=39.5 +19=223 +20=9.8 + + diff --git a/device_interfacing/device_watcher.py b/device_interfacing/device_watcher.py new file mode 100644 index 0000000000000000000000000000000000000000..e19e28d6b955c6436de93c64e632f564d382294f --- /dev/null +++ b/device_interfacing/device_watcher.py @@ -0,0 +1,517 @@ +# device_interfacing/device_watcher.py +# ===================================================== +# NexLab Device Link — CBC Folder Watcher +# ===================================================== +# Standalone service that watches a folder for CBC device +# result files and writes them directly to the database. +# +# Usage: +# python device_interfacing/device_watcher.py +# +# File format expected: +# PID = 110003 +# 1=4.5 +# 2=23.3 +# +# Where PID is the patient_id and 1,2,... are parameter IDs. +# ===================================================== + +import os +import sys +import subprocess + +# Resolve the project root (parent of device_interfacing/) +PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + +# ===================================================== +# AUTO-DETECT VENV: If running with system Python, +# re-launch with the project's venv Python automatically. +# ===================================================== +VENV_PYTHON = os.path.join(PROJECT_ROOT, "venv", "Scripts", "python.exe") + +if os.path.exists(VENV_PYTHON) and sys.executable.lower() != VENV_PYTHON.lower(): + # We're NOT running inside the venv — re-launch with venv Python + print(f"Re-launching with venv Python: {VENV_PYTHON}") + result = subprocess.call([VENV_PYTHON, os.path.abspath(__file__)]) + sys.exit(result) + +# ===================================================== +# From here on, we're guaranteed to be in the venv +# ===================================================== +import time +import shutil +import logging +from datetime import datetime +from pathlib import Path + +# CRITICAL: Change working directory to project root BEFORE importing database. +# database.py uses a relative SQLite path (sqlite:///./lab_database.db), +# so CWD must be the project root for the DB to be found. +os.chdir(PROJECT_ROOT) +sys.path.insert(0, PROJECT_ROOT) + +from sqlmodel import Session, select +from database import engine +from models import ( + Patient, PatientVisit, Order, TestDefinition, TestParameter, + Result, ResultDetail, AuditLog, ActivityLog +) + +# ===================================================== +# CONFIGURATION — Edit these to match your environment +# ===================================================== +# Watch folder: where the CBC device drops .txt files +WATCH_FOLDER = r"C:\Users\aliss\Desktop\lab_system\device_interfacing\CBC" + +# How often to check for new files (seconds) — used in polling mode +POLL_INTERVAL = 3 + +# System user ID for audit trail (admin = 1) +SYSTEM_USER_ID = 1 +SYSTEM_USERNAME = "CBC_Device" + +# Log file +LOG_FILE = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "device_interfacing.log" +) + +# ===================================================== +# LOGGING SETUP +# ===================================================== +logger = logging.getLogger("NexLabDeviceLink") +logger.setLevel(logging.INFO) + +# File handler +file_handler = logging.FileHandler(LOG_FILE, encoding="utf-8") +file_handler.setFormatter(logging.Formatter( + "%(asctime)s [%(levelname)s] %(message)s", + datefmt="%Y-%m-%d %H:%M:%S" +)) +logger.addHandler(file_handler) + +# Console handler +console_handler = logging.StreamHandler() +console_handler.setFormatter(logging.Formatter( + "%(asctime)s [%(levelname)s] %(message)s", + datefmt="%H:%M:%S" +)) +logger.addHandler(console_handler) + + +# ===================================================== +# FILE PARSER +# ===================================================== +def parse_result_file(filepath: str) -> dict: + """ + Parse a CBC result text file. + + Expected format: + PID = 110003 + 1=4.5 + 2=23.3 + + Returns: + { + "patient_id": "110003", + "results": {1: "4.5", 2: "23.3"} + } + + Raises ValueError if format is invalid. + """ + patient_id = None + results = {} + + with open(filepath, "r", encoding="utf-8-sig") as f: + for line_num, raw_line in enumerate(f, start=1): + line = raw_line.strip() + if not line: + continue + + # Parse PID line + if line.upper().startswith("PID"): + parts = line.split("=", 1) + if len(parts) == 2: + patient_id = parts[1].strip() + else: + raise ValueError(f"Line {line_num}: Invalid PID format: '{line}'") + continue + + # Parse parameter=value line + if "=" in line: + parts = line.split("=", 1) + try: + param_id = int(parts[0].strip()) + value = parts[1].strip() + results[param_id] = value + except ValueError: + raise ValueError(f"Line {line_num}: Invalid parameter format: '{line}'") + else: + raise ValueError(f"Line {line_num}: Unrecognized line: '{line}'") + + if patient_id is None: + raise ValueError("No PID line found in file") + + if not results: + raise ValueError("No parameter results found in file") + + return {"patient_id": patient_id, "results": results} + + +# ===================================================== +# DATABASE WRITER +# ===================================================== +def write_results_to_db(patient_id: str, results: dict) -> dict: + """ + Write parsed results to the NexLab database. + + Logic: + 1. Find the patient by patient_id + 2. Find their latest visit + 3. Find all orders for that visit + 4. Match parameter IDs to orders via TestParameter + 5. Upsert Result + ResultDetail rows + 6. Set order status to "resulted" + 7. Create audit log entries + + Args: + patient_id: The patient's ID string (e.g., "110003") + results: Dict of {parameter_id: value} (e.g., {1: "4.5", 2: "23.3"}) + + Returns: + Summary dict with counts of what was updated. + """ + now = datetime.now() + summary = { + "patient_id": patient_id, + "parameters_matched": 0, + "orders_updated": 0, + "parameters_skipped": [], + } + + with Session(engine) as session: + # Step 1: Find patient + patient = session.exec( + select(Patient).where(Patient.patient_id == patient_id) + ).first() + + if not patient: + raise ValueError(f"Patient not found: {patient_id}") + + # Step 2: Find latest visit + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.id.desc()) + ).first() + + if not visit: + raise ValueError(f"No visit found for patient: {patient_id}") + + # Step 3: Find all orders for this visit (excluding no_sample) + orders = session.exec( + select(Order) + .where(Order.visit_id == visit.id, Order.status != "no_sample") + ).all() + + if not orders: + raise ValueError(f"No orders found for patient {patient_id}, visit {visit.visit_id}") + + # Step 4: Build a map of parameter_id → order + # This tells us which order each parameter belongs to + param_to_order = {} + for order in orders: + # Skip already finalized orders + if order.status == "double_authorized": + continue + + test_params = session.exec( + select(TestParameter).where(TestParameter.test_id == order.test_id) + ).all() + + for tp in test_params: + param_to_order[tp.parameter_id] = order + + # Step 5: Group results by order + order_results = {} # order_id -> list of (param_id, value) + unmatched_params = [] + + for param_id, value in results.items(): + if param_id in param_to_order: + order = param_to_order[param_id] + if order.id not in order_results: + order_results[order.id] = [] + order_results[order.id].append((param_id, value)) + else: + unmatched_params.append(param_id) + + if unmatched_params: + summary["parameters_skipped"] = unmatched_params + logger.warning( + f" Parameters not matching any order: {unmatched_params}" + ) + + if not order_results: + raise ValueError( + f"None of the parameters ({list(results.keys())}) " + f"match any order for patient {patient_id}" + ) + + # Step 6: Write results to database + for order_id, param_values in order_results.items(): + order = session.get(Order, order_id) + if not order: + continue + + # Upsert parent Result + result = session.exec( + select(Result).where(Result.order_id == order_id) + ).first() + + if not result: + result = Result( + order_id=order_id, + result_value="", + rerun_result="", + flag="", + note="", + entered_by=SYSTEM_USER_ID, + entered_at=now, + ) + session.add(result) + session.flush() # Need result.id for details + + # Upsert each ResultDetail + for param_id, value in param_values: + detail = session.exec( + select(ResultDetail).where( + ResultDetail.result_id == result.id, + ResultDetail.parameter_id == param_id, + ) + ).first() + + if not detail: + detail = ResultDetail( + result_id=result.id, + parameter_id=param_id, + ) + session.add(detail) + + detail.result_value = value + session.add(detail) + summary["parameters_matched"] += 1 + + # Update order status to "resulted" (not authorized — needs human review) + if order.status in ("ordered", "resulted"): + order.status = "resulted" + session.add(order) + summary["orders_updated"] += 1 + + # Step 7: Audit log + try: + import json + audit_entry = AuditLog( + table_name="result", + record_id=visit.id, + action="DEVICE_IMPORT", + user_id=SYSTEM_USER_ID, + username=SYSTEM_USERNAME, + old_values=None, + new_values=json.dumps({ + "source": "CBC_Device", + "patient_id": patient_id, + "parameters_updated": summary["parameters_matched"], + "orders_updated": summary["orders_updated"], + }), + created_at=now, + ) + session.add(audit_entry) + + activity = ActivityLog( + action_type="DEVICE_IMPORT", + description=( + f"CBC device imported {summary['parameters_matched']} result(s) " + f"for patient {patient_id}" + ), + user_id=SYSTEM_USER_ID, + username=SYSTEM_USERNAME, + target_type="patient", + target_id=patient.id, + ) + session.add(activity) + except Exception as e: + logger.warning(f" Audit log failed (non-critical): {e}") + + session.commit() + + return summary + + +# ===================================================== +# FILE PROCESSOR +# ===================================================== +def process_file(filepath: str) -> bool: + """ + Process a single result file: parse → write to DB → move to processed/failed. + Returns True on success, False on failure. + """ + filename = os.path.basename(filepath) + logger.info(f"Found new file: {filename}") + + watch_dir = os.path.dirname(filepath) + processed_dir = os.path.join(watch_dir, "processed") + failed_dir = os.path.join(watch_dir, "failed") + os.makedirs(processed_dir, exist_ok=True) + os.makedirs(failed_dir, exist_ok=True) + + try: + # Parse the file + data = parse_result_file(filepath) + logger.info( + f"Processing results for Patient ID: {data['patient_id']} " + f"({len(data['results'])} parameters)" + ) + + # Write to database + summary = write_results_to_db(data["patient_id"], data["results"]) + logger.info( + f"✅ Successfully updated results for Patient {data['patient_id']} — " + f"{summary['parameters_matched']} params, " + f"{summary['orders_updated']} orders updated" + ) + + # Move to processed folder (add timestamp to avoid name collisions) + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + dest_name = f"{timestamp}_{filename}" + dest_path = os.path.join(processed_dir, dest_name) + shutil.move(filepath, dest_path) + logger.info(f"Moved {filename} → processed/{dest_name}") + + return True + + except ValueError as e: + # Known error (bad format, missing patient, etc.) + logger.error(f"❌ Failed to process {filename}: {e}") + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + dest_name = f"{timestamp}_{filename}" + dest_path = os.path.join(failed_dir, dest_name) + shutil.move(filepath, dest_path) + logger.info(f"Moved {filename} → failed/{dest_name}") + return False + + except Exception as e: + # Unexpected error + logger.error(f"❌ Unexpected error processing {filename}: {e}") + import traceback + logger.error(traceback.format_exc()) + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + dest_name = f"{timestamp}_{filename}" + dest_path = os.path.join(failed_dir, dest_name) + try: + shutil.move(filepath, dest_path) + logger.info(f"Moved {filename} → failed/{dest_name}") + except Exception: + pass + return False + + +# ===================================================== +# STARTUP — Process any existing files first +# ===================================================== +def process_existing_files(watch_folder: str): + """Process any .txt files already in the watch folder on startup.""" + existing = sorted(Path(watch_folder).glob("*.txt")) + if existing: + logger.info(f"Found {len(existing)} existing file(s) to process") + for fp in existing: + process_file(str(fp)) + + +# ===================================================== +# WATCHER — Two modes: watchdog (preferred) or polling +# ===================================================== +def start_watchdog_watcher(watch_folder: str): + """Use the watchdog library for efficient file system monitoring.""" + from watchdog.observers import Observer + from watchdog.events import FileSystemEventHandler + + class CBCFileHandler(FileSystemEventHandler): + def on_created(self, event): + if event.is_directory: + return + if event.src_path.lower().endswith(".txt"): + # Small delay to ensure the file is fully written + time.sleep(0.5) + process_file(event.src_path) + + observer = Observer() + observer.schedule(CBCFileHandler(), watch_folder, recursive=False) + observer.start() + logger.info("Watching with watchdog (real-time file detection)") + + try: + while True: + time.sleep(1) + except KeyboardInterrupt: + observer.stop() + logger.info("Service stopped by user") + observer.join() + + +def start_polling_watcher(watch_folder: str): + """Fallback: poll the folder every POLL_INTERVAL seconds.""" + logger.warning( + "Watchdog library not found. Falling back to polling mode " + f"(every {POLL_INTERVAL} seconds)." + ) + logger.info("Tip: Run 'pip install watchdog' for better performance.") + + known_files = set() + # Initialize with current files (already processed at startup) + for fp in Path(watch_folder).glob("*.txt"): + known_files.add(str(fp)) + + try: + while True: + time.sleep(POLL_INTERVAL) + current_files = set(str(fp) for fp in Path(watch_folder).glob("*.txt")) + new_files = current_files - known_files + + for filepath in sorted(new_files): + # Small delay to ensure the file is fully written + time.sleep(0.3) + process_file(filepath) + + known_files = current_files + except KeyboardInterrupt: + logger.info("Service stopped by user") + + +# ===================================================== +# MAIN ENTRY POINT +# ===================================================== +def main(): + print() + print("=" * 55) + print(" NexLab Device Link — CBC Folder Watcher") + print("=" * 55) + print() + + # Ensure watch folder exists + os.makedirs(WATCH_FOLDER, exist_ok=True) + + logger.info("NexLab Device Link Service Started") + logger.info(f"Watching folder: {WATCH_FOLDER}") + + # Process any files already waiting + process_existing_files(WATCH_FOLDER) + + # Start watching for new files + try: + start_watchdog_watcher(WATCH_FOLDER) + except ImportError: + start_polling_watcher(WATCH_FOLDER) + + +if __name__ == "__main__": + main() diff --git a/excel_files/Departments.xlsx b/excel_files/Departments.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..58c0280d1c4fcbe8ce1139e4b2c6d427c319ecad Binary files /dev/null and b/excel_files/Departments.xlsx differ diff --git a/excel_files/Devices.xlsx b/excel_files/Devices.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..db3cc74133ecd3768746c083cf2272fa46f5b1e6 Binary files /dev/null and b/excel_files/Devices.xlsx differ diff --git a/excel_files/Ranges.xlsx b/excel_files/Ranges.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..fcb1ad937ea710d6417de35c1842596b6e973c1c Binary files /dev/null and b/excel_files/Ranges.xlsx differ diff --git a/excel_files/ReportNote.xlsx b/excel_files/ReportNote.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..c963c91098597af7efc32307d09adbf5ab88b001 Binary files /dev/null and b/excel_files/ReportNote.xlsx differ diff --git a/excel_files/SampleType.xlsx b/excel_files/SampleType.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..e8a66f6f634b3c412864a463b3339532d5c800c8 Binary files /dev/null and b/excel_files/SampleType.xlsx differ diff --git a/excel_files/Tests.xlsx b/excel_files/Tests.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..9fdfbbd637a14032e186c61108a623cc0d987ab0 Binary files /dev/null and b/excel_files/Tests.xlsx differ diff --git a/excel_files/parmeters.xlsx b/excel_files/parmeters.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..4083ced7aa071425efe9ad0b61798473277654c8 Binary files /dev/null and b/excel_files/parmeters.xlsx differ diff --git a/main.py b/main.py new file mode 100644 index 0000000000000000000000000000000000000000..64d1ccfcf626f1534323f29e2141d9a806155aec --- /dev/null +++ b/main.py @@ -0,0 +1,7 @@ +# main.py +# =================================================================== +# BACKWARD-COMPATIBLE BRIDGE — re-exports from app/main.py. +# uvicorn main:app still works. +# =================================================================== + +from app.main import app diff --git a/migrations/migrate_calcontrol.py b/migrations/migrate_calcontrol.py new file mode 100644 index 0000000000000000000000000000000000000000..311cb989340cdc07cfb7f96fc572142c04108855 --- /dev/null +++ b/migrations/migrate_calcontrol.py @@ -0,0 +1,11 @@ +from sqlmodel import SQLModel +from database import engine +from models import CalControl + +def migrate(): + print("Creating CalControl table if it doesn't exist...") + SQLModel.metadata.create_all(engine) + print("Migration successful.") + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_double_auth.py b/migrations/migrate_double_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..e88c4fcf117bc298dc531f22fbadd6da8cc05516 --- /dev/null +++ b/migrations/migrate_double_auth.py @@ -0,0 +1,39 @@ +import sqlite3 + +def migrate(): + # Connect to the main database + conn = sqlite3.connect('lab_database.db') + cursor = conn.cursor() + + print("Starting database migration for Double Authorisation...") + + try: + cursor.execute("ALTER TABLE result ADD COLUMN double_authorized BOOLEAN DEFAULT 0") + print("Added double_authorized to result") + except sqlite3.OperationalError as e: + print(f"double_authorized column might already exist: {e}") + + try: + cursor.execute("ALTER TABLE result ADD COLUMN double_authorized_by INTEGER") + print("Added double_authorized_by to result") + except sqlite3.OperationalError as e: + print(f"double_authorized_by column might already exist: {e}") + + try: + cursor.execute("ALTER TABLE result ADD COLUMN double_authorized_at DATETIME") + print("Added double_authorized_at to result") + except sqlite3.OperationalError as e: + print(f"double_authorized_at column might already exist: {e}") + + try: + cursor.execute("ALTER TABLE result ADD COLUMN unauth_reason VARCHAR") + print("Added unauth_reason to result") + except sqlite3.OperationalError as e: + print(f"unauth_reason column might already exist: {e}") + + conn.commit() + conn.close() + print("Migration completed successfully.") + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_expenses.py b/migrations/migrate_expenses.py new file mode 100644 index 0000000000000000000000000000000000000000..823d5bd23fd28273f01cdb28fc9476c6996b32cb --- /dev/null +++ b/migrations/migrate_expenses.py @@ -0,0 +1,32 @@ +import sqlite3 + +def migrate(): + conn = sqlite3.connect("lab_database.db") + cursor = conn.cursor() + + # Check if table already exists + cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='expensetype'") + exists = cursor.fetchone() + + if not exists: + cursor.execute(""" + CREATE TABLE expensetype ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type_name TEXT NOT NULL UNIQUE, + created_by INTEGER, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + edited_by INTEGER, + edited_at TIMESTAMP, + FOREIGN KEY (created_by) REFERENCES user(id), + FOREIGN KEY (edited_by) REFERENCES user(id) + ) + """) + conn.commit() + print("✅ Created expensetype table") + else: + print("ℹ️ expensetype table already exists") + + conn.close() + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_expenses_entry.py b/migrations/migrate_expenses_entry.py new file mode 100644 index 0000000000000000000000000000000000000000..fe34137b6e8d408ed1008ddd60ef1d1c91aa7994 --- /dev/null +++ b/migrations/migrate_expenses_entry.py @@ -0,0 +1,38 @@ +import sqlite3 + +def migrate(): + conn = sqlite3.connect("lab_database.db") + cursor = conn.cursor() + + # Check if table already exists + cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='expense'") + exists = cursor.fetchone() + + if not exists: + cursor.execute(""" + CREATE TABLE expense ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type_id INTEGER NOT NULL, + expense_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + amount REAL DEFAULT 0.0, + note TEXT, + file_path TEXT, + file_name TEXT, + created_by INTEGER NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + edited_by INTEGER, + edited_at TIMESTAMP, + FOREIGN KEY (type_id) REFERENCES expensetype(id), + FOREIGN KEY (created_by) REFERENCES user(id), + FOREIGN KEY (edited_by) REFERENCES user(id) + ) + """) + conn.commit() + print("✅ Created expense table") + else: + print("ℹ️ expense table already exists") + + conn.close() + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_fasting_time.py b/migrations/migrate_fasting_time.py new file mode 100644 index 0000000000000000000000000000000000000000..74fad63efd71dadc8688eb40977aa4a570a4cf85 --- /dev/null +++ b/migrations/migrate_fasting_time.py @@ -0,0 +1,22 @@ +"""Migration script to add fasting_time column to patient table.""" +import sqlite3 + +def migrate(): + conn = sqlite3.connect("lab_database.db") + cursor = conn.cursor() + + # Check if column already exists + cursor.execute("PRAGMA table_info(patient)") + columns = [col[1] for col in cursor.fetchall()] + + if "fasting_time" not in columns: + cursor.execute("ALTER TABLE patient ADD COLUMN fasting_time INTEGER DEFAULT NULL") + conn.commit() + print("✅ Added fasting_time column to patient table") + else: + print("ℹ️ fasting_time column already exists") + + conn.close() + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_inventory.py b/migrations/migrate_inventory.py new file mode 100644 index 0000000000000000000000000000000000000000..d55aba63c734daa1ba7060e8f0eca67b7bcdea8b --- /dev/null +++ b/migrations/migrate_inventory.py @@ -0,0 +1,39 @@ +"""Migration script to create the inventory table.""" +import sqlite3 + +def migrate(): + conn = sqlite3.connect("lab_database.db") + cursor = conn.cursor() + + # Create inventory table if it doesn't exist + cursor.execute(""" + CREATE TABLE IF NOT EXISTS inventory ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + material_type VARCHAR NOT NULL, + test_id INTEGER, + supply_id INTEGER, + quantity REAL DEFAULT 0.0, + unit VARCHAR DEFAULT 'Test', + expiration_date TIMESTAMP NOT NULL, + note VARCHAR, + is_active BOOLEAN DEFAULT 1, + created_by INTEGER, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + edited_by INTEGER, + edited_at TIMESTAMP, + FOREIGN KEY (test_id) REFERENCES testdefinition(id), + FOREIGN KEY (supply_id) REFERENCES supply(id), + FOREIGN KEY (created_by) REFERENCES user(id), + FOREIGN KEY (edited_by) REFERENCES user(id) + ) + """) + + # Create indices + cursor.execute("CREATE INDEX IF NOT EXISTS ix_inventory_material_type ON inventory (material_type)") + + conn.commit() + conn.close() + print("Created inventory table (if not existed)") + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_labinfo_fields.py b/migrations/migrate_labinfo_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..006635af7149cc37a8626c943ea9cf867a458527 --- /dev/null +++ b/migrations/migrate_labinfo_fields.py @@ -0,0 +1,33 @@ +import sqlite3 + +def migrate(): + conn = sqlite3.connect("lab_database.db") + cursor = conn.cursor() + + # Check if column already exists + cursor.execute("PRAGMA table_info(labinfo)") + columns = [col[1] for col in cursor.fetchall()] + + if "welcome_message" not in columns: + cursor.execute("ALTER TABLE labinfo ADD COLUMN welcome_message TEXT DEFAULT NULL") + print("Added welcome_message column to labinfo table") + else: + print("welcome_message column already exists") + + if "province_id" not in columns: + cursor.execute("ALTER TABLE labinfo ADD COLUMN province_id INTEGER DEFAULT NULL") + print("Added province_id column to labinfo table") + else: + print("province_id column already exists") + + if "welcome_template_name" not in columns: + cursor.execute("ALTER TABLE labinfo ADD COLUMN welcome_template_name TEXT DEFAULT NULL") + print("Added welcome_template_name column to labinfo table") + else: + print("welcome_template_name column already exists") + + conn.commit() + conn.close() + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_messages.py b/migrations/migrate_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d68b3c01acdf3f1aec54ac37b0676dd1182c92 --- /dev/null +++ b/migrations/migrate_messages.py @@ -0,0 +1,38 @@ +import sqlite3 +import os + +DB_FILE = "lab_database.db" + +def migrate(): + if not os.path.exists(DB_FILE): + print(f"Error: Database {DB_FILE} not found!") + return + + conn = sqlite3.connect(DB_FILE) + cursor = conn.cursor() + + # Check if User table exists + cursor.execute("PRAGMA table_info(user)") + columns = [info[1] for info in cursor.fetchall()] + + if "last_seen" not in columns: + print("Adding 'last_seen' to user table...") + cursor.execute("ALTER TABLE user ADD COLUMN last_seen DATETIME") + + if "is_online" not in columns: + print("Adding 'is_online' to user table...") + cursor.execute("ALTER TABLE user ADD COLUMN is_online BOOLEAN DEFAULT 0") + + # The creation of the new tables will be handled by SQLModel's create_all + # But just in case, we can trigger SQLModel create_db_and_tables directly here. + conn.commit() + conn.close() + + from database import create_db_and_tables + print("Running sqlmodel create_db_and_tables...") + create_db_and_tables() + + print("Messaging DB models successfully migrated!") + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_models.py b/migrations/migrate_models.py new file mode 100644 index 0000000000000000000000000000000000000000..7ee61e426069ca6aa4aba7a78cc161cc9eeba631 --- /dev/null +++ b/migrations/migrate_models.py @@ -0,0 +1,12 @@ +import os +from sqlmodel import SQLModel, create_engine +import models # Make sure models are imported so SQLModel knows about them + +# Create sqlite engine pointing to lab_system database +sqlite_url = "sqlite:///./lab_database.db" +engine = create_engine(sqlite_url, echo=True) + +if __name__ == "__main__": + print("Creating new tables...") + SQLModel.metadata.create_all(engine) + print("Done!") diff --git a/migrations/migrate_print_status.py b/migrations/migrate_print_status.py new file mode 100644 index 0000000000000000000000000000000000000000..22b7d604f57de6f539bb24077e5540582f3f6bde --- /dev/null +++ b/migrations/migrate_print_status.py @@ -0,0 +1,37 @@ +import sqlite3 +import os + +DB_PATH = "lab_database.db" + +def migrate(): + print("Checking for 'is_printed' column in 'patientvisit' table...") + + if not os.path.exists(DB_PATH): + print(f"Error: {DB_PATH} not found.") + return + + conn = sqlite3.connect(DB_PATH) + cursor = conn.cursor() + + try: + # Check if the column exists + cursor.execute("PRAGMA table_info(patientvisit);") + columns = [column[1] for column in cursor.fetchall()] + + if "is_printed" not in columns: + print("Adding 'is_printed' column to 'patientvisit' table...") + cursor.execute("ALTER TABLE patientvisit ADD COLUMN is_printed BOOLEAN DEFAULT 0 NOT NULL;") + conn.commit() + print("Migration successful: 'is_printed' column added.") + else: + print("Migration skipped: 'is_printed' column already exists (applied previously).") + + except Exception as e: + print(f"Migration failed: {e}") + conn.rollback() + + finally: + conn.close() + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_security.py b/migrations/migrate_security.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbf4aa0cc76289d3911e87742d5b5f360faeabc --- /dev/null +++ b/migrations/migrate_security.py @@ -0,0 +1,32 @@ +import sqlite3 + +def migrate(): + conn = sqlite3.connect("lab_database.db") + cursor = conn.cursor() + + # We will add columns to the 'user' table + columns_to_add = [ + ("failed_login_attempts", "INTEGER DEFAULT 0 NOT NULL"), + ("locked_until", "DATETIME"), + ("session_token", "VARCHAR") + ] + + for col_name, col_type in columns_to_add: + try: + cursor.execute(f"ALTER TABLE user ADD COLUMN {col_name} {col_type};") + print(f"Added {col_name} to user table.") + except sqlite3.OperationalError as e: + # Column likely already exists + print(f"Could not add {col_name} (may already exist): {e}") + + # For any existing rows, give them a session token or initialization + # actually session_token can be NULL and will be filled upon next login. + # We can just update failed_login_attempts to 0 if it was null due to alter table. + cursor.execute("UPDATE user SET failed_login_attempts = 0 WHERE failed_login_attempts IS NULL;") + + conn.commit() + conn.close() + print("Migration complete!") + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_supplies.py b/migrations/migrate_supplies.py new file mode 100644 index 0000000000000000000000000000000000000000..dce00b430c9ca3108721b0eca812d75bcc4f9fc4 --- /dev/null +++ b/migrations/migrate_supplies.py @@ -0,0 +1,32 @@ +"""Migration script to create the supply table.""" +import sqlite3 + +def migrate(): + conn = sqlite3.connect("lab_database.db") + cursor = conn.cursor() + + # Create supply table if it doesn't exist + cursor.execute(""" + CREATE TABLE IF NOT EXISTS supply ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name VARCHAR NOT NULL, + note VARCHAR, + is_active BOOLEAN DEFAULT 1, + created_by INTEGER, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + edited_by INTEGER, + edited_at TIMESTAMP, + FOREIGN KEY (created_by) REFERENCES user(id), + FOREIGN KEY (edited_by) REFERENCES user(id) + ) + """) + + # Create index on name + cursor.execute("CREATE INDEX IF NOT EXISTS ix_supply_name ON supply (name)") + + conn.commit() + conn.close() + print("Created supply table (if not existed)") + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_tax.py b/migrations/migrate_tax.py new file mode 100644 index 0000000000000000000000000000000000000000..c5d8f2101b375501e51300ab6323482bf857c3bf --- /dev/null +++ b/migrations/migrate_tax.py @@ -0,0 +1,22 @@ +"""Migration script to add tax_percentage column to labinfo table.""" +import sqlite3 + +def migrate(): + conn = sqlite3.connect("lab_database.db") + cursor = conn.cursor() + + # Check if column already exists + cursor.execute("PRAGMA table_info(labinfo)") + columns = [col[1] for col in cursor.fetchall()] + + if "tax_percentage" not in columns: + cursor.execute("ALTER TABLE labinfo ADD COLUMN tax_percentage REAL DEFAULT 0.0") + conn.commit() + print("✅ Added tax_percentage column to labinfo table") + else: + print("ℹ️ tax_percentage column already exists") + + conn.close() + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_users.py b/migrations/migrate_users.py new file mode 100644 index 0000000000000000000000000000000000000000..85d1f269b268346b0ff93b93ddee80e3a13b836d --- /dev/null +++ b/migrations/migrate_users.py @@ -0,0 +1,48 @@ +"""Migration script to add user profile fields and userpermission table.""" +import sqlite3 + +def migrate(): + conn = sqlite3.connect("lab_database.db") + cursor = conn.cursor() + + # Check and add new columns to user table + cursor.execute("PRAGMA table_info(user)") + columns = [col[1] for col in cursor.fetchall()] + + new_columns = [ + ("date_of_birth", "TEXT"), + ("phone_number", "TEXT"), + ("address", "TEXT"), + ("edited_by", "INTEGER"), + ("edited_at", "TEXT"), + ] + + for col_name, col_type in new_columns: + if col_name not in columns: + cursor.execute(f"ALTER TABLE user ADD COLUMN {col_name} {col_type}") + print(f" [+] Added column user.{col_name}") + else: + print(f" [i] Column user.{col_name} already exists") + + # Create userpermission table + cursor.execute(""" + CREATE TABLE IF NOT EXISTS userpermission ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL REFERENCES user(id), + page_key TEXT NOT NULL, + allowed_buttons TEXT + ) + """) + print(" [+] userpermission table created/verified") + + # Create index on user_id + cursor.execute("CREATE INDEX IF NOT EXISTS idx_userpermission_user_id ON userpermission(user_id)") + cursor.execute("CREATE INDEX IF NOT EXISTS idx_userpermission_page_key ON userpermission(page_key)") + print(" [+] Indexes created/verified") + + conn.commit() + conn.close() + print("\n[+] User management migration complete!") + +if __name__ == "__main__": + migrate() diff --git a/migrations/migrate_visit_tax.py b/migrations/migrate_visit_tax.py new file mode 100644 index 0000000000000000000000000000000000000000..21bc0e88bd3915f9db62f12031ff51c3bcc98c18 --- /dev/null +++ b/migrations/migrate_visit_tax.py @@ -0,0 +1,23 @@ +import sqlite3 + +def migrate(): + conn = sqlite3.connect("lab_database.db") + cursor = conn.cursor() + + cursor.execute("PRAGMA table_info(patientvisit)") + columns = [col[1] for col in cursor.fetchall()] + + if "tax_applied" not in columns: + cursor.execute("ALTER TABLE patientvisit ADD COLUMN tax_applied BOOLEAN DEFAULT 1") + conn.commit() + print("Added tax_applied") + + if "tax_amount" not in columns: + cursor.execute("ALTER TABLE patientvisit ADD COLUMN tax_amount REAL DEFAULT 0.0") + conn.commit() + print("Added tax_amount") + + conn.close() + +if __name__ == "__main__": + migrate() diff --git a/migrations/run_all.py b/migrations/run_all.py new file mode 100644 index 0000000000000000000000000000000000000000..58ec244a1486f673037be783e6f284efd7a64d62 --- /dev/null +++ b/migrations/run_all.py @@ -0,0 +1,53 @@ +import os +import sys +import subprocess +import glob + +def run_migrations(): + # Set console encoding to UTF-8 to support emojis on Windows + if hasattr(sys.stdout, 'reconfigure'): + sys.stdout.reconfigure(encoding='utf-8') + + # Determine directories + base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + migrations_dir = os.path.join(base_dir, "migrations") + + # Find all migration files + search_pattern = os.path.join(migrations_dir, "migrate_*.py") + migration_files = glob.glob(search_pattern) + migration_files.sort() # Sort them to run in a consistent order + + if not migration_files: + print("ℹ️ No migration files found.") + return + + print(f"🚀 Found {len(migration_files)} migration files. Running them now...") + + # Set PYTHONPATH so migration scripts can import root modules (database.py, models.py) + env = os.environ.copy() + if "PYTHONPATH" in env: + env["PYTHONPATH"] = f"{base_dir}{os.pathsep}{env['PYTHONPATH']}" + else: + env["PYTHONPATH"] = base_dir + + # Force UTF-8 encoding in subprocesses to handle emojis correctly on Windows + env["PYTHONUTF8"] = "1" + + for migration_file in migration_files: + filename = os.path.basename(migration_file) + print(f"--- Running {filename} ---") + try: + # Use the current python interpreter + result = subprocess.run([sys.executable, migration_file], capture_output=True, text=True, env=env, encoding="utf-8") + if result.returncode == 0: + print(result.stdout) + else: + print(f"❌ Error running {filename}:") + print(result.stderr) + except Exception as e: + print(f"❌ System error running {filename}: {e}") + + print("✅ All migrations completed.") + +if __name__ == "__main__": + run_migrations() diff --git a/models.py b/models.py new file mode 100644 index 0000000000000000000000000000000000000000..7ac6e5fe34411e5b16e560f744ce8563170501cc --- /dev/null +++ b/models.py @@ -0,0 +1,7 @@ +# models.py +# =================================================================== +# BACKWARD-COMPATIBLE BRIDGE — re-exports from app/models/. +# Existing code can continue to use: from models import Patient, Order, ... +# =================================================================== + +from app.models import * \ No newline at end of file diff --git a/package_app.py b/package_app.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ba72d24baa8957828a08643d72f47e37a46974 --- /dev/null +++ b/package_app.py @@ -0,0 +1,117 @@ +import os +import shutil +import glob + +def package(): + # --- CONFIGURATION --- + PORT = 8000 + # --------------------- + + dist_dir = "NexLab_Published" + if os.path.exists(dist_dir): + shutil.rmtree(dist_dir) + os.makedirs(dist_dir) + + # 1. Copy application directories + include_dirs = ['app', 'routes', 'templates', 'static', 'uploads', 'tmp', 'device_interfacing', 'migrations', 'tools'] + # Removed lab_database.db from include_files to prevent overwriting production data + include_files = [ + 'main.py', 'models.py', 'database.py', 'requirements.txt', + 'update_system.bat', 'System_Update_Guide.md', '.env' + ] + + for d in include_dirs: + if os.path.exists(d): + shutil.copytree(d, os.path.join(dist_dir, d), dirs_exist_ok=True, + ignore=shutil.ignore_patterns('__pycache__', '*.pyc', '*.pyo')) + else: + os.makedirs(os.path.join(dist_dir, d), exist_ok=True) + + for f in include_files: + if os.path.exists(f): + shutil.copy2(f, os.path.join(dist_dir, f)) + + # 2. Create Start Script + start_bat_content = f"""@echo off +set "VENV_DIR=%~dp0venv" + +REM Load environment variables from .env +if exist "%~dp0.env" ( + for /F "tokens=1,2 delims==" %%A in ('type "%~dp0.env"') do ( + echo %%A | findstr /r "^#" >nul 2>&1 + if errorlevel 1 ( + if not "%%A"=="" set "%%A=%%B" + ) + ) +) + +if not exist "%VENV_DIR%" ( + echo [ERROR] Virtual environment not found. Please run 'install_requirements.bat' first. + pause + exit /b +) +echo Starting NexLab LIS Server... +echo Access this system at: http://localhost:%PORT% +echo. +REM Start CBC Device Watcher in a separate window +echo Starting CBC Device Watcher... +start "NexLab CBC Device Watcher" "%VENV_DIR%\\\\Scripts\\\\python.exe" device_interfacing\\\\device_watcher.py +"%VENV_DIR%\\\\Scripts\\\\python.exe" -m uvicorn main:app --host 0.0.0.0 --port %PORT% +pause +""" + with open(os.path.join(dist_dir, "start_nexlab.bat"), "w") as f: + f.write(start_bat_content) + + # 2b. Create standalone Device Watcher script + watcher_bat_content = """@echo off +set "VENV_DIR=%~dp0venv" +if not exist "%VENV_DIR%" ( + echo [ERROR] Virtual environment not found. Please run 'install_requirements.bat' first. + pause + exit /b +) +echo ===================================================== +echo NexLab CBC Device Watcher +echo ===================================================== +echo. +"%VENV_DIR%\\\\Scripts\\\\python.exe" device_interfacing\\\\device_watcher.py +pause +""" + with open(os.path.join(dist_dir, "start_device_watcher.bat"), "w") as f: + f.write(watcher_bat_content) + + # 3. Create Install Script + install_bat_content = """@echo off +echo Preparing NexLab Environment... +where python >nul 2>&1 +if %errorlevel% neq 0 ( + echo [ERROR] Python not found! Please install Python 3.10+ first. + pause + exit /b +) +if not exist "venv" ( + python -m venv venv +) +echo Installing dependencies... +"venv\\\\Scripts\\\\pip.exe" install -r requirements.txt +"venv\\\\Scripts\\\\python.exe" -m playwright install chromium +echo Setup Complete! Run 'start_nexlab.bat' +pause +""" + with open(os.path.join(dist_dir, "install_requirements.bat"), "w") as f: + f.write(install_bat_content) + + # 4. Create Auto-Start Script + autostart_bat_content = """@echo off +set "SCRIPT_PATH=%~dp0start_nexlab.bat" +set "SHORTCUT_PATH=%APPDATA%\\\\Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\Startup\\\\NexLab_LIS.lnk" +powershell "$s=(New-Object -ComObject WScript.Shell).CreateShortcut('%SHORTCUT_PATH%');$s.TargetPath='%SCRIPT_PATH%';$s.WorkingDirectory='%~dp0';$s.WindowStyle=7;$s.Save()" +echo Added to Startup! +pause +""" + with open(os.path.join(dist_dir, "add_to_startup.bat"), "w") as f: + f.write(autostart_bat_content) + +if __name__ == "__main__": + package() + print("Packaging finished successfully.") diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..a161815f3c7f5be6bc87105fd206e8032a7f8a54 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,48 @@ +# NexLab LIS - Python Dependencies +# Install with: pip install -r requirements.txt + +# Web Framework +fastapi==0.133.1 +uvicorn==0.41.0 +python-multipart==0.0.22 +starlette==0.52.1 +websockets==14.2 + +# Database +sqlmodel==0.0.37 +SQLAlchemy==2.0.47 + +# Templates +Jinja2==3.1.6 + +# Authentication & Security +passlib==1.7.4 +bcrypt==3.2.2 +itsdangerous==2.2.0 +python-jose==3.5.0 + +# Barcode & QR +python-barcode==0.16.1 +pillow==12.1.1 +qrcode==8.2 + +# PDF Generation +playwright==1.58.0 +xhtml2pdf==0.2.17 +reportlab==4.4.10 + +# WhatsApp / Google AI +requests==2.33.0 +google-generativeai==0.8.6 + +# Device Interfacing +watchdog==6.0.0 + +# Configuration +python-dotenv==1.1.0 + +# Utilities +pydantic==2.12.5 +aiofiles==25.1.0 +python-bidi==0.6.7 +arabic-reshaper==3.0.0 diff --git a/routes/__init__.py b/routes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/routes/api.py b/routes/api.py new file mode 100644 index 0000000000000000000000000000000000000000..f9791f02c6a68fb6d3397c0b07836916125654e1 --- /dev/null +++ b/routes/api.py @@ -0,0 +1,398 @@ +# routes/api.py +# JSON API endpoints — patient data, orders, barcode, lab info, general listings. +# Includes N+1 fixes with selectinload. + +from fastapi import APIRouter, Depends, Request +from sqlmodel import Session, select +from sqlalchemy.orm import selectinload +from database import get_session +from models import ( + Patient, PatientVisit, Order, TestDefinition, SampleType, + Region, PackageTest, Parameter, Department, Device, + ReportNote, Formula, LabInfo, AuditLog, ActivityLog, +) +from routes.helpers import generate_barcode_base64, get_current_user +from fastapi.responses import JSONResponse + +router = APIRouter() + +# =========================== +# REGION API +# =========================== +@router.get("/api/regions") +def get_regions_by_province(province_id: int, session: Session = Depends(get_session)): + regions = session.exec(select(Region).where(Region.province_id == province_id)).all() + return [{"id": r.id, "region_name": r.region_name} for r in regions] + +@router.get("/api/package-tests/{package_id}") +def get_package_tests(package_id: int, session: Session = Depends(get_session)): + package_tests = session.exec(select(PackageTest).where(PackageTest.package_id == package_id)).all() + return {"test_ids": [pt.test_id for pt in package_tests]} + +@router.get("/api/generate-patient-id") +def generate_patient_id_api(session: Session = Depends(get_session)): + try: + labId = 1 + baseNumber = 100000 + last_patient = session.exec(select(Patient).order_by(Patient.id.desc()).limit(1)).first() + if last_patient and last_patient.patient_id: + try: + last_number = int(last_patient.patient_id[1:]) + next_number = last_number + 1 + except Exception: + next_number = baseNumber + else: + next_number = baseNumber + patient_id = str(labId) + str(next_number).zfill(6) + return {"patient_id": patient_id} + except Exception as e: + return {"error": str(e)} + +# =========================== +# PATIENT SEARCH BY NAME (Live Autocomplete) +# =========================== +@router.get("/api/search-patients-by-name") +def search_patients_by_name(request: Request, q: str = "", session: Session = Depends(get_session)): + """Return up to 10 active patients matching the name fragment (for registration autocomplete).""" + if not _require_login(request, session): + return JSONResponse({"error": "Unauthorized"}, status_code=401) + q = q.strip() + if len(q) < 2: + return [] + patients = session.exec( + select(Patient) + .where(Patient.is_active == True, Patient.full_name.ilike(f"%{q}%")) + .order_by(Patient.created_at.desc()) + .limit(10) + ).all() + results = [] + for p in patients: + results.append({ + "id": p.id, + "patient_id": p.patient_id, + "full_name": p.full_name, + "phone_key": p.phone_key, + "phone_number": p.phone_number, + "gender": p.gender, + "age": p.age, + "age_unit": p.age_unit or "year", + "date_of_birth": p.date_of_birth.strftime("%Y-%m-%d") if p.date_of_birth else "", + "weight": p.weight or 0, + "height": p.height or 0, + "province_id": p.province_id, + "region_id": p.region_id, + "note": p.note or "", + "email": p.email or "", + "diagnosis": p.diagnosis or "", + "symptoms": p.symptoms or "", + "therapy": p.therapy or "", + "partner_id": p.partner_id, + "doctor": p.doctor or "", + "skin_colour": p.skin_colour or "", + "agent_name": p.agent_name or "", + "is_outlab": p.is_outlab, + }) + return results + +# =========================== +# PATIENT ORDERS API (WITH PRICE SNAPSHOT + N+1 FIX) +# =========================== +@router.get("/api/patient-orders/{patient_id}") +def get_patient_orders_api(patient_id: str, session: Session = Depends(get_session)): + try: + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + return {"success": False, "error": "Patient not found"} + + # ✅ N+1 FIX: eager-load test relationship + orders = session.exec( + select(Order) + .options(selectinload(Order.test)) + .where(Order.patient_id == patient.id) + ).all() + + orders_data = [] + for order in orders: + test = order.test + orders_data.append({ + "order_id": order.id, + "order_number": order.order_number, + "test_id": order.test_id, + "test_name": test.test_name if test else 'Unknown', + "package_name": order.package_name or None, + "unit_price": order.unit_price or (test.price if test else 0), + "discount_amount": order.discount_amount or 0, + "final_price": order.final_price or (order.unit_price or 0), + "status": order.status, + "order_date": order.order_date.isoformat() if order.order_date else None + }) + + return {"success": True, "orders": orders_data} + except Exception as e: + return {"success": False, "error": str(e)} + +# =========================== +# LAB INFO API +# =========================== +@router.get("/api/lab-info") +def get_lab_info_api(session: Session = Depends(get_session)): + lab_info = session.exec(select(LabInfo).limit(1)).first() + if lab_info: + return { + "success": True, + "lab_info": { + "lab_name": lab_info.lab_name or "NexLab Medical Center", + "lab_title": lab_info.lab_title or "Medical Laboratory", + "lab_address": lab_info.lab_address or "", + "lab_phone_1": lab_info.lab_phone_1 or "", + "lab_phone_2": lab_info.lab_phone_2 or "", + "lab_email": lab_info.lab_email or "", + "lab_website": lab_info.lab_website or "", + "tax_percentage": lab_info.tax_percentage if lab_info.tax_percentage is not None else 0.0, + "lab_currency": lab_info.lab_currency or "$", + "first_doctor_name": lab_info.first_doctor_name or "", + "second_doctor_name": lab_info.second_doctor_name or "", + "lab_note_1": lab_info.lab_note_1 or "", + "lab_note_2": lab_info.lab_note_2 or "", + "lab_logo": lab_info.lab_logo or "", + "lab_qr_1": lab_info.lab_qr_1 or "", + "lab_qr_2": lab_info.lab_qr_2 or "", + "lab_stamp_1": lab_info.lab_stamp_1 or "", + "lab_stamp_2": lab_info.lab_stamp_2 or "", + "lab_signature_1": lab_info.lab_signature_1 or "", + "lab_signature_2": lab_info.lab_signature_2 or "", + } + } + return { + "success": True, + "lab_info": { + "lab_name": "NexLab Medical Center", "lab_title": "Medical Laboratory", + "lab_address": "", "lab_phone_1": "", "lab_phone_2": "", + "lab_email": "", "lab_website": "", "lab_currency": "$", "tax_percentage": 0.0, + "first_doctor_name": "", "second_doctor_name": "", + "lab_note_1": "", "lab_note_2": "", + "lab_logo": "", "lab_qr_1": "", "lab_qr_2": "", + "lab_stamp_1": "", "lab_stamp_2": "", + "lab_signature_1": "", "lab_signature_2": "", + } + } + +# =========================== +# PATIENT API (WITH ACCOUNTING DATA + N+1 FIX) +# =========================== +@router.get("/api/patient/{patient_id}") +def get_patient_api(patient_id: str, session: Session = Depends(get_session)): + try: + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + return {"error": "Patient not found"} + + # ✅ N+1 FIX: eager-load test + sample_type relationships + orders = session.exec( + select(Order) + .options( + selectinload(Order.test).selectinload(TestDefinition.sample_type) + ) + .where(Order.patient_id == patient.id) + ).all() + + test_names = [order.test.test_name if order.test else 'Unknown' for order in orders] + test_short_names = [order.test.test_short_name if order.test and order.test.test_short_name else (order.test.test_name if order.test else 'Unknown') for order in orders] + + tests_by_sample_type = {} + for order in orders: + if order.test: + sample_type_name = order.test.sample_type.sample_name if order.test.sample_type else "Unknown" + if sample_type_name not in tests_by_sample_type: + tests_by_sample_type[sample_type_name] = [] + tests_by_sample_type[sample_type_name].append( + order.test.test_short_name if order.test.test_short_name else order.test.test_name + ) + + visits = session.exec(select(PatientVisit).where(PatientVisit.patient_id == patient.id)).all() + visit_id = visits[0].visit_id if visits else patient.patient_id + '000' + + received_amount = visits[0].received_amount if visits else 0.0 + discount_amount = visits[0].discount_amount if visits else 0.0 + tax_amount = visits[0].tax_amount if visits and visits[0].tax_amount else 0.0 + remaining_amount = visits[0].remaining_amount if visits else 0.0 + + total_amount = sum([float(order.final_price) if order.final_price else 0 for order in orders]) + + total_after_tax = total_amount - discount_amount + tax_amount + + return { + "patient_id": patient.patient_id, + "full_name": patient.full_name, + "gender": patient.gender, + "age": patient.age, + "age_unit": patient.age_unit, + "phone_key": patient.phone_key, + "phone_number": patient.phone_number, + "tests": test_names, + "tests_by_sample_type": tests_by_sample_type, + "visit_id": visit_id, + "visit_date": visits[0].visit_date.isoformat() if visits and visits[0].visit_date else None, + "total_amount": round(total_amount, 2), + "discount_amount": round(discount_amount, 2), + "tax_amount": round(tax_amount, 2), + "total_after_tax": round(total_after_tax, 2), + "paid_amount": round(received_amount, 2), + "remain_amount": round(remaining_amount, 2) + } + except Exception as e: + print(f"❌ Error in get_patient_api: {str(e)}") + import traceback + traceback.print_exc() + return {"error": str(e)} + +# =========================== +# BARCODE API +# =========================== +@router.get("/api/barcode/{patient_id}") +def get_barcode_api(patient_id: str, session: Session = Depends(get_session)): + barcode_data = generate_barcode_base64(patient_id) + return {"barcode_data": barcode_data} + +# =========================== +# CHECK DUPLICATE PATIENT BY PHONE +# =========================== +@router.get("/api/check-patient-phone") +def check_patient_phone(phone_key: str, phone_number: str, session: Session = Depends(get_session)): + try: + patient = session.exec(select(Patient).where( + Patient.phone_key == phone_key, + Patient.phone_number == phone_number, + Patient.is_active == True + )).first() + + if patient: + return { + "exists": True, + "patient": { + "id": patient.id, + "patient_id": patient.patient_id, + "full_name": patient.full_name, + "phone_key": patient.phone_key, + "phone_number": patient.phone_number, + "gender": patient.gender, + "age": patient.age, + "province_id": patient.province_id, + "region_id": patient.region_id, + "email": patient.email, + "note": patient.note + } + } + return {"exists": False} + except Exception as e: + return {"exists": False, "error": str(e)} + +# =========================== +# GENERAL LIST ENDPOINTS (Login Required) +# =========================== +def _require_login(request: Request, session: Session): + """Quick login check for data APIs. Returns user or None.""" + user = get_current_user(request, session) + if not user: + return None + return user + +@router.get("/api/patients") +def list_patients_api(request: Request, session: Session = Depends(get_session)): + if not _require_login(request, session): + return JSONResponse({"error": "Unauthorized"}, status_code=401) + return session.exec(select(Patient)).all() + +@router.get("/api/parameters") +def list_parameters_api(request: Request, session: Session = Depends(get_session)): + if not _require_login(request, session): + return JSONResponse({"error": "Unauthorized"}, status_code=401) + return session.exec(select(Parameter)).all() + +@router.get("/api/departments") +def list_departments_api(request: Request, session: Session = Depends(get_session)): + if not _require_login(request, session): + return JSONResponse({"error": "Unauthorized"}, status_code=401) + return session.exec(select(Department)).all() + +@router.get("/api/devices") +def list_devices_api(request: Request, session: Session = Depends(get_session)): + if not _require_login(request, session): + return JSONResponse({"error": "Unauthorized"}, status_code=401) + return session.exec(select(Device)).all() + +@router.get("/api/sample-types") +def list_sample_types_api(request: Request, session: Session = Depends(get_session)): + if not _require_login(request, session): + return JSONResponse({"error": "Unauthorized"}, status_code=401) + return session.exec(select(SampleType)).all() + +@router.get("/api/report-notes") +def list_report_notes_api(request: Request, session: Session = Depends(get_session)): + if not _require_login(request, session): + return JSONResponse({"error": "Unauthorized"}, status_code=401) + return session.exec(select(ReportNote)).all() + +@router.get("/api/tests") +def list_tests_api(request: Request, session: Session = Depends(get_session)): + if not _require_login(request, session): + return JSONResponse({"error": "Unauthorized"}, status_code=401) + return session.exec(select(TestDefinition)).all() + +@router.get("/api/formulas") +def list_formulas_api(request: Request, session: Session = Depends(get_session)): + if not _require_login(request, session): + return JSONResponse({"error": "Unauthorized"}, status_code=401) + return session.exec(select(Formula)).all() + +@router.get("/api/audit-logs") +def list_audit_logs_api(request: Request, session: Session = Depends(get_session)): + if not _require_login(request, session): + return JSONResponse({"error": "Unauthorized"}, status_code=401) + return session.exec(select(AuditLog).order_by(AuditLog.created_at.desc()).limit(500)).all() + +# =========================== +# AUDIT LOG CLEANUP (Admin Only) +# =========================== +@router.delete("/api/audit-logs/cleanup") +def cleanup_old_logs(request: Request, session: Session = Depends(get_session)): + """ + Delete audit and activity logs older than 6 months. + Admin-only endpoint to prevent unbounded table growth. + Accepts optional ?months=N query param (default: 6). + """ + from routes.helpers import require_permission + if not require_permission(request, session, "settings"): + return JSONResponse({"error": "Admin access required"}, status_code=403) + + try: + months = int(request.query_params.get("months", 6)) + except (ValueError, TypeError): + months = 6 + + from datetime import datetime, timedelta + cutoff_date = datetime.now() - timedelta(days=months * 30) + + # Count before deletion + audit_count = len(session.exec( + select(AuditLog).where(AuditLog.created_at < cutoff_date) + ).all()) + activity_count = len(session.exec( + select(ActivityLog).where(ActivityLog.created_at < cutoff_date) + ).all()) + + # Delete old records + from sqlalchemy import delete + session.exec(delete(AuditLog).where(AuditLog.created_at < cutoff_date)) + session.exec(delete(ActivityLog).where(ActivityLog.created_at < cutoff_date)) + session.commit() + + return { + "success": True, + "message": f"Cleaned up logs older than {months} months", + "deleted": { + "audit_logs": audit_count, + "activity_logs": activity_count + }, + "cutoff_date": cutoff_date.isoformat() + } diff --git a/routes/attachments.py b/routes/attachments.py new file mode 100644 index 0000000000000000000000000000000000000000..29b4913f00e1930381b741ff694a0521dac69505 --- /dev/null +++ b/routes/attachments.py @@ -0,0 +1,94 @@ +from fastapi import APIRouter, Depends, Request, Form, UploadFile, File, status +from fastapi.responses import RedirectResponse +from sqlmodel import Session, select +import os +import secrets +from datetime import datetime + +from database import get_session +from models import Patient, Attachment +from routes.helpers import get_current_user, require_permission + +router = APIRouter() + +ATTACHMENTS_DIR = "uploads/attachments" +os.makedirs(ATTACHMENTS_DIR, exist_ok=True) + +@router.post("/patient/{patient_id}/attachment") +async def upload_attachment( + patient_id: str, + request: Request, + file: UploadFile = File(...), + description: str = Form(None), + session: Session = Depends(get_session) +): + current_user = get_current_user(request, session) + if not current_user: + return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) + + try: + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + return RedirectResponse(url="/patients", status_code=status.HTTP_303_SEE_OTHER) + + if not file.filename: + return RedirectResponse(url=f"/patient/edit/{patient_id}?error=No file selected", status_code=status.HTTP_303_SEE_OTHER) + + # Secure file saving + ext = os.path.splitext(file.filename)[1].lower() + secure_filename = f"{patient.id}_{secrets.token_hex(8)}{ext}" + file_path = os.path.join(ATTACHMENTS_DIR, secure_filename) + + with open(file_path, "wb") as buffer: + content = await file.read() + buffer.write(content) + + file_type = "image" if ext in ['.jpg', '.jpeg', '.png', '.gif'] else ("pdf" if ext == ".pdf" else "document") + + attachment = Attachment( + patient_id=patient.id, + file_name=file.filename, + file_path=file_path.replace("\\", "/"), + file_type=file_type, + description=description, + uploaded_by=current_user.id + ) + session.add(attachment) + session.commit() + + return RedirectResponse(url=f"/patient/edit/{patient_id}?success=Attachment uploaded", status_code=status.HTTP_303_SEE_OTHER) + + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/patient/edit/{patient_id}?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/attachment/{attachment_id}/delete") +def delete_attachment( + attachment_id: int, + request: Request, + session: Session = Depends(get_session) +): + current_user = get_current_user(request, session) + if not current_user: + return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) + + try: + attachment = session.get(Attachment, attachment_id) + if not attachment: + return RedirectResponse(url="/patients", status_code=status.HTTP_303_SEE_OTHER) + + patient = session.get(Patient, attachment.patient_id) + patient_route_id = patient.patient_id if patient else "" + + # Physically delete the file + if os.path.exists(attachment.file_path): + os.remove(attachment.file_path) + + session.delete(attachment) + session.commit() + + return RedirectResponse(url=f"/patient/edit/{patient_route_id}?success=Attachment deleted", status_code=status.HTTP_303_SEE_OTHER) + + except Exception as e: + session.rollback() + return RedirectResponse(url="/patients?error=Failed to delete attachment", status_code=status.HTTP_303_SEE_OTHER) diff --git a/routes/auth.py b/routes/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..56017d145d474c8f8fc2e3a0dcb61affa4228fe7 --- /dev/null +++ b/routes/auth.py @@ -0,0 +1,219 @@ +# routes/auth.py +# Authentication and dashboard routes. + +from fastapi import APIRouter, Depends, Request, Form, status +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlmodel import Session, select, func, or_, and_ +from database import get_session +from models import User, Patient, Order, Result, PatientVisit, DeletedRecord, ResultDetail, TestDefinition, Parameter +# ✅ Centralized imports +from routes.helpers import templates, create_audit_log, log_activity_action, get_current_user, SECRET_KEY, pwd_context +from datetime import datetime, date, time + +router = APIRouter() + +# =========================== +# DASHBOARD & AUTH +# =========================== +@router.get("/", response_class=HTMLResponse) +def dashboard(request: Request, session: Session = Depends(get_session)): + # Check login + current_user = get_current_user(request, session) + if not current_user: + return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) + + # 1. Total Patients (Today) + today_start = datetime.combine(date.today(), time.min) + today_end = datetime.combine(date.today(), time.max) + today_patients_count = session.exec(select(func.count(Patient.id)).where(Patient.created_at >= today_start, Patient.created_at <= today_end)).one() + + # Orders and Results logic for Pending, Done, Waiting — filtered to TODAY's visits for performance + today_visits = select(PatientVisit.id).where( + PatientVisit.visit_date >= today_start, + PatientVisit.visit_date <= today_end + ).scalar_subquery() + + today_orders = select(Order).where(Order.visit_id.in_(today_visits)) + + stmt_has_orders = select(Order.patient_id).where(Order.visit_id.in_(today_visits)).distinct() + has_orders_ids = set(session.exec(stmt_has_orders).all()) + + # Pending: at least one order has NO result OR result is NOT authorized (today only) + stmt_pending = select(Order.patient_id).outerjoin(Result, Order.id == Result.order_id).where( + Order.visit_id.in_(today_visits), + or_(Result.id == None, Result.authorized == False) + ).distinct() + pending_ids = set(session.exec(stmt_pending).all()) + pending_patients_count = len(pending_ids) + + # Done: ALL tests are double authorized (today only) + stmt_not_done = select(Order.patient_id).outerjoin(Result, Order.id == Result.order_id).where( + Order.visit_id.in_(today_visits), + or_(Result.id == None, Result.double_authorized == False) + ).distinct() + not_done_ids = set(session.exec(stmt_not_done).all()) + + done_ids = has_orders_ids - not_done_ids + done_patients_count = len(done_ids) + + # Waiting: ALL tests are AUTH, but at least one NOT Double AUTH (today only) + waiting_ids = has_orders_ids - pending_ids - done_ids + waiting_patients_count = len(waiting_ids) + + # Deleted patients + deleted_patients_count = session.exec(select(func.count(DeletedRecord.id)).where(DeletedRecord.source_table == "patient")).one() + + # Call Centre (today only) + call_centre_total = done_patients_count + done_ids_list = list(done_ids) if done_ids else [-1] + sent_count = session.exec(select(func.count(func.distinct(PatientVisit.patient_id))).where(PatientVisit.patient_id.in_(done_ids_list), PatientVisit.is_called == True)).one() + not_sent_count = call_centre_total - sent_count + + # Critical Value Alerts (Last 10 PANIC results) + stmt_critical = select(ResultDetail, Order, Patient, Parameter, Result).join(Result, Result.id == ResultDetail.result_id).join(Order, Order.id == Result.order_id).join(Patient, Patient.id == Order.patient_id).join(Parameter, Parameter.id == ResultDetail.parameter_id).where(ResultDetail.flag == "⚠ PANIC").order_by(Result.entered_at.desc()).limit(10) + critical_data = session.exec(stmt_critical).all() + critical_alerts = [] + for cd, order, pat, param, res in critical_data: + critical_alerts.append({ + "patient_name": pat.full_name, + "patient_id": pat.patient_id, + "test_name": param.parameter_name, + "value": cd.result_value, + "date": res.entered_at.strftime('%Y-%m-%d %H:%M') if res.entered_at else "" + }) + # Also standalone test panics + stmt_critical_main = select(Result, Order, Patient, TestDefinition).join(Order, Order.id == Result.order_id).join(Patient, Patient.id == Order.patient_id).join(TestDefinition, TestDefinition.id == Order.test_id).where(Result.flag == "⚠ PANIC").order_by(Result.entered_at.desc()).limit(10) + critical_main_data = session.exec(stmt_critical_main).all() + for cm, order, pat, test in critical_main_data: + critical_alerts.append({ + "patient_name": pat.full_name, + "patient_id": pat.patient_id, + "test_name": test.test_name, + "value": cm.result_value, + "date": cm.entered_at.strftime('%Y-%m-%d %H:%M') if cm.entered_at else "" + }) + critical_alerts.sort(key=lambda x: x["date"], reverse=True) + critical_alerts = critical_alerts[:10] + + # Demographics + males = session.exec(select(func.count(Patient.id)).where(func.lower(Patient.gender) == "male")).one() + females = session.exec(select(func.count(Patient.id)).where(func.lower(Patient.gender) == "female")).one() + + # Top Requested Tests + top_tests_stmt = select(TestDefinition.test_name, func.count(Order.id).label("count")).join(Order, Order.test_id == TestDefinition.id).group_by(TestDefinition.test_name).order_by(func.count(Order.id).desc()).limit(5) + top_tests = session.exec(top_tests_stmt).all() + + dashboard_data = { + "today_patients": today_patients_count, + "pending_patients": pending_patients_count, + "waiting_patients": waiting_patients_count, + "done_patients": done_patients_count, + "deleted_patients": deleted_patients_count, + "call_center_total": call_centre_total, + "call_center_sent": sent_count, + "call_center_not_sent": not_sent_count, + "critical_alerts": critical_alerts, + "males": males, + "females": females, + "top_tests": [{"name": t[0], "count": t[1]} for t in top_tests] + } + + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse( + "dashboard.html", + {"request": request, "message_success": success, "message_error": error, "current_user": current_user, "dash": dashboard_data} + ) + +@router.get("/login", response_class=HTMLResponse) +def login_page(request: Request, session: Session = Depends(get_session)): + # If already logged in, redirect to dashboard + current_user = get_current_user(request, session) + if current_user: + return RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER) + return templates.TemplateResponse("login.html", {"request": request}) + +@router.post("/login") +def login_submit(request: Request, username: str = Form(...), password: str = Form(...), session: Session = Depends(get_session)): + from itsdangerous import URLSafeSerializer + import uuid + from datetime import timedelta + s = URLSafeSerializer(SECRET_KEY) + user = session.exec(select(User).where(User.username == username)).first() + + if user: + if user.locked_until and user.locked_until > datetime.now(): + return templates.TemplateResponse("login.html", {"request": request, "message_error": f"Account is locked. Try again after {user.locked_until.strftime('%H:%M')}."}) + elif user.locked_until and user.locked_until <= datetime.now(): + user.locked_until = None + user.failed_login_attempts = 0 + session.commit() + + if user and pwd_context.verify(password, user.hashed_password) and user.is_active: + user.failed_login_attempts = 0 + user.locked_until = None + user.session_token = uuid.uuid4().hex + user.last_seen = datetime.now() + + # Create session cookie + cookie_value = s.dumps({"user_id": user.id, "username": user.username, "session_token": user.session_token}) + + log_activity_action( + session=session, + action_type="LOGIN", + description="Successful password login via portal", + current_user=user, + target_type="system" + ) + session.commit() + + response = RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER) + response.set_cookie( + key="nexlab_session", + value=cookie_value, + httponly=True, + max_age=60 * 60 * 2, # 2 hours + samesite="lax" + ) + return response + else: + if user: + user.failed_login_attempts += 1 + if user.failed_login_attempts >= 10: + user.locked_until = datetime.now() + timedelta(minutes=60) + log_activity_action( + session=session, + action_type="ACCOUNT_LOCKED", + description="User account locked due to 10 failed login attempts", + current_user=user, + target_type="system" + ) + else: + log_activity_action( + session=session, + action_type="LOGIN_FAILED", + description=f"Failed login attempt ({user.failed_login_attempts}/10)", + current_user=user, + target_type="system" + ) + session.commit() + return templates.TemplateResponse("login.html", {"request": request, "message_error": "Invalid username or password"}) + +@router.get("/logout") +def logout(request: Request, session: Session = Depends(get_session)): + current_user = get_current_user(request, session) + + if current_user: + log_activity_action( + session=session, + action_type="LOGOUT", + description="User logged out manually", + current_user=current_user, + target_type="system" + ) + current_user.session_token = None + session.commit() + + response = RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) + response.delete_cookie("nexlab_session") + return response \ No newline at end of file diff --git a/routes/cal_control.py b/routes/cal_control.py new file mode 100644 index 0000000000000000000000000000000000000000..859b78bda852ef45ae72bbe23fc5e978c01548d8 --- /dev/null +++ b/routes/cal_control.py @@ -0,0 +1,151 @@ +# routes/cal_control.py +from fastapi import APIRouter, Depends, Request, Form, status +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlmodel import Session, select +from datetime import datetime +from database import get_session +from models import CalControl, Inventory, TestDefinition, Device +from routes.helpers import templates, get_current_user, require_permission, create_audit_log, model_to_dict +from typing import Optional +from sqlalchemy.orm import selectinload + +router = APIRouter() + +@router.get("/cal-control", response_class=HTMLResponse) +def cal_control_page(request: Request, session: Session = Depends(get_session)): + # Use inventory permission as primary for accessing this page + if not (require_permission(request, session, "inventory") or require_permission(request, session, "tests")): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all() + devices = session.exec(select(Device).where(Device.is_active == True)).all() + + date_from = request.query_params.get("date_from") + date_to = request.query_params.get("date_to") + search_test_id = request.query_params.get("search_test_id") + search_device_id = request.query_params.get("search_device_id") + search_process_type = request.query_params.get("search_process_type") + is_search = request.query_params.get("search") == "true" + + history = [] + if is_search: + history_query = select(CalControl).options( + selectinload(CalControl.test), + selectinload(CalControl.device) + ).order_by(CalControl.created_at.desc()) + + if date_from: + try: + df = datetime.strptime(date_from, "%Y-%m-%d").replace(hour=0, minute=0, second=0) + history_query = history_query.where(CalControl.created_at >= df) + except: + pass + if date_to: + try: + dt = datetime.strptime(date_to, "%Y-%m-%d").replace(hour=23, minute=59, second=59) + history_query = history_query.where(CalControl.created_at <= dt) + except: + pass + if search_test_id: + history_query = history_query.where(CalControl.test_id == int(search_test_id)) + if search_device_id: + history_query = history_query.where(CalControl.device_id == int(search_device_id)) + if search_process_type: + history_query = history_query.where(CalControl.process_type == search_process_type) + + history = session.exec(history_query).all() + + # Default to today if not provided + default_date = datetime.now().strftime("%Y-%m-%d") + + return templates.TemplateResponse("cal_control.html", { + "request": request, + "tests": tests, + "devices": devices, + "history": history, + "is_search": is_search, + "date_from": date_from or default_date, + "date_to": date_to or default_date, + "search_test_id": search_test_id, + "search_device_id": search_device_id, + "search_process_type": search_process_type, + "message_success": request.query_params.get("success"), + "message_error": request.query_params.get("error") + }) + +@router.post("/cal-control/create") +def create_cal_control( + test_id: int = Form(...), + device_id: int = Form(...), + process_type: str = Form(...), # "Cal" or "Control" + quantity: float = Form(...), + note: Optional[str] = Form(None), + request: Request = None, + session: Session = Depends(get_session) +): + if not (require_permission(request, session, "inventory", "edit") or require_permission(request, session, "tests")): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + if quantity <= 0: + return RedirectResponse(url="/cal-control?error=Quantity must be greater than zero", status_code=status.HTTP_303_SEE_OTHER) + + try: + current_user = get_current_user(request, session) + + # Determine total tests required + remaining_qty = quantity + + # Fetch inventory for this test_id ordered by nearest expiration first + inventory_items = session.exec( + select(Inventory) + .where(Inventory.test_id == test_id) + .where(Inventory.material_type == "Test") + .where(Inventory.is_active == True) + .where(Inventory.quantity > 0) + .order_by(Inventory.expiration_date.asc()) + ).all() + + # Check if enough inventory exists + total_inv = sum(item.quantity for item in inventory_items) + if total_inv < quantity: + return RedirectResponse(url="/cal-control?error=Not enough tests in inventory. Total available: " + str(total_inv), status_code=status.HTTP_303_SEE_OTHER) + + # Deduct from inventory + for item in inventory_items: + if remaining_qty <= 0: + break + + if item.quantity >= remaining_qty: + old_val = model_to_dict(item) + item.quantity -= remaining_qty + item.edited_by = current_user.id if current_user else None + item.edited_at = datetime.now() + remaining_qty = 0 + create_audit_log(session, "inventory", item.id, "update_cal_control", current_user, old_values=old_val, new_values=model_to_dict(item)) + else: + old_val = model_to_dict(item) + remaining_qty -= item.quantity + item.quantity = 0 + item.edited_by = current_user.id if current_user else None + item.edited_at = datetime.now() + create_audit_log(session, "inventory", item.id, "update_cal_control", current_user, old_values=old_val, new_values=model_to_dict(item)) + + session.add(item) + + # Create CalControl entry + new_cal = CalControl( + test_id=test_id, + device_id=device_id, + process_type=process_type, + quantity=quantity, + note=note, + created_by=current_user.id if current_user else None + ) + session.add(new_cal) + session.commit() + session.refresh(new_cal) + + return RedirectResponse(url="/cal-control?success=Process recorded successfully and inventory deducted.", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/cal-control?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) diff --git a/routes/call_centre.py b/routes/call_centre.py new file mode 100644 index 0000000000000000000000000000000000000000..80c52808329d626d5af6b1ab95e01d7b6a4d6693 --- /dev/null +++ b/routes/call_centre.py @@ -0,0 +1,466 @@ +# routes/call_centre.py +from fastapi import APIRouter, Depends, HTTPException, Request +from fastapi.responses import HTMLResponse +from fastapi.encoders import jsonable_encoder +from pydantic import BaseModel +from sqlmodel import Session, select +from sqlalchemy.orm import selectinload +from typing import List, Optional +import json +import traceback +from datetime import datetime + +from database import get_session +from models import Patient, PatientVisit, Order, Result, TestRange, LabInfo, PrintTemplate, Inventory, TestDefinition, TestParameter, TestResultType +# ✅ Shared templates (with AutoUserTemplates) + helpers +from routes.helpers import templates, get_current_user, log_audit_action, log_activity_action, require_permission, age_to_days +from fastapi.responses import RedirectResponse, JSONResponse +from routes.whatsapp_utils import generate_report_pdf, send_wati_pdf + +# --- Google Gemini AI Setup --- +import os +import google.generativeai as genai +_gemini_key = os.environ.get("GEMINI_API_KEY") +if _gemini_key: + genai.configure(api_key=_gemini_key) + +class AIRequest(BaseModel): + prompt: str + +class WhatsAppPayload(BaseModel): + order_ids: Optional[List[int]] = None + +router = APIRouter(tags=["Call Centre"]) + +@router.get("/call-centre", response_class=HTMLResponse) +def call_centre_list( + request: Request, + start_date: Optional[str] = None, + end_date: Optional[str] = None, + name: Optional[str] = None, + patient_id: Optional[str] = None, + test: Optional[str] = None, + status_filter: Optional[str] = "All", # Added toggle filter + session: Session = Depends(get_session) +): + if not require_permission(request, session, "call_centre"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=303) + # Pagination + try: + page = max(1, int(request.query_params.get("page", 1))) + except (ValueError, TypeError): + page = 1 + + PAGE_SIZE = 50 + + # 1. Default dates to TODAY if not provided + today_str = datetime.now().strftime('%Y-%m-%d') + if not start_date: + start_date = today_str + if not end_date: + end_date = today_str + + # Ensure Order.result is loaded to check authorization levels + query = select(PatientVisit).options( + selectinload(PatientVisit.patient), + selectinload(PatientVisit.orders).selectinload(Order.test), + selectinload(PatientVisit.orders).selectinload(Order.result) + ) + + # Date Filtering (Appending 23:59:59 ensures the entire end_date is included) + query = query.where(PatientVisit.visit_date >= start_date) + query = query.where(PatientVisit.visit_date <= f"{end_date} 23:59:59") + + if patient_id: + query = query.where(PatientVisit.visit_id.like(f"%{patient_id}%")) + if name: + query = query.join(Patient).where(Patient.full_name.like(f"%{name}%")) + + visits = session.exec(query.order_by(PatientVisit.visit_date.desc())).all() + + patient_data = [] + for v in visits: + test_list = [o.test.test_name for o in v.orders if o.test] + if test and test.lower() not in " ".join(test_list).lower(): + continue + + total_tests = len(v.orders) + + # 2. Strict Status Logic + has_pending = False + all_double_auth = True + + if total_tests == 0: + has_pending = True + all_double_auth = False + else: + for o in v.orders: + res = o.result + if not res or not res.authorized: + has_pending = True + all_double_auth = False + break + else: + # Safely check for double auth status (handles different possible column names) + is_da = getattr(res, 'double_authorized', getattr(res, 'is_double_authorized', False)) + if not is_da: + all_double_auth = False + + if has_pending: + status_text = "Pending" + status_color = "amber" + elif all_double_auth: + status_text = "Double Auth" + status_color = "emerald" + else: + status_text = "Authorize" # Authorized, but not double authorized yet + status_color = "blue" + + # 3. Apply Toggle Filters + if status_filter == "Pending": + # Show if ANY test is pending OR it's only single 'Authorize' (Not Double Auth) + if status_text == "Double Auth": + continue + elif status_filter == "Not Done": + # Show ONLY if all are Double Auth, but the patient hasn't been called yet + if status_text != "Double Auth" or v.is_called: + continue + elif status_filter == "Call done": + # Show ONLY if the call is completed + if not v.is_called: + continue + + patient_data.append({ + "registration_date": v.visit_date, + "patient": v.patient, + "visit": v, + "tests_names": ", ".join(test_list[:3]) + ("..." if len(test_list) > 3 else ""), + "status": status_text, + "status_color": status_color, + "is_called": v.is_called, + "is_printed": v.is_printed + }) + + # Paginate the results + total_count = len(patient_data) + total_pages = max(1, (total_count + PAGE_SIZE - 1) // PAGE_SIZE) + page = min(page, total_pages) + offset = (page - 1) * PAGE_SIZE + patient_data_page = patient_data[offset:offset + PAGE_SIZE] + + return templates.TemplateResponse("call_centre.html", { + "request": request, + "patient_data": patient_data_page, + "filters": { + "start_date": start_date, + "end_date": end_date, + "name": name or "", + "patient_id": patient_id or "", + "test": test or "", + "status_filter": status_filter + }, + "page": page, + "total_pages": total_pages, + "total_count": total_count, + }) + +@router.get("/view-call-centre/{visit_id}", response_class=HTMLResponse) +def view_call_centre_patient(visit_id: str, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "call_centre"): + return RedirectResponse(url="/call-centre?error=Permission Denied", status_code=303) + visit = session.exec( + select(PatientVisit) + .options( + selectinload(PatientVisit.patient), + selectinload(PatientVisit.orders).selectinload(Order.test), + selectinload(PatientVisit.orders).selectinload(Order.result).selectinload(Result.details) + ) + .where(PatientVisit.visit_id == visit_id) + ).first() + + if not visit: + raise HTTPException(status_code=404, detail="Visit not found") + + patient = visit.patient + visit_user_name = "System" + if visit and visit.created_by: + from models import User + user = session.get(User, visit.created_by) + if user: + visit_user_name = user.full_name or user.username + + # Fetch all visits for the "Previous Results" bar + all_visits = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.visit_date.asc()) + ).all() + + return templates.TemplateResponse("call_centre_view.html", { + "request": request, + "patient": patient, + "visit": visit, + "visit_user_name": visit_user_name, + "all_visits": all_visits + }) + +# ✅ NEW: Added request dependency to track WHO marked the patient as called +@router.post("/api/mark-called/{visit_id}") +def mark_called(visit_id: str, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "call_centre", "mark_called"): + return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403) + current_user = get_current_user(request, session) + visit = session.exec(select(PatientVisit).where(PatientVisit.visit_id == visit_id)).first() + if not visit: + raise HTTPException(status_code=404, detail="Visit not found") + + visit.is_called = True + session.add(visit) + + # --------------------------------------------------------- + # ✅ NEW: INJECT AUDIT LOG HERE (Tracking Call Centre mark) + # --------------------------------------------------------- + log_audit_action( + session=session, + table_name="patientvisit", + record_id=visit.id, + action="UPDATE", + current_user=current_user, + new_values={"action": "Patient marked as Called"} + ) + # --------------------------------------------------------- + + session.commit() + return {"success": True} + +@router.post("/api/mark-printed/{visit_id}") +def mark_printed(visit_id: str, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "call_centre", "mark_printed"): + return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403) + current_user = get_current_user(request, session) + visit = session.exec(select(PatientVisit).options(selectinload(PatientVisit.orders)).where(PatientVisit.visit_id == visit_id)).first() + if not visit: + raise HTTPException(status_code=404, detail="Visit not found") + + if not visit.is_printed: + # Automatic deduction of tests from inventory + for order in visit.orders: + if order.test_id and order.status != "no_sample": + # Find available tests in inventory ordered by nearest expiration_date + inventory_items = session.exec( + select(Inventory).where( + Inventory.material_type == "Test", + Inventory.test_id == order.test_id, + Inventory.quantity > 0 + ).order_by(Inventory.expiration_date.asc()) + ).all() + + if inventory_items: + # Deduct 1 from the nearest expiring item + inventory_items[0].quantity -= 1 + session.add(inventory_items[0]) + + visit.is_printed = True + session.add(visit) + + # --------------------------------------------------------- + # ✅ INJECT AUDIT LOG HERE (Tracking Results Print) + # --------------------------------------------------------- + log_audit_action( + session=session, + table_name="patientvisit", + record_id=visit.id, + action="UPDATE", + current_user=current_user, + new_values={"action": "Patient Results Printed"} + ) + # --------------------------------------------------------- + + session.commit() + return {"success": True} + +# ✅ NEW: Added request dependency to track WHO sent the WhatsApp message +@router.post("/api/send-whatsapp/{visit_id}") +def send_whatsapp_results(visit_id: str, request: Request, payload: Optional[WhatsAppPayload] = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "call_centre", "send_whatsapp"): + return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403) + current_user = get_current_user(request, session) + visit = session.exec(select(PatientVisit).where(PatientVisit.visit_id == visit_id)).first() + if not visit: + raise HTTPException(status_code=404, detail="Visit not found") + + patient = session.get(Patient, visit.patient_id) + if not patient: + raise HTTPException(status_code=404, detail="Patient not found") + + query = select(Order).options( + selectinload(Order.test).selectinload(TestDefinition.test_parameters).selectinload(TestParameter.parameter), + selectinload(Order.result).selectinload(Result.details) + ).where(Order.visit_id == visit.id, Order.status != "no_sample") + if payload and payload.order_ids: + query = query.where(Order.id.in_(payload.order_ids)) + + orders = session.exec(query).all() + test_ids = [order.test_id for order in orders if order.test_id] + all_result_types = session.exec( + select(TestResultType).where(TestResultType.test_id.in_(test_ids), TestResultType.is_active == True) + ).all() + result_type_map = {} + for rt in all_result_types: + result_type_map[(rt.test_id, rt.parameter_id)] = rt.result_type + + def get_result_type(test_id, param_id=None): + return result_type_map.get((test_id, param_id), "number") + + structured_results = [] + for order in orders: + test = order.test + res = order.result + if not test: continue + + # Fetch ranges for this test/patient (same logic as print report) + ranges = session.exec( + select(TestRange).where(TestRange.test_id == test.id, TestRange.is_active == True) + ).all() + + patient_days = age_to_days(patient.age or 0, patient.age_unit or "year") + + def find_range(param_id=None): + best = None + for r in ranges: + if r.parameter_id == param_id: + gender_ok = r.gender_type == "both" or r.gender_type == patient.gender + range_from_days = age_to_days(r.age_from, r.age_from_unit or "year") + range_to_days = age_to_days(r.age_to, r.age_to_unit or "year") + age_ok = range_from_days <= patient_days <= range_to_days + if gender_ok and age_ok: + best = r + break + if not best and ranges: + for r in ranges: + if r.parameter_id == param_id: + return r + return best + + if test.test_parameters: + structured_results.append({"type": "parent", "test_name": test.test_name, "print_separately": test.print_separately, "note": res.note if res else ""}) + for tp in test.test_parameters: + p = tp.parameter + d = next((dt for dt in res.details if dt.parameter_id == p.id), None) if res else None + rng = find_range(p.id) + structured_results.append({ + "type": "child", "parameter_name": p.parameter_name, "result_value": d.result_value if d else "-", + "result_type": get_result_type(test.id, p.id), + "unit": rng.unit if rng else "", + "range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""), + "flag": d.flag if d else "", + "remark": d.remark if d else "" + }) + else: + rng = find_range(None) + structured_results.append({ + "type": "standalone", "test_name": test.test_name, "result_value": res.result_value if res else "-", + "result_type": get_result_type(test.id, None), + "unit": rng.unit if rng else "", + "range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""), + "flag": res.flag if res else "", + "note": res.note if res else "", + "print_separately": test.print_separately + }) + + lab_info = session.exec(select(LabInfo).limit(1)).first() or LabInfo(lab_name="NexLab") + template_obj = session.exec(select(PrintTemplate).where(PrintTemplate.template_name == "result_report")).first() + + template_data = { + "elements": [], + "paperSize": "A4" + } + if template_obj: + try: + elements = template_obj.elements + if isinstance(elements, str): + elements = json.loads(elements) + if isinstance(elements, dict): + template_data = elements + else: + template_data["elements"] = elements + except Exception: + pass + + from routes.helpers import generate_barcode_base64 + barcode_data = generate_barcode_base64(patient.patient_id) + if "base64," in barcode_data: + barcode_data = barcode_data.split("base64,")[1] + + try: + pdf_bytes = generate_report_pdf( + jsonable_encoder(patient), + jsonable_encoder(visit), + structured_results, + jsonable_encoder(lab_info), + template_data, + barcode_data + ) + + to_phone = patient.phone_number + if not to_phone: + raise HTTPException(status_code=400, detail="Patient phone number not found") + + to_phone = to_phone.strip().replace(" ", "") + country_code = getattr(lab_info, 'phone_country_code', '964') or '964' + if not to_phone.startswith('+'): + to_phone = "+" + (to_phone if to_phone.startswith(country_code) else country_code + to_phone.lstrip('0')) + + safe_name = "".join(c for c in patient.full_name if c.isalnum() or c in (' ', '_', '-')).strip() + filename = f"{safe_name}.pdf" + caption = f"{patient.full_name}" + + # Using dynamic lab_info credentials! + report = send_wati_pdf(to_phone, pdf_bytes, filename, caption, jsonable_encoder(lab_info)) + + if report.get('status') != 'error' and not str(report.get('result')).lower() == 'error': + visit.is_whatsapp_sent = True + session.add(visit) + + # --------------------------------------------------------- + # ✅ NEW: INJECT AUDIT LOG HERE (Tracking WhatsApp Dispatch) + # --------------------------------------------------------- + log_audit_action( + session=session, + table_name="patientvisit", + record_id=visit.id, + action="DISPATCH", + current_user=current_user, + new_values={"action": "Results sent to patient via WhatsApp", "phone": to_phone} + ) + # --------------------------------------------------------- + + session.commit() + + # Activity Log: WhatsApp sent + log_activity_action(session, "SEND_WHATSAPP", f"Sent results via WhatsApp to {to_phone} for patient {patient.full_name}", current_user, "patient", patient.id) + session.commit() + + return {"success": True, "message": "Result sent successfully"} + else: + return {"success": False, "error": report.get('message', 'WhatsApp API Error')} + + except Exception as e: + traceback.print_exc() + raise HTTPException(status_code=500, detail=f"Error: {str(e)}") + + +# ========================================== +# 🤖 FREE AI ANALYSIS ROUTE +# ========================================== +@router.post("/api/ai-analyse") +async def ai_analyse_results(req: AIRequest): + if not _gemini_key: + return {"success": False, "error": "AI service not configured. Set GEMINI_API_KEY environment variable."} + try: + model = genai.GenerativeModel('gemini-2.5-flash') + response = model.generate_content(req.prompt) + return {"success": True, "analysis": response.text} + except Exception as e: + print(f"AI Error: {e}") + return {"success": False, "error": str(e)} \ No newline at end of file diff --git a/routes/departments.py b/routes/departments.py new file mode 100644 index 0000000000000000000000000000000000000000..27b2fc3ccb6cd2e4e3754d1b5872ffbfbe323261 --- /dev/null +++ b/routes/departments.py @@ -0,0 +1,407 @@ +# routes/departments.py +# CRUD routes for: Departments, Sample Types, Devices, Parameters, Report Notes. + +from fastapi import APIRouter, Depends, Request, Form, status +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlmodel import Session, select +from datetime import datetime +from typing import Optional +from database import get_session +from models import Department, SampleType, Device, Parameter, ReportNote +from routes.helpers import templates, get_current_user, create_audit_log, model_to_dict, require_permission + +router = APIRouter() + +# =========================== +# DEPARTMENTS ROUTES +# =========================== +@router.get("/departments", response_class=HTMLResponse) +def departments_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "departments"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + departments = session.exec(select(Department).order_by(Department.id.asc())).all() + departments_dict = [model_to_dict(d) for d in departments] + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("departments.html", { + "request": request, "departments": departments, + "departments_json": departments_dict, "message_success": success, "message_error": error + }) + +@router.post("/departments/create") +def create_department(department_name: str = Form(...), department_note: Optional[str] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "departments", "create"): + return RedirectResponse(url="/departments?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + new_department = Department(department_name=department_name, department_note=department_note, is_active=True, + created_by=current_user.id if current_user else None) + session.add(new_department) + session.commit() + session.refresh(new_department) + create_audit_log(session, "department", new_department.id, "create", current_user, new_values=model_to_dict(new_department)) + return RedirectResponse(url="/departments?success=Department saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/departments?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/departments/update/{dept_id}") +def update_department(dept_id: int, department_name: str = Form(...), department_note: Optional[str] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "departments", "edit"): + return RedirectResponse(url="/departments?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + dept = session.get(Department, dept_id) + if dept: + old_values = model_to_dict(dept) + dept.department_name = department_name + dept.department_note = department_note + dept.edited_by = current_user.id if current_user else None + dept.edited_at = datetime.now() + session.add(dept) + session.commit() + session.refresh(dept) + create_audit_log(session, "department", dept.id, "update", current_user, old_values=old_values, new_values=model_to_dict(dept)) + return RedirectResponse(url="/departments?success=Department updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/departments?error=Department not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/departments?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/departments/delete/{dept_id}") +def delete_department(dept_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "departments", "delete"): + return RedirectResponse(url="/departments?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + dept = session.get(Department, dept_id) + if dept: + old_values = model_to_dict(dept) + create_audit_log(session, "department", dept.id, "delete", current_user, old_values=old_values) + session.delete(dept) + session.commit() + return RedirectResponse(url="/departments?success=Department deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/departments?error=Department not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/departments?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# SAMPLE TYPES ROUTES +# =========================== +@router.get("/sample-types", response_class=HTMLResponse) +def sample_types_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "sample_types"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + sample_types = session.exec(select(SampleType).order_by(SampleType.id.asc())).all() + sample_types_dict = [model_to_dict(s) for s in sample_types] + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("sample_types.html", { + "request": request, "sample_types": sample_types, + "sample_types_json": sample_types_dict, "message_success": success, "message_error": error + }) + +@router.post("/sample-types/create") +def create_sample_type(sample_name: str = Form(...), sample_note: Optional[str] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "sample_types", "create"): + return RedirectResponse(url="/sample-types?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + new_sample_type = SampleType(sample_name=sample_name, sample_note=sample_note, is_active=True, + created_by=current_user.id if current_user else None) + session.add(new_sample_type) + session.commit() + session.refresh(new_sample_type) + create_audit_log(session, "sampletype", new_sample_type.id, "create", current_user, new_values=model_to_dict(new_sample_type)) + return RedirectResponse(url="/sample-types?success=Sample type saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/sample-types?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/sample-types/update/{sample_id}") +def update_sample_type(sample_id: int, sample_name: str = Form(...), sample_note: Optional[str] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "sample_types", "edit"): + return RedirectResponse(url="/sample-types?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + sample = session.get(SampleType, sample_id) + if sample: + old_values = model_to_dict(sample) + sample.sample_name = sample_name + sample.sample_note = sample_note + sample.edited_by = current_user.id if current_user else None + sample.edited_at = datetime.now() + session.add(sample) + session.commit() + session.refresh(sample) + create_audit_log(session, "sampletype", sample.id, "update", current_user, old_values=old_values, new_values=model_to_dict(sample)) + return RedirectResponse(url="/sample-types?success=Sample type updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/sample-types?error=Sample type not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/sample-types?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/sample-types/delete/{sample_id}") +def delete_sample_type(sample_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "sample_types", "delete"): + return RedirectResponse(url="/sample-types?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + sample = session.get(SampleType, sample_id) + if sample: + old_values = model_to_dict(sample) + create_audit_log(session, "sampletype", sample.id, "delete", current_user, old_values=old_values) + session.delete(sample) + session.commit() + return RedirectResponse(url="/sample-types?success=Sample type deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/sample-types?error=Sample type not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/sample-types?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# DEVICES ROUTES +# =========================== +@router.get("/devices", response_class=HTMLResponse) +def devices_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "devices"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + devices = session.exec(select(Device).order_by(Device.id.asc())).all() + devices_dict = [model_to_dict(d) for d in devices] + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("devices.html", { + "request": request, "devices": devices, + "devices_json": devices_dict, "message_success": success, "message_error": error + }) + +@router.post("/devices/create") +def create_device(device_name: str = Form(...), serial_number: str = Form(...), install_date: str = Form(...), + installer_name: str = Form(...), installer_phone: str = Form(...), note: Optional[str] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "devices", "create"): + return RedirectResponse(url="/devices?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + install_dt = datetime.strptime(install_date, "%Y-%m-%d") + new_device = Device(device_name=device_name, serial_number=serial_number, install_date=install_dt, + installer_name=installer_name, installer_phone=installer_phone, note=note, is_active=True, + created_by=current_user.id if current_user else None) + session.add(new_device) + session.commit() + session.refresh(new_device) + create_audit_log(session, "device", new_device.id, "create", current_user, new_values=model_to_dict(new_device)) + return RedirectResponse(url="/devices?success=Device saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/devices?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/devices/update/{device_id}") +def update_device(device_id: int, device_name: str = Form(...), serial_number: str = Form(...), install_date: str = Form(...), + installer_name: str = Form(...), installer_phone: str = Form(...), note: Optional[str] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "devices", "edit"): + return RedirectResponse(url="/devices?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + device = session.get(Device, device_id) + if device: + old_values = model_to_dict(device) + device.device_name = device_name + device.serial_number = serial_number + device.install_date = datetime.strptime(install_date, "%Y-%m-%d") + device.installer_name = installer_name + device.installer_phone = installer_phone + device.note = note + device.edited_by = current_user.id if current_user else None + device.edited_at = datetime.now() + session.add(device) + session.commit() + session.refresh(device) + create_audit_log(session, "device", device.id, "update", current_user, old_values=old_values, new_values=model_to_dict(device)) + return RedirectResponse(url="/devices?success=Device updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/devices?error=Device not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/devices?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/devices/delete/{device_id}") +def delete_device(device_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "devices", "delete"): + return RedirectResponse(url="/devices?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + device = session.get(Device, device_id) + if device: + old_values = model_to_dict(device) + create_audit_log(session, "device", device.id, "delete", current_user, old_values=old_values) + session.delete(device) + session.commit() + return RedirectResponse(url="/devices?success=Device deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/devices?error=Device not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/devices?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# PARAMETERS ROUTES +# =========================== +@router.get("/parameters", response_class=HTMLResponse) +def parameters_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "parameters"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + parameters = session.exec(select(Parameter).order_by(Parameter.id.asc())).all() + parameters_dict = [model_to_dict(p) for p in parameters] + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("parameters.html", { + "request": request, "parameters": parameters, + "parameters_json": parameters_dict, "message_success": success, "message_error": error + }) + +@router.post("/parameters/create") +def create_parameter(parameter_name: str = Form(...), parameter_short_name: str = Form(...), + is_header: str = Form(None), request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "parameters", "create"): + return RedirectResponse(url="/parameters?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + # Check for duplicate name before inserting + existing = session.exec(select(Parameter).where(Parameter.parameter_name == parameter_name)).first() + if existing: + return RedirectResponse(url=f"/parameters?error=Parameter '{parameter_name}' already exists!", status_code=status.HTTP_303_SEE_OTHER) + is_header_bool = True if is_header == "on" else False + new_parameter = Parameter(parameter_name=parameter_name, parameter_short_name=parameter_short_name.upper(), + is_header=is_header_bool, created_by=current_user.id if current_user else None) + session.add(new_parameter) + session.commit() + session.refresh(new_parameter) + create_audit_log(session, "parameter", new_parameter.id, "create", current_user, new_values=model_to_dict(new_parameter)) + return RedirectResponse(url="/parameters?success=Parameter saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/parameters?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/parameters/update/{param_id}") +def update_parameter(param_id: int, parameter_name: str = Form(...), parameter_short_name: str = Form(...), + is_header: str = Form(None), request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "parameters", "edit"): + return RedirectResponse(url="/parameters?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + param = session.get(Parameter, param_id) + if param: + old_values = model_to_dict(param) + param.parameter_name = parameter_name + param.parameter_short_name = parameter_short_name.upper() + param.is_header = True if is_header == "on" else False + param.edited_by = current_user.id if current_user else None + param.edited_at = datetime.now() + session.add(param) + session.commit() + session.refresh(param) + create_audit_log(session, "parameter", param.id, "update", current_user, old_values=old_values, new_values=model_to_dict(param)) + return RedirectResponse(url="/parameters?success=Parameter updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/parameters?error=Parameter not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/parameters?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/parameters/delete/{param_id}") +def delete_parameter(param_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "parameters", "delete"): + return RedirectResponse(url="/parameters?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + param = session.get(Parameter, param_id) + if param: + old_values = model_to_dict(param) + create_audit_log(session, "parameter", param.id, "delete", current_user, old_values=old_values) + session.delete(param) + session.commit() + return RedirectResponse(url="/parameters?success=Parameter deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/parameters?error=Parameter not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/parameters?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# REPORT NOTES ROUTES +# =========================== +@router.get("/report-notes", response_class=HTMLResponse) +def report_notes_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "report_notes"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + report_notes = session.exec(select(ReportNote).order_by(ReportNote.id.asc())).all() + report_notes_dict = [model_to_dict(n) for n in report_notes] + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("report_notes.html", { + "request": request, "report_notes": report_notes, + "report_notes_json": report_notes_dict, "message_success": success, "message_error": error + }) + +@router.post("/report-notes/create") +def create_report_note(note_name: str = Form(...), note_content: str = Form(...), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "report_notes", "create"): + return RedirectResponse(url="/report-notes?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + new_note = ReportNote(note_name=note_name, note_content=note_content, is_active=True, + created_by=current_user.id if current_user else None) + session.add(new_note) + session.commit() + session.refresh(new_note) + create_audit_log(session, "reportnote", new_note.id, "create", current_user, new_values=model_to_dict(new_note)) + return RedirectResponse(url="/report-notes?success=Report note saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/report-notes?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/report-notes/update/{note_id}") +def update_report_note(note_id: int, note_name: str = Form(...), note_content: str = Form(...), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "report_notes", "edit"): + return RedirectResponse(url="/report-notes?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + note = session.get(ReportNote, note_id) + if note: + old_values = model_to_dict(note) + note.note_name = note_name + note.note_content = note_content + note.edited_by = current_user.id if current_user else None + note.edited_at = datetime.now() + session.add(note) + session.commit() + session.refresh(note) + create_audit_log(session, "reportnote", note.id, "update", current_user, old_values=old_values, new_values=model_to_dict(note)) + return RedirectResponse(url="/report-notes?success=Report note updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/report-notes?error=Report note not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/report-notes?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/report-notes/delete/{note_id}") +def delete_report_note(note_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "report_notes", "delete"): + return RedirectResponse(url="/report-notes?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + note = session.get(ReportNote, note_id) + if note: + old_values = model_to_dict(note) + create_audit_log(session, "reportnote", note.id, "delete", current_user, old_values=old_values) + session.delete(note) + session.commit() + return RedirectResponse(url="/report-notes?success=Report note deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/report-notes?error=Report note not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/report-notes?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) diff --git a/routes/double_auth.py b/routes/double_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..90f4ba78c2892591d506cd7d640cb521f87e1d95 --- /dev/null +++ b/routes/double_auth.py @@ -0,0 +1,267 @@ +# routes/double_auth.py +from fastapi import APIRouter, Depends, Request +from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse +from sqlmodel import Session, select +from sqlalchemy.orm import selectinload +from datetime import datetime + +from database import get_session +from models import Patient, PatientVisit, Order, TestDefinition, Result, ResultDetail +# ✅ NEW: Added log_audit_action to imports +from routes.helpers import templates, get_current_user, log_audit_action, log_activity_action, require_permission, build_patient_visit_data + +router = APIRouter() + +# 1. Double Auth Patients List +@router.get("/double-auth", response_class=HTMLResponse) +def double_auth_patients_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "double_auth"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=303) + + patient_data, filters, page, total_pages, total_count = build_patient_visit_data(session, request) + + return templates.TemplateResponse("double_auth_patients.html", { + "request": request, + "patient_data": patient_data, + "filters": filters, + "page": page, + "total_pages": total_pages, + "total_count": total_count, + }) + +# 2. Double Auth Page +@router.get("/double-auth/{patient_id}", response_class=HTMLResponse) +def double_auth_page(patient_id: str, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "double_auth"): + return RedirectResponse(url="/double-auth?error=Permission Denied", status_code=303) + current_user = get_current_user(request, session) + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + return RedirectResponse(url="/double-auth?error=Patient not found", status_code=303) + + # Support visit_id query param to select a specific visit + visit_id_param = request.query_params.get("visit_id") + if visit_id_param: + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.visit_id == visit_id_param, PatientVisit.patient_id == patient.id) + ).first() + else: + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.id.desc()) + ).first() + + visit_user_name = None + if visit and visit.created_by: + from models import User + user = session.get(User, visit.created_by) + if user: + visit_user_name = user.full_name or user.username + + # Fetch all visits for the "Previous Results" bar + all_visits = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.visit_date.asc()) + ).all() + + return templates.TemplateResponse("double_auth.html", { + "request": request, + "patient": patient, + "visit": visit, + "visit_user_name": visit_user_name, + "all_visits": all_visits, + }) + + +# 3. Actions API +@router.post("/api/double-auth/authorize/{order_id}") +def double_authorize_order(order_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "double_auth", "double_authorize"): + return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403) + current_user = get_current_user(request, session) + if not current_user: + return JSONResponse({"success": False, "message": "Unauthorized"}, status_code=401) + + try: + order = session.get(Order, order_id) + if not order: + return JSONResponse({"success": False, "message": "Order not found"}, status_code=404) + + result = session.exec(select(Result).where(Result.order_id == order_id)).first() + if not result: + return JSONResponse({"success": False, "message": "Result not found"}, status_code=404) + + # Guard: must be authorized first before double-authorizing + if not result.authorized: + return JSONResponse({"success": False, "message": "Test must be authorized before double authorization"}, status_code=400) + + # Guard: must be in correct status + if order.status not in ("authorized", "resulted"): + return JSONResponse({"success": False, "message": f"Cannot double-authorize from status '{order.status}'"}, status_code=400) + + result.double_authorized = True + result.double_authorized_by = current_user.id + result.double_authorized_at = datetime.now() + result.unauth_reason = None + + order.status = "double_authorized" + + session.add(result) + session.add(order) + + # --------------------------------------------------------- + # ✅ NEW: INJECT AUDIT LOG HERE (Tracking Double Auth) + # --------------------------------------------------------- + log_audit_action( + session=session, + table_name="order", + record_id=order.id, + action="UPDATE", + current_user=current_user, + new_values={ + "action": "Test Double Authorized", + "status": "double_authorized" + } + ) + # --------------------------------------------------------- + + session.commit() + + # Activity Log + test_name = order.test.test_name if order.test else "Unknown" + patient = session.get(Patient, order.patient_id) if order.patient_id else None + patient_name = patient.full_name if patient else "Unknown" + log_activity_action(session, "DOUBLE_AUTH", f"Double authorized test '{test_name}' for patient {patient_name}", current_user, "patient", order.patient_id) + session.commit() + + return {"success": True, "message": "Test double authorized"} + except Exception as e: + session.rollback() + return JSONResponse({"success": False, "message": str(e)}, status_code=500) + +@router.post("/api/double-auth/rerun/{order_id}") +def rerun_order(order_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "double_auth", "rerun"): + return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403) + current_user = get_current_user(request, session) + if not current_user: + return JSONResponse({"success": False, "message": "Unauthorized"}, status_code=401) + + try: + order = session.get(Order, order_id) + if not order: + return JSONResponse({"success": False, "message": "Order not found"}, status_code=404) + + # Guard: rerun only allowed from authorized or double_authorized + if order.status not in ("authorized", "double_authorized"): + return JSONResponse({"success": False, "message": f"Cannot rerun from status '{order.status}'. Only authorized tests can be rerun."}, status_code=400) + + result = session.exec(select(Result).where(Result.order_id == order_id)).first() + if result: + # Standalone result value backup + if result.result_value: + result.rerun_result = result.result_value + result.result_value = "" + + # Reset authorization + result.authorized = False + result.authorized_by = None + result.authorized_at = None + result.double_authorized = False + result.double_authorized_by = None + result.double_authorized_at = None + + # Handle children results (ResultDetail) + details = session.exec(select(ResultDetail).where(ResultDetail.result_id == result.id)).all() + for detail in details: + if detail.result_value: + detail.rerun_result = detail.result_value + detail.result_value = "" + session.add(detail) + + session.add(result) + + order.status = "ordered" # pending + session.add(order) + + # --------------------------------------------------------- + # ✅ NEW: INJECT AUDIT LOG HERE (Tracking ReRun) + # --------------------------------------------------------- + log_audit_action( + session=session, + table_name="order", + record_id=order.id, + action="UPDATE", + current_user=current_user, + new_values={ + "action": "Test marked for ReRun", + "status": "ordered" + } + ) + # --------------------------------------------------------- + + session.commit() + return {"success": True, "message": "Test marked for rerun (pending)"} + except Exception as e: + session.rollback() + return JSONResponse({"success": False, "message": str(e)}, status_code=500) + +@router.post("/api/double-auth/unauth/{order_id}") +async def unauth_order(order_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "double_auth", "unauthorize"): + return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403) + current_user = get_current_user(request, session) + if not current_user: + return JSONResponse({"success": False, "message": "Unauthorized"}, status_code=401) + + try: + data = await request.json() + reason = data.get("reason", "") + + order = session.get(Order, order_id) + if not order: + return JSONResponse({"success": False, "message": "Order not found"}, status_code=404) + + # Guard: unauth only allowed from double_authorized + if order.status != "double_authorized": + return JSONResponse({"success": False, "message": f"Cannot unauthorize from status '{order.status}'. Only double-authorized tests can be unauthorized."}, status_code=400) + + result = session.exec(select(Result).where(Result.order_id == order_id)).first() + if not result: + return JSONResponse({"success": False, "message": "Result not found"}, status_code=404) + + result.double_authorized = False + result.double_authorized_by = None + result.double_authorized_at = None + result.unauth_reason = reason + + order.status = "authorized" # Return to auth and rerun buttons + + session.add(result) + session.add(order) + + # --------------------------------------------------------- + # ✅ NEW: INJECT AUDIT LOG HERE (Tracking Unauthorize) + # --------------------------------------------------------- + log_audit_action( + session=session, + table_name="order", + record_id=order.id, + action="UPDATE", + current_user=current_user, + new_values={ + "action": "Test Unauthorized", + "status": "authorized", + "reason": reason + } + ) + # --------------------------------------------------------- + + session.commit() + return {"success": True, "message": "Test Unauthorized with reason"} + except Exception as e: + session.rollback() + return JSONResponse({"success": False, "message": str(e)}, status_code=500) \ No newline at end of file diff --git a/routes/expenses.py b/routes/expenses.py new file mode 100644 index 0000000000000000000000000000000000000000..4cc5cfb7c3e71320c26ceb19a46f4fde35e9c970 --- /dev/null +++ b/routes/expenses.py @@ -0,0 +1,263 @@ +# routes/expenses.py +from fastapi import APIRouter, Depends, Request, Form, status, UploadFile, File +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlmodel import Session, select +from datetime import datetime +import os +import secrets +from typing import Optional +from database import get_session +from models import ExpenseType, Expense +from routes.helpers import templates, get_current_user, create_audit_log, model_to_dict, require_permission + +router = APIRouter() + +EXPENSES_UPLOAD_DIR = "uploads/expenses" +os.makedirs(EXPENSES_UPLOAD_DIR, exist_ok=True) + +# =========================== +# EXPENSE TYPES ROUTES +# =========================== +@router.get("/expenses-types", response_class=HTMLResponse) +def expenses_types_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "expenses_types"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + types = session.exec(select(ExpenseType).order_by(ExpenseType.id.asc())).all() + types_dict = [model_to_dict(t) for t in types] + success = request.query_params.get("success") + error = request.query_params.get("error") + + return templates.TemplateResponse("expenses_types.html", { + "request": request, + "expense_types": types, + "expense_types_json": types_dict, + "message_success": success, + "message_error": error + }) + +@router.post("/expenses-types/create") +def create_expense_type(type_name: str = Form(...), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "expenses_types", "create"): + return RedirectResponse(url="/expenses-types?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + new_type = ExpenseType(type_name=type_name, + created_by=current_user.id if current_user else None) + session.add(new_type) + session.commit() + session.refresh(new_type) + create_audit_log(session, "expensetype", new_type.id, "create", current_user, new_values=model_to_dict(new_type)) + return RedirectResponse(url="/expenses-types?success=Expense type saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/expenses-types?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/expenses-types/update/{type_id}") +def update_expense_type(type_id: int, type_name: str = Form(...), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "expenses_types", "edit"): + return RedirectResponse(url="/expenses-types?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + etype = session.get(ExpenseType, type_id) + if etype: + old_values = model_to_dict(etype) + etype.type_name = type_name + etype.edited_by = current_user.id if current_user else None + etype.edited_at = datetime.now() + session.add(etype) + session.commit() + session.refresh(etype) + create_audit_log(session, "expensetype", etype.id, "update", current_user, old_values=old_values, new_values=model_to_dict(etype)) + return RedirectResponse(url="/expenses-types?success=Expense type updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/expenses-types?error=Expense type not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/expenses-types?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/expenses-types/delete/{type_id}") +def delete_expense_type(type_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "expenses_types", "delete"): + return RedirectResponse(url="/expenses-types?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + etype = session.get(ExpenseType, type_id) + if etype: + old_values = model_to_dict(etype) + create_audit_log(session, "expensetype", etype.id, "delete", current_user, old_values=old_values) + session.delete(etype) + session.commit() + return RedirectResponse(url="/expenses-types?success=Expense type deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/expenses-types?error=Expense type not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/expenses-types?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# EXPENSES ENTRY ROUTES +# =========================== +@router.get("/expenses-entry", response_class=HTMLResponse) +def expenses_entry_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "expenses_entry"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + # Fetch all expenses joined with type + expenses = session.exec(select(Expense).order_by(Expense.expense_date.desc())).all() + # Fetch types for dropdown + types = session.exec(select(ExpenseType).order_by(ExpenseType.type_name.asc())).all() + + success = request.query_params.get("success") + error = request.query_params.get("error") + + return templates.TemplateResponse("expenses_entry.html", { + "request": request, + "expenses": expenses, + "expenses_json": [model_to_dict(e) for e in expenses], + "expense_types": types, + "message_success": success, + "message_error": error + }) + +@router.post("/expenses-entry/create") +async def create_expense( + type_id: int = Form(...), + expense_date: str = Form(...), + amount: float = Form(...), + note: Optional[str] = Form(None), + file: Optional[UploadFile] = File(None), + request: Request = None, + session: Session = Depends(get_session) +): + if not require_permission(request, session, "expenses_entry", "create"): + return RedirectResponse(url="/expenses-entry?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + + # Handle file upload + file_path = None + file_name = None + if file and file.filename: + ext = os.path.splitext(file.filename)[1].lower() + secure_filename = f"EXP_{secrets.token_hex(8)}{ext}" + file_path = os.path.join(EXPENSES_UPLOAD_DIR, secure_filename).replace("\\", "/") + file_name = file.filename + + with open(file_path, "wb") as buffer: + content = await file.read() + buffer.write(content) + + # Parse date + try: + exp_dt = datetime.strptime(expense_date, "%Y-%m-%d") + except ValueError: + exp_dt = datetime.now() + + new_expense = Expense( + type_id=type_id, + expense_date=exp_dt, + amount=amount, + note=note, + file_path=file_path, + file_name=file_name, + created_by=current_user.id if current_user else 0 + ) + session.add(new_expense) + session.commit() + session.refresh(new_expense) + + create_audit_log(session, "expense", new_expense.id, "create", current_user, new_values=model_to_dict(new_expense)) + return RedirectResponse(url="/expenses-entry?success=Expense saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/expenses-entry?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/expenses-entry/update/{expense_id}") +async def update_expense( + expense_id: int, + type_id: int = Form(...), + expense_date: str = Form(...), + amount: float = Form(...), + note: Optional[str] = Form(None), + file: Optional[UploadFile] = File(None), + request: Request = None, + session: Session = Depends(get_session) +): + if not require_permission(request, session, "expenses_entry", "edit"): + return RedirectResponse(url="/expenses-entry?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + expense = session.get(Expense, expense_id) + if not expense: + return RedirectResponse(url="/expenses-entry?error=Expense not found", status_code=status.HTTP_303_SEE_OTHER) + + old_values = model_to_dict(expense) + + # Handle file upload if provided + if file and file.filename: + # Delete old file + if expense.file_path and os.path.exists(expense.file_path): + try: + os.remove(expense.file_path) + except Exception: + pass + + ext = os.path.splitext(file.filename)[1].lower() + secure_filename = f"EXP_{secrets.token_hex(8)}{ext}" + file_path = os.path.join(EXPENSES_UPLOAD_DIR, secure_filename).replace("\\", "/") + expense.file_path = file_path + expense.file_name = file.filename + + with open(file_path, "wb") as buffer: + content = await file.read() + buffer.write(content) + + # Update other fields + try: + exp_dt = datetime.strptime(expense_date, "%Y-%m-%d") + expense.expense_date = exp_dt + except Exception: + pass + + expense.type_id = type_id + expense.amount = amount + expense.note = note + expense.edited_by = current_user.id if current_user else None + expense.edited_at = datetime.now() + + session.add(expense) + session.commit() + session.refresh(expense) + + create_audit_log(session, "expense", expense.id, "update", current_user, old_values=old_values, new_values=model_to_dict(expense)) + return RedirectResponse(url="/expenses-entry?success=Expense updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/expenses-entry?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/expenses-entry/delete/{expense_id}") +def delete_expense(expense_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "expenses_entry", "delete"): + return RedirectResponse(url="/expenses-entry?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + expense = session.get(Expense, expense_id) + if expense: + old_values = model_to_dict(expense) + + # Physically delete file if exists + if expense.file_path and os.path.exists(expense.file_path): + try: + os.remove(expense.file_path) + except Exception: + pass + + create_audit_log(session, "expense", expense.id, "delete", current_user, old_values=old_values) + session.delete(expense) + session.commit() + return RedirectResponse(url="/expenses-entry?success=Expense deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/expenses-entry?error=Expense not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/expenses-entry?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) diff --git a/routes/generate_pdf.py b/routes/generate_pdf.py new file mode 100644 index 0000000000000000000000000000000000000000..29c666b6c1dd47fc1bcbf257898cbb350b4c724f --- /dev/null +++ b/routes/generate_pdf.py @@ -0,0 +1,6 @@ +# routes/generate_pdf.py +# =================================================================== +# BACKWARD-COMPATIBLE BRIDGE — re-exports from app/services/pdf_service.py. +# =================================================================== + +from app.services.pdf_service import generate_native_barcode_pdf, parse_pt diff --git a/routes/geography.py b/routes/geography.py new file mode 100644 index 0000000000000000000000000000000000000000..bed6f8823c2e3c8fa2df54446a9bb7609b73e44f --- /dev/null +++ b/routes/geography.py @@ -0,0 +1,348 @@ +# routes/geography.py +# CRUD routes for: Partners, Provinces, Regions, Lab Info. + +from fastapi import APIRouter, Depends, Request, Form, UploadFile, File, status +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlmodel import Session, select +from datetime import datetime +from typing import Optional +import os +import uuid +from database import get_session +from models import Partner, Province, Region, LabInfo +from routes.helpers import templates, get_current_user, create_audit_log, model_to_dict, save_uploaded_file, require_permission + +router = APIRouter() + +# =========================== +# PARTNER ROUTES +# =========================== +@router.get("/partners", response_class=HTMLResponse) +def partners_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "partners"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + partners = session.exec(select(Partner).order_by(Partner.id.asc())).all() + partners_json = [model_to_dict(p) for p in partners] + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("partners.html", { + "request": request, "partners": partners, "partners_json": partners_json, + "message_success": success, "message_error": error + }) + +@router.post("/partners/create") +def create_partner(partner_name: str = Form(...), partner_note: Optional[str] = Form(None), + partner_contact: Optional[str] = Form(None), partner_weight: Optional[float] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "partners", "create"): + return RedirectResponse(url="/partners?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + new_partner = Partner( + partner_name=partner_name, partner_note=partner_note, + partner_contact=partner_contact, partner_weight=partner_weight if partner_weight else None, + is_active=True, created_by=current_user.id if current_user else None + ) + session.add(new_partner) + session.commit() + session.refresh(new_partner) + create_audit_log(session, "partner", new_partner.id, "create", current_user, new_values=model_to_dict(new_partner)) + return RedirectResponse(url="/partners?success=Partner saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/partners?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/partners/update/{partner_id}") +def update_partner(partner_id: int, partner_name: str = Form(...), partner_note: Optional[str] = Form(None), + partner_contact: Optional[str] = Form(None), partner_weight: Optional[float] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "partners", "edit"): + return RedirectResponse(url="/partners?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + partner = session.get(Partner, partner_id) + if partner: + old_values = model_to_dict(partner) + partner.partner_name = partner_name + partner.partner_note = partner_note + partner.partner_contact = partner_contact + partner.partner_weight = partner_weight if partner_weight else None + partner.edited_by = current_user.id if current_user else None + partner.edited_at = datetime.now() + session.add(partner) + session.commit() + session.refresh(partner) + create_audit_log(session, "partner", partner.id, "update", current_user, old_values=old_values, new_values=model_to_dict(partner)) + return RedirectResponse(url="/partners?success=Partner updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/partners?error=Partner not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/partners?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/partners/delete/{partner_id}") +def delete_partner(partner_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "partners", "delete"): + return RedirectResponse(url="/partners?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + partner = session.get(Partner, partner_id) + if partner: + old_values = model_to_dict(partner) + session.delete(partner) + session.commit() + create_audit_log(session, "partner", partner.id, "delete", current_user, old_values=old_values) + return RedirectResponse(url="/partners?success=Partner deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/partners?error=Partner not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/partners?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# PROVINCE ROUTES +# =========================== +@router.get("/provinces", response_class=HTMLResponse) +def provinces_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "provinces"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + provinces = session.exec(select(Province).order_by(Province.id.asc())).all() + provinces_json = [model_to_dict(p) for p in provinces] + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("provinces.html", { + "request": request, "provinces": provinces, "provinces_json": provinces_json, + "message_success": success, "message_error": error + }) + +@router.post("/provinces/create") +def create_province(province_name: str = Form(...), request: Request = None, + session: Session = Depends(get_session)): + if not require_permission(request, session, "provinces", "create"): + return RedirectResponse(url="/provinces?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + new_province = Province(province_name=province_name, is_active=True, + created_by=current_user.id if current_user else None) + session.add(new_province) + session.commit() + session.refresh(new_province) + create_audit_log(session, "province", new_province.id, "create", current_user, new_values=model_to_dict(new_province)) + return RedirectResponse(url="/provinces?success=Province saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/provinces?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/provinces/update/{province_id}") +def update_province(province_id: int, province_name: str = Form(...), request: Request = None, + session: Session = Depends(get_session)): + if not require_permission(request, session, "provinces", "edit"): + return RedirectResponse(url="/provinces?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + province = session.get(Province, province_id) + if province: + old_values = model_to_dict(province) + province.province_name = province_name + province.edited_by = current_user.id if current_user else None + province.edited_at = datetime.now() + session.add(province) + session.commit() + session.refresh(province) + create_audit_log(session, "province", province.id, "update", current_user, old_values=old_values, new_values=model_to_dict(province)) + return RedirectResponse(url="/provinces?success=Province updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/provinces?error=Province not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/provinces?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/provinces/delete/{province_id}") +def delete_province(province_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "provinces", "delete"): + return RedirectResponse(url="/provinces?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + province = session.get(Province, province_id) + if province: + old_values = model_to_dict(province) + session.delete(province) + session.commit() + create_audit_log(session, "province", province.id, "delete", current_user, old_values=old_values) + return RedirectResponse(url="/provinces?success=Province deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/provinces?error=Province not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/provinces?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# REGION ROUTES +# =========================== +@router.get("/regions", response_class=HTMLResponse) +def regions_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "regions"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + regions = session.exec(select(Region).order_by(Region.id.asc())).all() + regions_json = [model_to_dict(r) for r in regions] + provinces = session.exec(select(Province).where(Province.is_active == True)).all() + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("regions.html", { + "request": request, "regions": regions, "regions_json": regions_json, + "provinces": provinces, "message_success": success, "message_error": error + }) + +@router.post("/regions/create") +def create_region(region_name: str = Form(...), province_id: int = Form(...), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "regions", "create"): + return RedirectResponse(url="/regions?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + new_region = Region(region_name=region_name, province_id=province_id, is_active=True, + created_by=current_user.id if current_user else None) + session.add(new_region) + session.commit() + session.refresh(new_region) + create_audit_log(session, "region", new_region.id, "create", current_user, new_values=model_to_dict(new_region)) + return RedirectResponse(url="/regions?success=Region saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/regions?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/regions/update/{region_id}") +def update_region(region_id: int, region_name: str = Form(...), province_id: int = Form(...), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "regions", "edit"): + return RedirectResponse(url="/regions?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + region = session.get(Region, region_id) + if region: + old_values = model_to_dict(region) + region.region_name = region_name + region.province_id = province_id + region.edited_by = current_user.id if current_user else None + region.edited_at = datetime.now() + session.add(region) + session.commit() + session.refresh(region) + create_audit_log(session, "region", region.id, "update", current_user, old_values=old_values, new_values=model_to_dict(region)) + return RedirectResponse(url="/regions?success=Region updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/regions?error=Region not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/regions?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/regions/delete/{region_id}") +def delete_region(region_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "regions", "delete"): + return RedirectResponse(url="/regions?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + region = session.get(Region, region_id) + if region: + old_values = model_to_dict(region) + session.delete(region) + session.commit() + create_audit_log(session, "region", region.id, "delete", current_user, old_values=old_values) + return RedirectResponse(url="/regions?success=Region deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/regions?error=Region not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/regions?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# LAB INFO ROUTES +# =========================== +@router.get("/lab-info", response_class=HTMLResponse) +def lab_info_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "lab_info"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + lab_info = session.exec(select(LabInfo).limit(1)).first() + + province_name = None + if lab_info and lab_info.province_id: + province = session.get(Province, lab_info.province_id) + if province: + province_name = province.province_name + + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("lab_info.html", { + "request": request, "lab_info": lab_info, "edit_mode": False, + "province_name": province_name, + "message_success": success, "message_error": error + }) + +@router.get("/lab-info/edit", response_class=HTMLResponse) +def lab_info_edit_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "lab_info", "edit"): + return RedirectResponse(url="/lab-info?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + lab_info = session.exec(select(LabInfo).limit(1)).first() + provinces = session.exec(select(Province).where(Province.is_active == True)).all() + return templates.TemplateResponse("lab_info.html", { + "request": request, "lab_info": lab_info, "edit_mode": True, "provinces": provinces + }) + +@router.post("/lab-info/update") +async def update_lab_info(request: Request, lab_name: str = Form(...), lab_title: Optional[str] = Form(None), + welcome_message: Optional[str] = Form(None), welcome_template_name: Optional[str] = Form(None), + province_id: Optional[int] = Form(None), + first_doctor_name: Optional[str] = Form(None), second_doctor_name: Optional[str] = Form(None), + lab_address: Optional[str] = Form(None), lab_phone_1: str = Form(...), + lab_phone_2: Optional[str] = Form(None), whatsapp_api: Optional[str] = Form(None), + whatsapp_token: Optional[str] = Form(None), telegram_api: Optional[str] = Form(None), + telegram_token: Optional[str] = Form(None), lab_email: Optional[str] = Form(None), + lab_website: Optional[str] = Form(None), tax_percentage: Optional[float] = Form(0.0), + lab_note_1: Optional[str] = Form(None), + lab_note_2: Optional[str] = Form(None), lab_logo: Optional[UploadFile] = File(None), + lab_qr_1: Optional[UploadFile] = File(None), lab_qr_2: Optional[UploadFile] = File(None), + lab_stamp_1: Optional[UploadFile] = File(None), lab_stamp_2: Optional[UploadFile] = File(None), + lab_signature_1: Optional[UploadFile] = File(None), lab_signature_2: Optional[UploadFile] = File(None), + lab_image_1: Optional[UploadFile] = File(None), lab_image_2: Optional[UploadFile] = File(None), + session: Session = Depends(get_session)): + if not require_permission(request, session, "lab_info", "edit"): + return RedirectResponse(url="/lab-info?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + lab_info = session.exec(select(LabInfo).limit(1)).first() + if not lab_info: + lab_info = LabInfo() + session.add(lab_info) + lab_info.lab_name = lab_name + lab_info.lab_title = lab_title + lab_info.first_doctor_name = first_doctor_name + lab_info.second_doctor_name = second_doctor_name + lab_info.lab_address = lab_address + lab_info.lab_phone_1 = lab_phone_1 + lab_info.lab_phone_2 = lab_phone_2 + lab_info.whatsapp_api = whatsapp_api + lab_info.whatsapp_token = whatsapp_token + lab_info.telegram_api = telegram_api + lab_info.telegram_token = telegram_token + lab_info.lab_email = lab_email + lab_info.lab_website = lab_website + lab_info.welcome_message = welcome_message + lab_info.welcome_template_name = welcome_template_name + lab_info.province_id = province_id + lab_info.tax_percentage = tax_percentage if tax_percentage is not None else 0.0 + lab_info.lab_note_1 = lab_note_1 + lab_info.lab_note_2 = lab_note_2 + lab_info.edited_by = current_user.id if current_user else None + lab_info.edited_at = datetime.now() + files_to_upload = [ + ('lab_logo', lab_logo), ('lab_qr_1', lab_qr_1), ('lab_qr_2', lab_qr_2), + ('lab_stamp_1', lab_stamp_1), ('lab_stamp_2', lab_stamp_2), + ('lab_signature_1', lab_signature_1), ('lab_signature_2', lab_signature_2), + ('lab_image_1', lab_image_1), ('lab_image_2', lab_image_2), + ] + for field_name, file in files_to_upload: + if file and file.filename: + ext = os.path.splitext(file.filename)[1] + unique_filename = f"{field_name}_{uuid.uuid4().hex}{ext}" + saved_filename = save_uploaded_file(file, unique_filename) + setattr(lab_info, field_name, saved_filename) + session.commit() + session.refresh(lab_info) + return RedirectResponse(url="/lab-info?success=Lab information updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/lab-info?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) diff --git a/routes/helpers.py b/routes/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..76d22d82be65132798e8b5a3c1dfe3b16f58966e --- /dev/null +++ b/routes/helpers.py @@ -0,0 +1,112 @@ +# routes/helpers.py +# =================================================================== +# BACKWARD-COMPATIBLE BRIDGE — re-exports from new SoC locations. +# All route files import from here; this file delegates to app/services/. +# =================================================================== + +# Config +from app.config import SECRET_KEY, pwd_context + +# Auth +from app.services.auth_service import get_current_user, login_required + +# Permissions +from app.services.permission_service import require_permission + +# Audit +from app.services.audit_service import ( + log_audit_action, create_audit_log, + archive_deleted_record, log_activity_action +) + +# Patient utilities +from app.services.patient_service import ( + calculate_age, age_to_days, model_to_dict, + build_patient_visit_data +) + +# Barcode +from app.services.barcode_service import generate_barcode_base64 + +# Templates +from app.routes.template_helpers import templates + +# Upload directory +import os +UPLOAD_DIR = "uploads" +os.makedirs(UPLOAD_DIR, exist_ok=True) + +# File upload helper (used by several routes) +import shutil +import uuid + +def save_uploaded_file(file, filename: str) -> str: + """Save uploaded file and return the filename.""" + file_path = os.path.join(UPLOAD_DIR, filename) + with open(file_path, "wb") as f: + shutil.copyfileobj(file.file, f) + return filename + +# Timezone helper +from datetime import datetime +def local_now() -> datetime: + """Return current local datetime.""" + return datetime.now() + + +# =========================== +# SHARED PATIENT LIST QUERY BUILDER (used by history.py) +# =========================== +from sqlmodel import select +from app.models import Patient, PatientVisit, Order, TestDefinition + +def build_patient_list_query(request, defaults_today=True): + """Build a filtered patient query from common request query params.""" + today_str = datetime.today().strftime("%Y-%m-%d") if defaults_today else "" + + start_date = request.query_params.get("start_date", today_str) + end_date = request.query_params.get("end_date", today_str) + name = request.query_params.get("name", "") + patient_id_q = request.query_params.get("patient_id", "") + test_q = request.query_params.get("test", "") + + query = select(Patient).where(Patient.is_active == True) + + needs_visit_join = bool(start_date or end_date or test_q) + if needs_visit_join: + query = query.join(PatientVisit) + + if start_date: + query = query.where(PatientVisit.visit_date >= datetime.strptime(f"{start_date} 00:00:00", "%Y-%m-%d %H:%M:%S")) + if end_date: + query = query.where(PatientVisit.visit_date <= datetime.strptime(f"{end_date} 23:59:59", "%Y-%m-%d %H:%M:%S")) + + if name: + query = query.where(Patient.full_name.ilike(f"%{name}%")) + if patient_id_q: + query = query.where(Patient.patient_id.ilike(f"%{patient_id_q}%")) + + if test_q: + if not needs_visit_join: + query = query.join(PatientVisit) + query = query.join(Order, Order.visit_id == PatientVisit.id).join(TestDefinition, Order.test_id == TestDefinition.id) + query = query.where( + (TestDefinition.test_name.ilike(f"%{test_q}%")) | + (TestDefinition.test_short_name.ilike(f"%{test_q}%")) + ) + + query = query.distinct().order_by(Patient.created_at.desc()) + + filters = { + "start_date": start_date, + "end_date": end_date, + "name": name, + "patient_id": patient_id_q, + "test": test_q, + } + + return query, filters + + +# Register calculate_age as a Jinja template global +templates.env.globals["calculate_age"] = calculate_age \ No newline at end of file diff --git a/routes/history.py b/routes/history.py new file mode 100644 index 0000000000000000000000000000000000000000..7a2c49a2d75efe39fd599650dc991e1afdfd61dd --- /dev/null +++ b/routes/history.py @@ -0,0 +1,194 @@ +from fastapi import APIRouter, Depends, Request +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlmodel import Session, select +from sqlalchemy import or_, and_ +from sqlalchemy.orm import selectinload +from datetime import datetime +import json + +from database import get_session +from models import Patient, PatientVisit, Order, TestDefinition, AuditLog, ActivityLog # ✅ Added ActivityLog +from routes.helpers import templates, require_permission, build_patient_list_query + +router = APIRouter() + +# =========================== +# 1. PATIENT HISTORY SEARCH PAGE +# =========================== +@router.get("/patient-history", response_class=HTMLResponse) +def patient_history_search(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "patient_history"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=303) + + query, filters = build_patient_list_query(request) + patients = session.exec(query).all() + + return templates.TemplateResponse("patient_history_list.html", { + "request": request, + "patients": patients, + "filters": filters + }) + +# =========================== +# 2. PATIENT HISTORY DETAIL PAGE +# =========================== +@router.get("/patient-history/{patient_id}", response_class=HTMLResponse) +def patient_history_detail(patient_id: str, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "patient_history"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=303) + # 1. Get the Core Patient + patient = session.exec( + select(Patient) + .options(selectinload(Patient.visits), selectinload(Patient.orders)) + .where(Patient.patient_id == patient_id) + ).first() + + if not patient: + return templates.TemplateResponse("error.html", {"request": request, "message": "Patient not found"}) + + # 2. Gather all related IDs to build the Polymorphic Query + visit_ids = [v.id for v in patient.visits] if patient.visits else [] + order_ids = [o.id for o in patient.orders] if patient.orders else [] + + # We must also find the result IDs linked to these orders + result_ids = [] + if order_ids: + from models import Result + results = session.exec(select(Result.id).where(Result.order_id.in_(order_ids))).all() + result_ids = [r for r in results] + + # 3. Build the OR condition for the AuditLog + conditions = [ + and_(AuditLog.table_name == 'patient', AuditLog.record_id == patient.id) + ] + if visit_ids: + conditions.append(and_(AuditLog.table_name == 'patientvisit', AuditLog.record_id.in_(visit_ids))) + if order_ids: + conditions.append(and_(AuditLog.table_name == 'order', AuditLog.record_id.in_(order_ids))) + if result_ids: + conditions.append(and_(AuditLog.table_name == 'result', AuditLog.record_id.in_(result_ids))) + + logs_query = select(AuditLog).where(or_(*conditions)).order_by(AuditLog.created_at.desc()) + audit_logs = session.exec(logs_query).all() + + # 4. Smart Formatting for the UI + formatted_logs = [] + for log in audit_logs: + # Normalize text to avoid case-sensitivity bugs + safe_action = str(log.action).upper() if log.action else "" + safe_table = str(log.table_name).lower() if log.table_name else "" + + # Default Fallbacks + action_type = f"{safe_action} - {safe_table.upper()}" + action_detail = f"System action on {safe_table} record." + + # Parse the JSON payload we injected during saves + if log.new_values: + try: + new_vals = json.loads(log.new_values) + explicit_action = new_vals.get("action") + test_name = new_vals.get("test_name") + + # --- TRANSLATE ACTION TYPE --- + if safe_action == "PRINT": + action_type = "Document Printed" + elif safe_action == "DISPATCH": + action_type = "Communication" + elif safe_action == "CREATE" and safe_table == "patient": + action_type = "Registration" + elif safe_action == "UPDATE" and safe_table == "patient": + if explicit_action and "Added" in explicit_action: + action_type = "Test Added" + else: + action_type = "Profile Update" + elif safe_action == "DELETE" and safe_table == "patient": + if explicit_action and "Removed" in explicit_action: + action_type = "Test Removed" + else: + action_type = "Patient Deleted" + elif safe_table == "order": + if explicit_action: + if "Removed" in explicit_action: + action_type = "Test Removed" + elif "Double" in explicit_action: + action_type = "Double Auth" + elif "Authorized" in explicit_action: + action_type = "Authorization" + elif "No Sample" in explicit_action: + action_type = "Sample Issue" + elif "ReRun" in explicit_action: + action_type = "ReRun Request" + else: + action_type = "Result Update" + else: + action_type = "Test Update" + elif safe_table == "patientvisit": + action_type = "Visit Update" + + # --- TRANSLATE ACTION DETAIL --- + if explicit_action: + action_detail = explicit_action + + if test_name: + action_detail += f": {test_name}" + if "reason" in new_vals and new_vals["reason"]: + action_detail += f" (Reason: {new_vals['reason']})" + if "phone" in new_vals: + action_detail += f" to {new_vals['phone']}" + if "total_tests_ordered" in new_vals: + action_detail += f" with {new_vals['total_tests_ordered']} tests" + else: + if "status" in new_vals: + friendly_status = str(new_vals['status']).replace('_', ' ').title() + action_detail = f"Status changed to: {friendly_status}" + + except Exception: + pass # Silently fallback to raw data if JSON parsing fails + + formatted_logs.append({ + "date": log.created_at, + "action_type": action_type, + "username": log.username or "System", + "detail": action_detail + }) + + return templates.TemplateResponse("patient_history_detail.html", { + "request": request, + "patient": patient, + "logs": formatted_logs + }) + +# =========================== +# 3. GLOBAL ACTIVITY LOGS PAGE +# =========================== +@router.get("/activity-logs", response_class=HTMLResponse) +def global_activity_logs(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "activity_logs", "view"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=303) + + # Filters + filter_user = request.query_params.get("user", "") + filter_action = request.query_params.get("action", "") + + query = select(ActivityLog) + + if filter_user: + query = query.where(ActivityLog.username == filter_user) + if filter_action: + query = query.where(ActivityLog.action_type == filter_action) + + query = query.order_by(ActivityLog.created_at.desc()).limit(500) + activities = session.exec(query).all() + + # Get distinct usernames and action types for the filter dropdowns + all_users = session.exec(select(ActivityLog.username).distinct()).all() + all_actions = session.exec(select(ActivityLog.action_type).distinct()).all() + + return templates.TemplateResponse("activity_logs.html", { + "request": request, + "activities": activities, + "all_users": sorted([u for u in all_users if u]), + "all_actions": sorted([a for a in all_actions if a]), + "filter_user": filter_user, + "filter_action": filter_action + }) \ No newline at end of file diff --git a/routes/hr.py b/routes/hr.py new file mode 100644 index 0000000000000000000000000000000000000000..c90f075bdc9f2402e1d1d10b1e71dc4361518924 --- /dev/null +++ b/routes/hr.py @@ -0,0 +1,268 @@ +# routes/hr.py +# HR Module: Employee Management + +from fastapi import APIRouter, Depends, Request, Form, UploadFile, File, status +from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse +from sqlmodel import Session, select +from datetime import datetime +from typing import Optional +import os +import shutil +import uuid + +from database import get_session +from app.models.hr import Employee, EmployeeAttachment +from routes.helpers import templates, get_current_user + +router = APIRouter() + +EMPLOYEES_UPLOAD_DIR = "uploads/employees" +os.makedirs(EMPLOYEES_UPLOAD_DIR, exist_ok=True) + +EMPLOYEE_ATTACHMENTS_DIR = "uploads/employee_attachments" +os.makedirs(EMPLOYEE_ATTACHMENTS_DIR, exist_ok=True) + +# =========================== +# HR PAGE +# =========================== +@router.get("/hr", response_class=HTMLResponse) +def hr_page(request: Request, session: Session = Depends(get_session)): + current_user = get_current_user(request, session) + if not current_user: + return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) + + employees = session.exec(select(Employee).where(Employee.is_active == True).order_by(Employee.created_at.desc())).all() + + import json + employees_json = {} + for emp in employees: + emp_dict = emp.dict() if hasattr(emp, 'dict') else emp.model_dump() + emp_dict['start_date'] = emp.start_date.isoformat() if emp.start_date else None + emp_dict['created_at'] = emp.created_at.isoformat() if emp.created_at else None + emp_dict['working_life_months'] = emp.working_life_months + employees_json[emp.id] = emp_dict + + success = request.query_params.get("success") + error = request.query_params.get("error") + + return templates.TemplateResponse("hr.html", { + "request": request, + "employees": employees, + "employees_json": employees_json, + "current_user": current_user, + "message_success": success, + "message_error": error + }) + + +# =========================== +# CREATE EMPLOYEE +# =========================== +@router.post("/api/hr/employees") +def create_employee( + full_name: str = Form(...), + age: Optional[int] = Form(None), + phone: Optional[str] = Form(None), + address: Optional[str] = Form(None), + start_date: str = Form(...), + working_days: Optional[str] = Form(None), + working_hours_start: Optional[str] = Form(None), + working_hours_end: Optional[str] = Form(None), + salary: Optional[float] = Form(None), + username: Optional[str] = Form(None), + photo: Optional[UploadFile] = File(None), + request: Request = None, + session: Session = Depends(get_session) +): + current_user = get_current_user(request, session) + if not current_user: + return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) + + try: + sd = datetime.strptime(start_date, "%Y-%m-%d") + + photo_path = None + if photo and photo.filename: + ext = photo.filename.split(".")[-1] + unique_filename = f"{uuid.uuid4().hex}.{ext}" + file_path = os.path.join(EMPLOYEES_UPLOAD_DIR, unique_filename) + with open(file_path, "wb") as buffer: + shutil.copyfileobj(photo.file, buffer) + photo_path = f"/{EMPLOYEES_UPLOAD_DIR}/{unique_filename}" + + emp = Employee( + full_name=full_name, + age=age, + phone=phone, + address=address, + start_date=sd, + working_days=working_days, + working_hours_start=working_hours_start, + working_hours_end=working_hours_end, + salary=salary, + username=username, + photo_path=photo_path + ) + session.add(emp) + session.commit() + return RedirectResponse(url="/hr?success=Employee created successfully", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/hr?error={str(e)}", status_code=status.HTTP_303_SEE_OTHER) + + +# =========================== +# UPDATE EMPLOYEE +# =========================== +@router.post("/api/hr/employees/{employee_id}/update") +def update_employee( + employee_id: int, + full_name: str = Form(...), + age: Optional[int] = Form(None), + phone: Optional[str] = Form(None), + address: Optional[str] = Form(None), + start_date: str = Form(...), + working_days: Optional[str] = Form(None), + working_hours_start: Optional[str] = Form(None), + working_hours_end: Optional[str] = Form(None), + salary: Optional[float] = Form(None), + username: Optional[str] = Form(None), + photo: Optional[UploadFile] = File(None), + request: Request = None, + session: Session = Depends(get_session) +): + current_user = get_current_user(request, session) + if not current_user: + return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) + + try: + emp = session.get(Employee, employee_id) + if not emp: + return RedirectResponse(url="/hr?error=Employee not found", status_code=status.HTTP_303_SEE_OTHER) + + emp.full_name = full_name + emp.age = age + emp.phone = phone + emp.address = address + emp.start_date = datetime.strptime(start_date, "%Y-%m-%d") + emp.working_days = working_days + emp.working_hours_start = working_hours_start + emp.working_hours_end = working_hours_end + emp.salary = salary + emp.username = username + + if photo and photo.filename: + ext = photo.filename.split(".")[-1] + unique_filename = f"{uuid.uuid4().hex}.{ext}" + file_path = os.path.join(EMPLOYEES_UPLOAD_DIR, unique_filename) + with open(file_path, "wb") as buffer: + shutil.copyfileobj(photo.file, buffer) + emp.photo_path = f"/{EMPLOYEES_UPLOAD_DIR}/{unique_filename}" + + session.add(emp) + session.commit() + return RedirectResponse(url="/hr?success=Employee updated successfully", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/hr?error={str(e)}", status_code=status.HTTP_303_SEE_OTHER) + + +# =========================== +# DELETE EMPLOYEE +# =========================== +@router.post("/api/hr/employees/{employee_id}/delete") +def delete_employee( + employee_id: int, + request: Request, + session: Session = Depends(get_session) +): + current_user = get_current_user(request, session) + if not current_user: + return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) + + try: + emp = session.get(Employee, employee_id) + if not emp: + return RedirectResponse(url="/hr?error=Employee not found", status_code=status.HTTP_303_SEE_OTHER) + + emp.is_active = False + session.add(emp) + session.commit() + return RedirectResponse(url="/hr?success=Employee deleted successfully", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/hr?error={str(e)}", status_code=status.HTTP_303_SEE_OTHER) + + +# =========================== +# GET ATTACHMENTS API +# =========================== +@router.get("/api/hr/employees/{employee_id}/attachments") +def get_employee_attachments(employee_id: int, session: Session = Depends(get_session)): + attachments = session.exec(select(EmployeeAttachment).where(EmployeeAttachment.employee_id == employee_id)).all() + return {"attachments": [{"id": a.id, "file_name": a.file_name, "file_path": a.file_path, "uploaded_at": a.uploaded_at.isoformat()} for a in attachments]} + + +# =========================== +# UPLOAD ATTACHMENT API +# =========================== +@router.post("/api/hr/employees/{employee_id}/attachments") +def upload_employee_attachment( + employee_id: int, + file: UploadFile = File(...), + request: Request = None, + session: Session = Depends(get_session) +): + current_user = get_current_user(request, session) + if not current_user: + return JSONResponse(status_code=401, content={"success": False, "error": "Not authenticated"}) + + try: + emp = session.get(Employee, employee_id) + if not emp: + return JSONResponse(status_code=404, content={"success": False, "error": "Employee not found"}) + + ext = file.filename.split(".")[-1] if "." in file.filename else "" + unique_filename = f"{uuid.uuid4().hex}.{ext}" + file_path = os.path.join(EMPLOYEE_ATTACHMENTS_DIR, unique_filename) + + with open(file_path, "wb") as buffer: + shutil.copyfileobj(file.file, buffer) + + attachment = EmployeeAttachment( + employee_id=employee_id, + file_name=file.filename, + file_path=f"/{EMPLOYEE_ATTACHMENTS_DIR}/{unique_filename}" + ) + session.add(attachment) + session.commit() + + return JSONResponse({"success": True}) + except Exception as e: + session.rollback() + return JSONResponse(status_code=500, content={"success": False, "error": str(e)}) + +# =========================== +# DELETE ATTACHMENT API +# =========================== +@router.delete("/api/hr/employees/attachments/{attachment_id}") +def delete_employee_attachment( + attachment_id: int, + request: Request, + session: Session = Depends(get_session) +): + current_user = get_current_user(request, session) + if not current_user: + return JSONResponse(status_code=401, content={"success": False, "error": "Not authenticated"}) + + try: + attachment = session.get(EmployeeAttachment, attachment_id) + if not attachment: + return JSONResponse(status_code=404, content={"success": False, "error": "Attachment not found"}) + + session.delete(attachment) + session.commit() + return JSONResponse({"success": True}) + except Exception as e: + session.rollback() + return JSONResponse(status_code=500, content={"success": False, "error": str(e)}) diff --git a/routes/inventory.py b/routes/inventory.py new file mode 100644 index 0000000000000000000000000000000000000000..5470390755aa6646b57364b30d8ffd59231d182c --- /dev/null +++ b/routes/inventory.py @@ -0,0 +1,193 @@ +# routes/inventory.py +from fastapi import APIRouter, Depends, Request, Form, status +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlmodel import Session, select +from datetime import datetime, timedelta +from typing import Optional +from database import get_session +from models import Inventory, TestDefinition, Supply +from sqlalchemy.orm import selectinload +from routes.helpers import templates, get_current_user, create_audit_log, model_to_dict, require_permission + +router = APIRouter() + +@router.get("/inventory", response_class=HTMLResponse) +def inventory_list(request: Request, search: Optional[str] = None, expires_soon: Optional[bool] = False, session: Session = Depends(get_session)): + if not require_permission(request, session, "inventory"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + query = select(Inventory).options( + selectinload(Inventory.test), + selectinload(Inventory.supply) + ).where(Inventory.is_active == True) + + # Base query for display + items = session.exec(query.order_by(Inventory.expiration_date.asc())).all() + + # Filter in python or db + today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) + thirty_days_later = today + timedelta(days=30) + + filtered_items = [] + + for item in items: + # Determine name dynamically based on material_type + if item.material_type == "Test": + name = item.test.test_name if item.test else "Unknown Test" + else: + name = item.supply.name if item.supply else "Unknown Supply" + + # Apply Search Filter + if search and search.lower() not in name.lower(): + continue + + # Apply Expiration Filter + if expires_soon: + if item.expiration_date > thirty_days_later: + continue + + # Determine if it expires soon for row highlighting + is_expiring_soon = item.expiration_date <= thirty_days_later + + filtered_items.append({ + "id": item.id, + "material_type": item.material_type, + "name": name, + "quantity": item.quantity, + "unit": item.unit, + "expiration_date": item.expiration_date, + "note": item.note, + "is_expiring_soon": is_expiring_soon, + "test_id": item.test_id, + "supply_id": item.supply_id + }) + + # Get total sum of quantity at the bottom + total_quantity = sum(float(item["quantity"]) for item in filtered_items) + + # Create JSON safe items + json_safe_items = [] + for fi in filtered_items: + new_fi = fi.copy() + new_fi["expiration_date"] = new_fi["expiration_date"].isoformat() + json_safe_items.append(new_fi) + + # Get tests and supplies for the form dropdowns + tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all() + supplies = session.exec(select(Supply).where(Supply.is_active == True)).all() + + tests_dict = [{"id": t.id, "name": t.test_name} for t in tests] + supplies_dict = [{"id": s.id, "name": s.name} for s in supplies] + + return templates.TemplateResponse("inventory.html", { + "request": request, + "inventory_items": filtered_items, + "inventory_json": json_safe_items, # To be used in javascript for editing + "tests": tests, + "supplies": supplies, + "tests_json": tests_dict, + "supplies_json": supplies_dict, + "search": search or "", + "expires_soon": expires_soon, + "total_quantity": total_quantity, + "message_success": request.query_params.get("success"), + "message_error": request.query_params.get("error") + }) + +@router.post("/inventory/create") +def create_inventory( + material_type: str = Form(...), + test_id: Optional[int] = Form(None), + supply_id: Optional[int] = Form(None), + quantity: float = Form(...), + unit: str = Form("Test"), + expiration_date: str = Form(...), # DD-MM-YYYY + note: Optional[str] = Form(None), + request: Request = None, + session: Session = Depends(get_session) +): + if not require_permission(request, session, "inventory", "create"): + return RedirectResponse(url="/inventory?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + try: + current_user = get_current_user(request, session) + exp_date_obj = datetime.strptime(expiration_date, "%Y-%m-%d") + + new_item = Inventory( + material_type=material_type, + test_id=test_id if material_type == "Test" else None, + supply_id=supply_id if material_type == "Supply" else None, + quantity=quantity, + unit=unit if material_type == "Supply" else "Test", + expiration_date=exp_date_obj, + note=note, + created_by=current_user.id if current_user else None + ) + session.add(new_item) + session.commit() + session.refresh(new_item) + + create_audit_log(session, "inventory", new_item.id, "create", current_user, new_values=model_to_dict(new_item)) + return RedirectResponse(url="/inventory?success=Inventory item added successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/inventory?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/inventory/update/{item_id}") +def update_inventory( + item_id: int, + material_type: str = Form(...), + test_id: Optional[int] = Form(None), + supply_id: Optional[int] = Form(None), + quantity: float = Form(...), + unit: str = Form("Test"), + expiration_date: str = Form(...), + note: Optional[str] = Form(None), + request: Request = None, + session: Session = Depends(get_session) +): + if not require_permission(request, session, "inventory", "edit"): + return RedirectResponse(url="/inventory?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + try: + current_user = get_current_user(request, session) + item = session.get(Inventory, item_id) + if item: + old_values = model_to_dict(item) + + item.material_type = material_type + item.test_id = test_id if material_type == "Test" else None + item.supply_id = supply_id if material_type == "Supply" else None + item.quantity = quantity + item.unit = unit if material_type == "Supply" else "Test" + item.expiration_date = datetime.strptime(expiration_date, "%Y-%m-%d") + item.note = note + item.edited_by = current_user.id if current_user else None + item.edited_at = datetime.now() + + session.add(item) + session.commit() + create_audit_log(session, "inventory", item.id, "update", current_user, old_values=old_values, new_values=model_to_dict(item)) + return RedirectResponse(url="/inventory?success=Inventory item updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/inventory?error=Item not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/inventory?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/inventory/delete/{item_id}") +def delete_inventory(item_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "inventory", "delete"): + return RedirectResponse(url="/inventory?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + item = session.get(Inventory, item_id) + if item: + old_values = model_to_dict(item) + session.delete(item) + session.commit() + create_audit_log(session, "inventory", item.id, "delete", current_user, old_values=old_values) + return RedirectResponse(url="/inventory?success=Inventory item deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/inventory?error=Item not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/inventory?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) diff --git a/routes/messages.py b/routes/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..976096e7dd690def06215bc55fd0d888f96ca12d --- /dev/null +++ b/routes/messages.py @@ -0,0 +1,232 @@ +from fastapi import APIRouter, Request, Depends, HTTPException, UploadFile, File, Form +from fastapi.responses import HTMLResponse, JSONResponse +from fastapi.templating import Jinja2Templates +from sqlmodel import Session, select, or_, and_ +from typing import Optional, List +import os +import uuid +import datetime +from pathlib import Path + +from database import get_session +from models import User, Chat, ChatMember, Message, MessageReceipt +from routes.helpers import templates + +router = APIRouter(prefix="/messages", tags=["Messages"]) + +# Dependency to get current user ID +def get_current_user_id(request: Request): + user_id = getattr(request.state, "user_id", None) + if not user_id: + raise HTTPException(status_code=401, detail="Not authenticated") + return user_id + +@router.get("/", response_class=HTMLResponse) +async def messages_page(request: Request, session: Session = Depends(get_session)): + user_id = get_current_user_id(request) + current_user = session.get(User, user_id) + if not current_user: + raise HTTPException(status_code=401) + + return templates.TemplateResponse("messages.html", {"request": request, "current_user": current_user}) + +@router.get("/api/users") +async def get_all_users(request: Request, session: Session = Depends(get_session)): + user_id = get_current_user_id(request) + users = session.exec(select(User).where(User.is_active == True)).all() + # Exclude admin if it's not relevant, or just return all except self + # Return id, full_name, username, is_online, last_seen + users_data = [] + for u in users: + users_data.append({ + "id": u.id, + "full_name": u.full_name, + "username": u.username, + "is_online": u.is_online, + "last_seen": u.last_seen.isoformat() if u.last_seen else None + }) + return {"users": users_data} + +@router.get("/api/chats") +async def get_user_chats(request: Request, session: Session = Depends(get_session)): + user_id = get_current_user_id(request) + + # Get all chats the user is a member of + memberships = session.exec(select(ChatMember).where(ChatMember.user_id == user_id)).all() + chat_ids = [m.chat_id for m in memberships] + + if not chat_ids: + return {"chats": []} + + chats = session.exec(select(Chat).where(Chat.id.in_(chat_ids))).all() + + chats_data = [] + for chat in chats: + # Get members of this chat + members = session.exec(select(ChatMember).where(ChatMember.chat_id == chat.id)).all() + # Get last message + last_msg = session.exec(select(Message).where(Message.chat_id == chat.id).order_by(Message.created_at.desc())).first() + + # Determine chat title and avatar if it's 1-on-1 + chat_name = chat.name + other_user = None + if not chat.is_group: + for m in members: + if m.user_id != user_id: + u = session.get(User, m.user_id) + if u: + chat_name = u.full_name + other_user = u + break + + last_msg_data = None + unread_count = 0 + if last_msg: + # Count unread messages strictly for this user + # Unread could be calculated by checking MessageReceipt for this user where status != 'read' + unread_count = len(session.exec(select(MessageReceipt).where( + MessageReceipt.chat_id == chat.id, + MessageReceipt.user_id == user_id, + MessageReceipt.status != "read" + )).all()) + + last_msg_data = { + "id": last_msg.id, + "text": last_msg.text, + "created_at": last_msg.created_at.isoformat(), + "sender_id": last_msg.sender_id, + "is_attachment": bool(last_msg.attachment_path), + "is_voice": bool(last_msg.voice_note_path) + } + + chats_data.append({ + "id": chat.id, + "is_group": chat.is_group, + "name": chat_name, + "other_user_id": other_user.id if other_user else None, + "other_user_online": other_user.is_online if other_user else False, + "other_user_last_seen": other_user.last_seen.isoformat() if other_user and other_user.last_seen else None, + "last_message": last_msg_data, + "unread_count": unread_count, + "members": [m.user_id for m in members] + }) + + # Sort by recent message + chats_data.sort(key=lambda x: x["last_message"]["created_at"] if x["last_message"] else "", reverse=True) + return {"chats": chats_data} + +@router.get("/api/chats/{chat_id}/history") +async def get_chat_history(chat_id: int, request: Request, session: Session = Depends(get_session)): + user_id = get_current_user_id(request) + + # Verify membership + membership = session.exec(select(ChatMember).where(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id)).first() + if not membership: + raise HTTPException(status_code=403, detail="Not a member of this chat") + + messages = session.exec(select(Message).where(Message.chat_id == chat_id).order_by(Message.created_at.asc())).all() + + # Mark all unread messages as read + unreads = session.exec(select(MessageReceipt).where( + MessageReceipt.chat_id == chat_id, + MessageReceipt.user_id == user_id, + MessageReceipt.status != "read" + )).all() + for unread in unreads: + unread.status = "read" + unread.updated_at = datetime.datetime.now() + session.add(unread) + session.commit() + + msg_data = [] + for msg in messages: + # Get receipt status for message sender (if valid) + # Usually sender wants to know if others read it + receipts = session.exec(select(MessageReceipt).where(MessageReceipt.message_id == msg.id)).all() + status = "sent" + if receipts: + # If all are read, it's read. If some delivered, delivered. + if all(r.status == "read" for r in receipts): + status = "read" + elif any(r.status == "delivered" for r in receipts): + status = "delivered" + + msg_data.append({ + "id": msg.id, + "sender_id": msg.sender_id, + "text": msg.text, + "attachment_path": msg.attachment_path, + "attachment_name": msg.attachment_name, + "attachment_type": msg.attachment_type, + "voice_note_path": msg.voice_note_path, + "voice_note_duration": msg.voice_note_duration, + "is_call": msg.is_call, + "call_status": msg.call_status, + "call_duration": msg.call_duration, + "created_at": msg.created_at.isoformat(), + "status": status + }) + + return {"messages": msg_data} + +@router.post("/api/chats/create") +async def create_chat(data: dict, request: Request, session: Session = Depends(get_session)): + user_id = get_current_user_id(request) + is_group = data.get("is_group", False) + members_ids = data.get("members", []) + name = data.get("name") + + if user_id not in members_ids: + members_ids.append(user_id) + + if not is_group and len(members_ids) == 2: + # Check if 1-on-1 chat already exists + target_id = [m for m in members_ids if m != user_id][0] + # Find all 1-on-1 chats for this user + my_chats = session.exec(select(ChatMember).where(ChatMember.user_id == user_id)).all() + my_chat_ids = [m.chat_id for m in my_chats] + + # Check if target is in any of these, and chat is not a group + shared_chats = session.exec(select(Chat).where(Chat.id.in_(my_chat_ids), Chat.is_group == False)).all() + for sc in shared_chats: + target_membership = session.exec(select(ChatMember).where(ChatMember.chat_id == sc.id, ChatMember.user_id == target_id)).first() + if target_membership: + return {"chat_id": sc.id} # return existing + + # Create new chat + new_chat = Chat(is_group=is_group, name=name, created_by=user_id) + session.add(new_chat) + session.commit() + session.refresh(new_chat) + + for m_id in members_ids: + member = ChatMember(chat_id=new_chat.id, user_id=m_id, is_admin=(m_id == user_id)) + session.add(member) + session.commit() + + return {"chat_id": new_chat.id} + +@router.post("/api/upload") +async def upload_attachment(request: Request, file: UploadFile, type: str = Form(...), session: Session = Depends(get_session)): + user_id = get_current_user_id(request) + + upload_dir = Path("uploads/chat_media") + upload_dir.mkdir(parents=True, exist_ok=True) + + # Generate unique filename + ext = os.path.splitext(file.filename)[1] + filename = f"{uuid.uuid4()}{ext}" + if type == "voice" and not ext: + filename += ".webm" # default for browser MediaRecorder + + filepath = upload_dir / filename + + content = await file.read() + with open(filepath, "wb") as f: + f.write(content) + + return { + "path": f"/uploads/chat_media/{filename}", + "name": file.filename, + "type": type # 'image', 'document', 'voice' + } diff --git a/routes/patient_status.py b/routes/patient_status.py new file mode 100644 index 0000000000000000000000000000000000000000..55049105ba7b1dc6e28d7344d4185c5718c34df1 --- /dev/null +++ b/routes/patient_status.py @@ -0,0 +1,137 @@ +from fastapi import APIRouter, Depends, Request +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlmodel import Session, select +from sqlalchemy.orm import selectinload +from datetime import datetime + +from database import get_session +from models import Patient, PatientVisit, Order, TestDefinition, Package +from routes.helpers import templates, require_permission + +router = APIRouter() + +@router.get("/patient-status", response_class=HTMLResponse) +def patient_status_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "patient_status"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=303) + + today_str = datetime.today().strftime("%Y-%m-%d") + from_date = request.query_params.get("from_date", today_str) + to_date = request.query_params.get("to_date", today_str) + name = request.query_params.get("name", "") + patient_id_q = request.query_params.get("patient_id", "") + status_q = request.query_params.get("status", "all") + + # Visit-centric query (each visit shown separately) + visit_query = ( + select(PatientVisit) + .options( + selectinload(PatientVisit.patient), + selectinload(PatientVisit.orders).selectinload(Order.test) + ) + .join(Patient, PatientVisit.patient_id == Patient.id) + .where(Patient.is_active == True) + ) + + if from_date: + visit_query = visit_query.where(PatientVisit.visit_date >= datetime.strptime(f"{from_date} 00:00:00", "%Y-%m-%d %H:%M:%S")) + if to_date: + visit_query = visit_query.where(PatientVisit.visit_date <= datetime.strptime(f"{to_date} 23:59:59", "%Y-%m-%d %H:%M:%S")) + if name: + visit_query = visit_query.where(Patient.full_name.ilike(f"%{name}%")) + if patient_id_q: + visit_query = visit_query.where(Patient.patient_id.ilike(f"%{patient_id_q}%")) + + if status_q != "all": + visit_query = visit_query.join(Order, Order.visit_id == PatientVisit.id) + if status_q == "pending": + visit_query = visit_query.where(Order.status == "ordered") + elif status_q == "resulted": + visit_query = visit_query.where(Order.status == "resulted") + elif status_q == "auth": + visit_query = visit_query.where(Order.status == "authorized") + elif status_q == "double_auth": + visit_query = visit_query.where(Order.status == "double_authorized") + + visits = session.exec(visit_query.distinct().order_by(PatientVisit.visit_date.desc())).all() + + patient_data = [] + for visit in visits: + patient = visit.patient + if not patient: + continue + + tests_data = [] + packages = {} + standalones = [] + + for order in visit.orders: + if not order.test or order.status == "no_sample": + continue + + if status_q == "pending" and order.status != "ordered": continue + if status_q == "resulted" and order.status != "resulted": continue + if status_q == "auth" and order.status != "authorized": continue + if status_q == "double_auth" and order.status != "double_authorized": continue + + # Formulate the human readable status + readable_status = "Pending" + badge_color = "bg-red-500 text-white" + if order.status == "resulted": + readable_status = "Resulted" + badge_color = "bg-blue-500 text-white" + elif order.status == "authorized": + readable_status = "Authorize" + badge_color = "bg-emerald-500 text-white" + elif order.status == "double_authorized": + readable_status = "Double Authorized" + badge_color = "bg-purple-500 text-white" + + test_obj = { + "name": order.test.test_name, + "status": readable_status, + "color": badge_color + } + + if order.package_name: + if order.package_name not in packages: + packages[order.package_name] = [] + packages[order.package_name].append(test_obj) + else: + standalones.append(test_obj) + + if not packages and not standalones: + continue + + for pkg_name, pkg_tests in packages.items(): + sub_test_names = ",".join([t["name"] for t in pkg_tests]) + tests_data.append({ + "is_package": True, + "group_header": f"{pkg_name.upper()},{sub_test_names}", + "tests": pkg_tests + }) + + for t in standalones: + tests_data.append({ + "is_package": False, + "test": t + }) + + patient_data.append({ + "patient": patient, + "visit": visit, + "registration_date": visit.visit_date, + "tests": tests_data + }) + + return templates.TemplateResponse("patient_status.html", { + "request": request, + "patient_data": patient_data, + "filters": { + "from_date": from_date, + "to_date": to_date, + "name": name, + "patient_id": patient_id_q, + "status": status_q + } + }) diff --git a/routes/patients.py b/routes/patients.py new file mode 100644 index 0000000000000000000000000000000000000000..4aba2c3d615b09c24d948e8cf7e8746753a773f2 --- /dev/null +++ b/routes/patients.py @@ -0,0 +1,1427 @@ +# routes/patients.py +# Patient registration, management, editing, soft-delete/restore, and deleted patients view. + +from fastapi import APIRouter, Depends, Request, Form, status +from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse +from sqlmodel import Session, select +from sqlalchemy import func +from sqlalchemy.orm import selectinload +from datetime import datetime +from typing import Optional +import json +from pydantic import BaseModel +from database import get_session +from models import ( + Patient, PatientVisit, Order, TestDefinition, Package, PackageTest, + Province, Region, Partner, SampleType, LabInfo, Payment, Attachment, User, DeletedRecord, Result, ResultDetail +) +from routes.helpers import templates, get_current_user, create_audit_log, model_to_dict, generate_barcode_base64, require_permission, archive_deleted_record, log_activity_action + +router = APIRouter() + +# =========================== +# PATIENT REGISTRATION PAGE +# =========================== +@router.get("/patient-registration", response_class=HTMLResponse) +def patient_registration_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "patient_registration"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + provinces = session.exec(select(Province).where(Province.is_active == True)).all() + partners = session.exec(select(Partner).where(Partner.is_active == True)).all() + tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all() + packages = session.exec(select(Package).where(Package.is_active == True)).all() + success = request.query_params.get("success") + error = request.query_params.get("error") + last_patient_id = request.query_params.get("patient_id") + import hashlib + from routes.helpers import SECRET_KEY + print_token = hashlib.sha256(SECRET_KEY.encode()).hexdigest()[:16] + + from models import PrintTemplate + barcode_template = session.exec(select(PrintTemplate).where(PrintTemplate.template_name == "barcode")).first() + receipt_template = session.exec(select(PrintTemplate).where(PrintTemplate.template_name == "receipt")).first() + + lab_info = session.exec(select(LabInfo)).first() + default_province_id = lab_info.province_id if lab_info else None + + return templates.TemplateResponse("patient_registration.html", { + "request": request, "provinces": provinces, "partners": partners, + "tests": tests, "packages": packages, + "message_success": success, "message_error": error, + "last_patient_id": last_patient_id, + "print_token": print_token, + "default_province_id": default_province_id, + "barcode_width": barcode_template.paper_width if barcode_template else '4in', + "barcode_height": barcode_template.paper_height if barcode_template else '2in', + "receipt_width": receipt_template.paper_width if receipt_template else '80mm', + "receipt_height": receipt_template.paper_height if receipt_template else 'auto' + }) + +class CheckDuplicateRequest(BaseModel): + full_name: str + selected_items: str + +@router.post("/api/check-duplicate-registration") +def check_duplicate_registration(request_data: CheckDuplicateRequest, session: Session = Depends(get_session)): + today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) + + # 1. Parse requested tests + try: + items = json.loads(request_data.selected_items) + except Exception: + items = [] + + requested_test_ids = set() + for item in items: + if item.get('type') == 'test': + requested_test_ids.add(int(item['id'])) + elif item.get('type') == 'package': + pts = session.exec(select(PackageTest).where(PackageTest.package_id == int(item['id']))).all() + for pt in pts: + requested_test_ids.add(pt.test_id) + + if not requested_test_ids: + return JSONResponse({"duplicate": False}) + + # 2. Find visits today for patients with same name + visits_today = session.exec( + select(PatientVisit) + .join(Patient) + .where( + Patient.full_name.ilike(request_data.full_name), + PatientVisit.created_at >= today_start + ) + ).all() + + for visit in visits_today: + orders = session.exec(select(Order).where(Order.visit_id == visit.id)).all() + visit_test_ids = {o.test_id for o in orders} + if requested_test_ids.issubset(visit_test_ids) and len(requested_test_ids) > 0: + # We have a duplicate + return JSONResponse({ + "duplicate": True, + "message": "This patient has already been registered today with all of the selected tests." + }) + + return JSONResponse({"duplicate": False}) + +# =========================== +# PATIENT REGISTRATION CREATE (WITH PRICE SNAPSHOT) +# =========================== +@router.post("/patient-registration/create") +async def create_patient_registration( + request: Request, + patient_id: str = Form(...), + full_name: str = Form(...), + gender: str = Form(...), + date_of_birth: Optional[str] = Form(None), + age: Optional[int] = Form(None), + age_unit: Optional[str] = Form(None), + phone_key: str = Form(...), + phone_number: str = Form(...), + weight: float = Form(...), + height: float = Form(...), + province_id: int = Form(...), + region_id: int = Form(...), + fasting_time: Optional[int] = Form(None), + note: Optional[str] = Form(None), + email: Optional[str] = Form(None), + diagnosis: Optional[str] = Form(None), + symptoms: Optional[str] = Form(None), + therapy: Optional[str] = Form(None), + partner_id: Optional[int] = Form(None), + doctor: Optional[str] = Form(None), + skin_colour: Optional[str] = Form(None), + agent_name: Optional[str] = Form(None), + is_outlab: str = Form("false"), + selected_items: str = Form(...), + discount_percentage: Optional[float] = Form(None), + discount_amount: Optional[float] = Form(None), + discount_note: Optional[str] = Form(None), + received_amount: Optional[float] = Form(None), + apply_tax_toggle: Optional[str] = Form(None), + force_duplicate: Optional[str] = Form("false"), + existing_patient_db_id: Optional[int] = Form(None), + session: Session = Depends(get_session) +): + if not require_permission(request, session, "patient_registration", "save_registration"): + return RedirectResponse(url="/patient-registration?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + items = json.loads(selected_items) + + total_price = sum(float(item.get('price', 0)) for item in items) + + # --- Check Discount Permissions --- + has_discount_perm = require_permission(request, session, "patient_registration", "discount") + + if not has_discount_perm: + discount_percentage = None + discount_amount = None + # ---------------------------------- + + final_total = total_price + discount_amt = float(discount_amount) if discount_amount else 0.0 + if discount_percentage: + final_total = total_price * (1 - discount_percentage / 100) + discount_amt = total_price - final_total + elif discount_amount: + final_total = total_price - float(discount_amount) + + # --- NEW TAX LOGIC --- + is_tax_applied = apply_tax_toggle == "on" + tax_amount = 0.0 + if is_tax_applied: + from models import LabInfo + lab_info = session.exec(select(LabInfo)).first() + tax_percentage = lab_info.tax_percentage if lab_info else 0.0 + tax_amount = (tax_percentage / 100) * final_total + final_total += tax_amount + # --------------------- + + received = float(received_amount) if received_amount else 0.0 + remaining = max(0, final_total - received) + + # --- Returning patient vs new patient --- + is_returning = False + if existing_patient_db_id: + existing = session.get(Patient, existing_patient_db_id) + if existing and existing.is_active: + new_patient = existing + patient_id = existing.patient_id # Reuse the same Patient ID + new_patient.fasting_time = fasting_time # Update for the new visit + is_returning = True + else: + existing_patient_db_id = None # Fallback to new patient + + if not existing_patient_db_id: + new_patient = Patient( + patient_id=patient_id, + full_name=full_name, + gender=gender, + date_of_birth=datetime.strptime(date_of_birth, "%Y-%m-%d") if date_of_birth else None, + age=age, + age_unit=age_unit, + phone_key=phone_key, + phone_number=phone_number, + weight=weight, + height=height, + province_id=province_id, + region_id=region_id, + fasting_time=fasting_time, + note=note, + email=email, + diagnosis=diagnosis, + symptoms=symptoms, + therapy=therapy, + partner_id=partner_id if partner_id else None, + doctor=doctor, + skin_colour=skin_colour, + agent_name=agent_name, + is_outlab=is_outlab.lower() == "true", + created_by=current_user.id if current_user else None + ) + session.add(new_patient) + session.flush() # Get new_patient.id without committing + + # Generate visit_id using timestamp to avoid race conditions with concurrent registrations + import time + ts_suffix = str(int(time.time() * 1000))[-6:] # Last 6 digits of ms timestamp + visit_id = f"{patient_id}{ts_suffix}" + + disc_pct = float(discount_percentage) if discount_percentage else 0.0 + new_visit = PatientVisit( + visit_id=visit_id, + patient_id=new_patient.id, + created_by=current_user.id if current_user else None, + received_amount=received, + discount_amount=round(discount_amt, 2), + discount_percentage=disc_pct, + discount_note=discount_note, + tax_applied=is_tax_applied, + tax_amount=round(tax_amount, 2), + remaining_amount=remaining + ) + session.add(new_visit) + session.flush() # Get new_visit.id without committing + + # [NEW] Add initial payment record if amount > 0 + if received > 0: + payment = Payment( + visit_id=new_visit.id, + patient_id=new_patient.id, + amount=received, + payment_method="cash", + recorded_by=current_user.id if current_user else 0 + ) + session.add(payment) + + discount_ratio = discount_amt / total_price if total_price > 0 else 0 + + created_orders = {} + + for item in items: + if item['type'] == 'test': + test_id = int(item['id']) + test = session.get(TestDefinition, test_id) + unit_price = test.price if test else 0.0 + order_discount = unit_price * discount_ratio + final_price = unit_price - order_discount + + if test_id in created_orders: + existing_order = created_orders[test_id] + existing_order.unit_price += unit_price + existing_order.discount_amount += order_discount + existing_order.final_price += final_price + else: + order = Order( + order_number=f"ORD-{visit_id}-{test_id}", + patient_id=new_patient.id, + test_id=test_id, + visit_id=new_visit.id, + ordered_by=current_user.id if current_user else None, + unit_price=unit_price, + discount_amount=order_discount, + final_price=final_price + ) + created_orders[test_id] = order + session.add(order) + + elif item['type'] == 'package': + package_id = int(item['id']) + package = session.get(Package, package_id) + package_name = package.package_name if package else '' + package_price = package.price if package else 0.0 + package_tests = session.exec( + select(PackageTest).where(PackageTest.package_id == package_id) + ).all() + num_tests = len(package_tests) + price_per_test = package_price / num_tests if num_tests > 0 else 0.0 + for pt in package_tests: + test_id = pt.test_id + unit_price = price_per_test + order_discount = unit_price * discount_ratio + final_price = unit_price - order_discount + + if test_id in created_orders: + existing_order = created_orders[test_id] + existing_order.unit_price += unit_price + existing_order.discount_amount += order_discount + existing_order.final_price += final_price + if existing_order.package_name: + if package_name and package_name not in existing_order.package_name: + existing_order.package_name += f", {package_name}" + else: + existing_order.package_name = package_name + else: + order = Order( + order_number=f"ORD-{visit_id}-{test_id}", + patient_id=new_patient.id, + test_id=test_id, + visit_id=new_visit.id, + ordered_by=current_user.id if current_user else None, + unit_price=unit_price, + discount_amount=order_discount, + final_price=final_price, + package_name=package_name + ) + created_orders[test_id] = order + session.add(order) + + # Audit & Activity Logs (all part of the same transaction) + audit_action = "New Visit (Returning Patient)" if is_returning else "Patient Registered" + create_audit_log( + session, + "patient", + new_patient.id, + "create" if not is_returning else "update", + current_user, + new_values={"action": audit_action, "total_tests_ordered": len(items), "visit_id": visit_id} + ) + + if force_duplicate.lower() == "true": + create_audit_log( + session, + "patient", + new_patient.id, + "update", + current_user, + old_values={}, + new_values={"action": "Duplicate Registration Confirmed", "note": "User explicitly confirmed bypassing duplicate check."} + ) + + activity_msg = f"New visit for returning patient {new_patient.full_name} (ID: {new_patient.patient_id})" if is_returning else f"Registered patient {new_patient.full_name} (ID: {new_patient.patient_id})" + log_activity_action(session, "REGISTER_PATIENT", activity_msg, current_user, "patient", new_patient.id) + + # Single atomic commit — all or nothing + session.commit() + + # --- Send Welcome WhatsApp Message (background thread — non-blocking) --- + try: + lab_info = session.exec(select(LabInfo)).first() + if lab_info and lab_info.welcome_message and phone_number: + from fastapi.encoders import jsonable_encoder + import threading + + to_phone = phone_number.strip().replace(" ", "") + country_code = getattr(lab_info, 'phone_country_code', '964') or '964' + if not to_phone.startswith('+'): + to_phone = "+" + (to_phone if to_phone.startswith(country_code) else country_code + to_phone.lstrip('0')) + + lab_info_data = jsonable_encoder(lab_info) + welcome_msg = lab_info.welcome_message + + def _send_welcome(): + try: + from routes.whatsapp_utils import send_wati_text + send_wati_text(to_phone, welcome_msg, lab_info_data) + except Exception as e: + import logging + logging.getLogger("nexlab.whatsapp").warning(f"Welcome message failed: {e}") + + threading.Thread(target=_send_welcome, daemon=True).start() + except Exception as wa_err: + import logging + logging.getLogger("nexlab.whatsapp").warning(f"Welcome message setup failed: {wa_err}") + # ------------------------------------------------------- + + return RedirectResponse( + url=f"/patient-registration?success=Patient registered successfully!&patient_id={new_patient.patient_id}", + status_code=status.HTTP_303_SEE_OTHER + ) + except Exception as e: + session.rollback() + print(f"❌ Error creating patient: {str(e)}") + import traceback + traceback.print_exc() + return RedirectResponse( + url=f"/patient-registration?error={str(e).replace(' ', '%20')}", + status_code=status.HTTP_303_SEE_OTHER + ) + +# =========================== +# PATIENT MANAGEMENT ROUTES +# =========================== +PAGE_SIZE = 50 # Patients per page + +@router.get("/patients", response_class=HTMLResponse) +def patients_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "patients"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + search = request.query_params.get("search", "") + today_str = datetime.now().strftime('%Y-%m-%d') + from_date = request.query_params.get("from_date", today_str) + to_date = request.query_params.get("to_date", today_str) + test_filter = request.query_params.get("test_filter", "") + + # Pagination + try: + page = max(1, int(request.query_params.get("page", 1))) + except (ValueError, TypeError): + page = 1 + + query = select(PatientVisit).join(Patient).where(Patient.is_active == True) + count_query = select(func.count(PatientVisit.id)).join(Patient).where(Patient.is_active == True) + + if search: + search_filter = ( + (Patient.full_name.ilike(f"%{search}%")) | + (Patient.patient_id.ilike(f"%{search}%")) | + (Patient.phone_number.ilike(f"%{search}%")) + ) + query = query.where(search_filter) + count_query = count_query.where(search_filter) + + if from_date: + try: + fd = datetime.strptime(from_date, "%Y-%m-%d").replace(hour=0, minute=0, second=0) + query = query.where(PatientVisit.visit_date >= fd) + count_query = count_query.where(PatientVisit.visit_date >= fd) + except Exception: + pass + + if to_date: + try: + td = datetime.strptime(to_date, "%Y-%m-%d").replace(hour=23, minute=59, second=59) + query = query.where(PatientVisit.visit_date <= td) + count_query = count_query.where(PatientVisit.visit_date <= td) + except Exception: + pass + + if test_filter: + try: + query = query.join(Order, PatientVisit.id == Order.visit_id).where(Order.test_id == int(test_filter)).distinct() + count_query = count_query.join(Order, PatientVisit.id == Order.visit_id).where(Order.test_id == int(test_filter)) + except Exception: + pass + + # Get total count for pagination + total_count = session.exec(count_query).one() + total_pages = max(1, (total_count + PAGE_SIZE - 1) // PAGE_SIZE) + page = min(page, total_pages) + offset = (page - 1) * PAGE_SIZE + + # Use selectinload to eagerly load the related Patient so it's accessible in the template + query = query.options(selectinload(PatientVisit.patient)) + patient_visits = session.exec(query.order_by(PatientVisit.visit_date.desc()).offset(offset).limit(PAGE_SIZE)).all() + tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all() + + success = request.query_params.get("success") + error = request.query_params.get("error") + + return templates.TemplateResponse("patients.html", { + "request": request, + "patient_visits": patient_visits, + "tests": tests, + "search": search, + "from_date": from_date, + "to_date": to_date, + "test_filter": test_filter, + "message_success": success, + "message_error": error, + "page": page, + "total_pages": total_pages, + "total_count": total_count, + }) +@router.get("/api/patients/{patient_id}/has-resulted-tests") +def check_has_resulted_tests(patient_id: str, session: Session = Depends(get_session)): + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + return JSONResponse({"success": False, "error": "Patient not found"}) + + orders = session.exec(select(Order).where(Order.patient_id == patient.id)).all() + has_results = any(o.status in ['resulted', 'received', 'authorized', 'double_authorized'] for o in orders) + + return JSONResponse({"success": True, "has_results": has_results}) + +@router.get("/patients/edit/{patient_id}", response_class=HTMLResponse) +def patient_edit_page(request: Request, patient_id: str, session: Session = Depends(get_session)): + if not require_permission(request, session, "patient_edit"): + return RedirectResponse(url="/patients?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + + if not patient: + return RedirectResponse(url="/patients?error=Patient not found", status_code=status.HTTP_303_SEE_OTHER) + + provinces = session.exec(select(Province).where(Province.is_active == True)).all() + regions = session.exec(select(Region).where(Region.province_id == patient.province_id)).all() if patient.province_id else [] + partners = session.exec(select(Partner).where(Partner.is_active == True)).all() + tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all() + packages = session.exec(select(Package).where(Package.is_active == True)).all() + + visit_id_param = request.query_params.get("visit_id") + visits = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.visit_date.desc()) + ).all() + latest_visit = None + if visit_id_param: + for v in visits: + if v.visit_id == visit_id_param: + latest_visit = v + break + if not latest_visit and visits: + latest_visit = visits[0] + + # ✅ N+1 FIX: eager-load test relationship for orders + orders_json = [] + if latest_visit: + orders = session.exec( + select(Order) + .options(selectinload(Order.test)) + .where(Order.visit_id == latest_visit.id) + ).all() + for order in orders: + test = order.test + orders_json.append({ + "id": order.test_id, + "name": test.test_name if test else 'Unknown Test', + "type": 'test', + "price": float(order.unit_price) if order.unit_price else (float(test.price) if test else 0.0), + "package_name": order.package_name, + "status": order.status + }) + + orders_json_str = json.dumps(orders_json if orders_json else []) + + # [NEW] Fetch payments for the latest visit + payments = [] + if latest_visit: + payments = session.exec( + select(Payment) + .where(Payment.visit_id == latest_visit.id) + .order_by(Payment.payment_date.desc()) + ).all() + + # Fetch attachments for the patient + attachments = session.exec( + select(Attachment) + .where(Attachment.patient_id == patient.id) + .order_by(Attachment.uploaded_at.desc()) + ).all() + + success = request.query_params.get("success") + error = request.query_params.get("error") + + return templates.TemplateResponse("patient_edit.html", { + "request": request, + "patient": patient, + "provinces": provinces, + "regions": regions, + "partners": partners, + "tests": tests, + "packages": packages, + "visits": visits, + "latest_visit": latest_visit, + "payments": payments, + "attachments": attachments, + "orders_json": orders_json_str, + "message_success": success, + "message_error": error + }) + except Exception as e: + print(f"❌ ERROR in patient_edit_page: {str(e)}") + import traceback + traceback.print_exc() + return HTMLResponse(content=f"{str(e)}
", status_code=500) + +# =========================== +# IMMEDIATE TEST REMOVAL API (AJAX) +# =========================== +@router.post("/api/patients/{patient_id}/remove-test") +def api_remove_test(patient_id: str, request: Request, session: Session = Depends(get_session)): + """Immediately delete a specific test order from the patient's latest visit.""" + if not require_permission(request, session, "patient_edit", "save"): + return JSONResponse({"success": False, "error": "Permission Denied"}, status_code=403) + try: + current_user = get_current_user(request, session) + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + return JSONResponse({"success": False, "error": "Patient not found"}, status_code=404) + + visit_id_param = request.query_params.get("visit_id") + + # Get target visit + if visit_id_param: + latest_visit = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id, PatientVisit.visit_id == visit_id_param) + ).first() + else: + latest_visit = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.visit_date.desc()) + ).first() + + if not latest_visit: + return JSONResponse({"success": False, "error": "No visit found"}, status_code=404) + + # Parse query params since this is called from JS + test_id = int(request.query_params.get("test_id", 0)) + reason = request.query_params.get("reason", "Removed from patient edit") + + if not test_id: + return JSONResponse({"success": False, "error": "test_id is required"}, status_code=400) + + # Find matching order(s) + orders_to_delete = session.exec( + select(Order) + .options(selectinload(Order.result).selectinload(Result.details)) + .where(Order.visit_id == latest_visit.id, Order.test_id == test_id) + ).all() + + if not orders_to_delete: + return JSONResponse({"success": False, "error": "Order not found"}, status_code=404) + + deleted_test_names = [] + for order in orders_to_delete: + # Resolve test name for logging + test_def = session.get(TestDefinition, order.test_id) + test_name = test_def.test_name if test_def else f"Test #{order.test_id}" + deleted_test_names.append(test_name) + + # Archive before deletion + archive_deleted_record(session, "order", order.id, model_to_dict(order), current_user, reason) + + # ✅ Audit Log — log against PATIENT so it appears in Patient History + # (logging against the order would orphan the entry since the order gets deleted) + create_audit_log( + session, + "patient", + patient.id, + "delete", + current_user, + old_values=model_to_dict(order), + new_values={"action": "Test Removed", "test_name": test_name, "reason": reason} + ) + + # Delete result and details if they exist + if order.result: + for det in order.result.details: + session.delete(det) + session.delete(order.result) + session.delete(order) + + # Recalculate visit financial totals from remaining orders + remaining_orders = session.exec( + select(Order).where(Order.visit_id == latest_visit.id) + ).all() + new_total_price = sum((o.unit_price or 0.0) for o in remaining_orders) + + # Recalculate discount proportionally + disc_pct = latest_visit.discount_percentage or 0.0 + new_discount = round(new_total_price * disc_pct / 100, 2) if disc_pct > 0 else 0.0 + + # Recalculate tax + new_tax = round((new_total_price - new_discount) * 0.0, 2) # Preserve existing tax logic + if latest_visit.tax_applied and latest_visit.tax_amount: + # Keep tax ratio consistent + old_total = sum((o.unit_price or 0.0) for o in remaining_orders) + sum((o.unit_price or 0.0) for _ in []) + new_tax = latest_visit.tax_amount # Tax amount set by user, preserved + + final_total = new_total_price - new_discount + (latest_visit.tax_amount or 0.0) + latest_visit.discount_amount = new_discount + latest_visit.remaining_amount = max(0, final_total - (latest_visit.received_amount or 0.0)) + session.add(latest_visit) + + # Log activity (same transaction) + log_activity_action(session, "REMOVE_TEST", f"Removed {', '.join(deleted_test_names)} from patient {patient.full_name} (ID: {patient_id}). Reason: {reason}", current_user, "order", test_id) + + session.commit() + + print(f"✅ API: Removed test_id={test_id} from patient {patient_id}, reason: {reason}") + return JSONResponse({"success": True, "message": "Test removed successfully"}) + + except Exception as e: + session.rollback() + print(f"❌ API Error removing test: {str(e)}") + import traceback + traceback.print_exc() + return JSONResponse({"success": False, "error": str(e)}, status_code=500) + +# =========================== +# PATIENT UPDATE +# =========================== +@router.post("/patients/update/{patient_id}") +def update_patient( + patient_id: str, + request: Request, + full_name: str = Form(...), + gender: str = Form(...), + date_of_birth: Optional[str] = Form(None), + age: Optional[int] = Form(None), + age_unit: Optional[str] = Form(None), + phone_key: str = Form(...), + phone_number: str = Form(...), + weight: float = Form(...), + height: float = Form(...), + province_id: int = Form(...), + region_id: int = Form(...), + fasting_time: Optional[int] = Form(None), + note: Optional[str] = Form(None), + email: Optional[str] = Form(None), + diagnosis: Optional[str] = Form(None), + symptoms: Optional[str] = Form(None), + therapy: Optional[str] = Form(None), + partner_id: Optional[int] = Form(None), + doctor: Optional[str] = Form(None), + skin_colour: Optional[str] = Form(None), + agent_name: Optional[str] = Form(None), + is_outlab: str = Form("false"), + selected_items: str = Form("[]"), + deleted_items: str = Form("[]"), + discount_percentage: Optional[float] = Form(None), + discount_amount: Optional[float] = Form(None), + discount_note: Optional[str] = Form(None), + received_amount: Optional[float] = Form(None), + apply_tax_toggle: Optional[str] = Form(None), + session: Session = Depends(get_session) +): + if not require_permission(request, session, "patient_edit", "save"): + return RedirectResponse(url="/patients?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + + if not patient: + return RedirectResponse(url="/patients?error=Patient not found", status_code=status.HTTP_303_SEE_OTHER) + + old_values = model_to_dict(patient) + + # Update patient fields + patient.full_name = full_name + patient.gender = gender + patient.date_of_birth = datetime.strptime(date_of_birth, "%Y-%m-%d") if date_of_birth else None + patient.age = age + patient.age_unit = age_unit + patient.phone_key = phone_key + patient.phone_number = phone_number + patient.weight = weight + patient.height = height + patient.province_id = province_id + patient.region_id = region_id + patient.fasting_time = fasting_time + patient.note = note + patient.email = email + patient.diagnosis = diagnosis + patient.symptoms = symptoms + patient.therapy = therapy + patient.partner_id = partner_id if partner_id else None + patient.doctor = doctor + patient.skin_colour = skin_colour + patient.agent_name = agent_name + patient.is_outlab = is_outlab.lower() == "true" + patient.edited_by = current_user.id if current_user else None + patient.edited_at = datetime.now() + + session.add(patient) + session.commit() + + # Update orders: remove old orders for latest visit, recreate from selected_items + items = json.loads(selected_items) if selected_items else [] + import logging + logger = logging.getLogger("nexlab.patients") + logger.debug(f"Update patient {patient_id} | selected_items: {selected_items} | deleted_items: {deleted_items}") + + visit_id_param = request.query_params.get("visit_id") + + # Get or create the latest visit + visits = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.visit_date.desc()) + ).all() + + latest_visit = None + if visit_id_param: + for v in visits: + if v.visit_id == visit_id_param: + latest_visit = v + break + if not latest_visit and visits: + latest_visit = visits[0] + + if not latest_visit: + visit_count = 0 + visit_id = patient_id + str(visit_count).zfill(3) + latest_visit = PatientVisit( + visit_id=visit_id, + patient_id=patient.id, + created_by=current_user.id if current_user else None + ) + session.add(latest_visit) + session.commit() + session.refresh(latest_visit) + + # Safely handle deleted orders and preserve unmodified ones + deleted_tests_json = json.loads(deleted_items) if deleted_items else [] + final_test_ids = [] + for item in items: + if item.get('type') == 'test': + final_test_ids.append(int(item['id'])) + elif item.get('type') == 'package': + pts = session.exec(select(PackageTest).where(PackageTest.package_id == int(item['id']))).all() + final_test_ids.extend([pt.test_id for pt in pts]) + + print(f"🔍 PATIENT UPDATE DEBUG [{patient_id}]:") + print(f" selected_items count: {len(items)}") + print(f" deleted_items count: {len(deleted_tests_json)}") + print(f" final_test_ids (should remain): {final_test_ids}") + print(f" deleted_tests_json: {deleted_tests_json}") + + old_orders = session.exec( + select(Order) + .options(selectinload(Order.result).selectinload(Result.details)) + .where(Order.visit_id == latest_visit.id) + ).all() + active_old_order_test_ids = [] + + print(f" old_orders test_ids: {[o.test_id for o in old_orders]}") + + for old_order in old_orders: + if old_order.test_id not in final_test_ids: + reason = "Deleted test from patient visit" + for dt in deleted_tests_json: + if dt.get('type') == 'test' and int(dt['id']) == old_order.test_id: + reason = dt.get('reason', reason) + + print(f" ❌ DELETING order id={old_order.id}, test_id={old_order.test_id}, reason={reason}") + + # Resolve test name for logging + test_def = session.get(TestDefinition, old_order.test_id) + test_name = test_def.test_name if test_def else f"Test #{old_order.test_id}" + + archive_deleted_record(session, "order", old_order.id, model_to_dict(old_order), current_user, reason) + + # ✅ Audit Log — log against PATIENT so it appears in Patient History + create_audit_log( + session, + "patient", + patient.id, + "delete", + current_user, + old_values=model_to_dict(old_order), + new_values={"action": "Test Removed", "test_name": test_name, "reason": reason} + ) + if old_order.result: + for det in old_order.result.details: + session.delete(det) + session.delete(old_order.result) + session.delete(old_order) + else: + print(f" ✅ KEEPING order id={old_order.id}, test_id={old_order.test_id}") + active_old_order_test_ids.append(old_order.test_id) + session.commit() + print(f" ✅ Deletion commit successful") + + # Calculate totals + total_price = sum(float(item.get('price', 0)) for item in items) + + # --- Check Discount Permissions --- + has_discount_perm = require_permission(request, session, "patient_edit", "discount") + + if not has_discount_perm: + discount_percentage = None + discount_amount = None + # ---------------------------------- + + discount_amt = float(discount_amount) if discount_amount else 0.0 + final_total = total_price + + if discount_percentage: + final_total = total_price * (1 - discount_percentage / 100) + discount_amt = total_price - final_total + elif discount_amount: + final_total = total_price - float(discount_amount) + + # --- NEW TAX LOGIC --- + is_tax_applied = apply_tax_toggle == "on" + tax_amount = 0.0 + if is_tax_applied: + lab_info = session.exec(select(LabInfo)).first() + tax_percentage = lab_info.tax_percentage if lab_info else 0.0 + tax_amount = (tax_percentage / 100) * final_total + final_total += tax_amount + # --------------------- + + received = float(received_amount) if received_amount else 0.0 + remaining = max(0, final_total - received) + + # [NEW] Record payment difference as a new Payment record + print(f"DEBUG Update Patient: {patient_id}") + print(f"DEBUG selected_items received: {selected_items}") + print(f"DEBUG deleted_items received: {deleted_items}") + payment_diff = received - (latest_visit.received_amount if latest_visit.received_amount else 0.0) + if payment_diff != 0: + payment_record = Payment( + visit_id=latest_visit.id, + patient_id=patient.id, + amount=abs(payment_diff), + payment_method="cash", + recorded_by=current_user.id if current_user else 0, + is_refund=(payment_diff < 0), + note="Updated via EDIT form" + ) + session.add(payment_record) + + # Update visit payment info + disc_pct = float(discount_percentage) if discount_percentage else 0.0 + latest_visit.received_amount = received + latest_visit.discount_amount = round(discount_amt, 2) + latest_visit.discount_percentage = disc_pct + latest_visit.discount_note = discount_note + latest_visit.tax_applied = is_tax_applied + latest_visit.tax_amount = round(tax_amount, 2) + latest_visit.remaining_amount = remaining + latest_visit.edited_by = current_user.id if current_user else None + latest_visit.edited_at = datetime.now() + session.add(latest_visit) + + # Recreate orders with price snapshots + discount_ratio = discount_amt / total_price if total_price > 0 else 0 + + # map old active orders + active_orders_map = {o.test_id: o for o in old_orders if o.test_id in active_old_order_test_ids} + + # Reset their prices to 0 so we can recalculate them from the current items list + for o in active_orders_map.values(): + o.unit_price = 0.0 + o.discount_amount = 0.0 + o.final_price = 0.0 + + created_orders = {} + + for item in items: + if item.get('type') == 'test': + test_id = int(item['id']) + test = session.get(TestDefinition, test_id) + unit_price = test.price if test else 0.0 + order_discount = unit_price * discount_ratio + final_price = unit_price - order_discount + + if test_id in active_orders_map: + order = active_orders_map[test_id] + order.unit_price += unit_price + order.discount_amount += order_discount + order.final_price += final_price + elif test_id in created_orders: + order = created_orders[test_id] + order.unit_price += unit_price + order.discount_amount += order_discount + order.final_price += final_price + else: + order = Order( + order_number=f"ORD-{latest_visit.visit_id}-{test_id}", + patient_id=patient.id, + test_id=test_id, + visit_id=latest_visit.id, + ordered_by=current_user.id if current_user else None, + unit_price=unit_price, + discount_amount=order_discount, + final_price=final_price + ) + created_orders[test_id] = order + session.add(order) + + # Log newly added test + test_name = test.test_name if test else f"Test #{test_id}" + create_audit_log( + session, + "patient", + patient.id, + "update", + current_user, + old_values={}, + new_values={"action": "Test Added", "test_name": test_name} + ) + + elif item.get('type') == 'package': + package_id = int(item['id']) + package = session.get(Package, package_id) + package_name = package.package_name if package else '' + package_price = package.price if package else 0.0 + package_tests = session.exec( + select(PackageTest).where(PackageTest.package_id == package_id) + ).all() + num_tests = len(package_tests) + price_per_test = package_price / num_tests if num_tests > 0 else 0.0 + for pt in package_tests: + test_id = pt.test_id + unit_price = price_per_test + order_discount = unit_price * discount_ratio + final_price = unit_price - order_discount + + if test_id in active_orders_map: + order = active_orders_map[test_id] + order.unit_price += unit_price + order.discount_amount += order_discount + order.final_price += final_price + if not order.package_name: + order.package_name = package_name + elif package_name and package_name not in order.package_name: + order.package_name += f", {package_name}" + elif test_id in created_orders: + order = created_orders[test_id] + order.unit_price += unit_price + order.discount_amount += order_discount + order.final_price += final_price + if not order.package_name: + order.package_name = package_name + elif package_name and package_name not in order.package_name: + order.package_name += f", {package_name}" + else: + order = Order( + order_number=f"ORD-{latest_visit.visit_id}-{test_id}", + patient_id=patient.id, + test_id=test_id, + visit_id=latest_visit.id, + ordered_by=current_user.id if current_user else None, + unit_price=unit_price, + discount_amount=order_discount, + final_price=final_price, + package_name=package_name + ) + created_orders[test_id] = order + session.add(order) + + # Log newly added test + test_def = session.get(TestDefinition, test_id) + test_name = test_def.test_name if test_def else f"Test #{test_id}" + create_audit_log( + session, + "patient", + patient.id, + "update", + current_user, + old_values={}, + new_values={"action": "Test Added", "test_name": test_name} + ) + + # Audit & Activity Logs (same transaction as data changes) + create_audit_log( + session, + "patient", + patient.id, + "update", + current_user, + old_values=old_values, + new_values={"action": "Patient Profile Updated"} + ) + log_activity_action(session, "EDIT_PATIENT", f"Updated patient {patient.full_name} (ID: {patient_id})", current_user, "patient", patient.id) + + # Single atomic commit + session.commit() + + return RedirectResponse( + url=f"/patients/edit/{patient_id}?success=Patient updated successfully!", + status_code=status.HTTP_303_SEE_OTHER + ) + except Exception as e: + session.rollback() + print(f"❌ Error updating patient: {str(e)}") + import traceback + traceback.print_exc() + return RedirectResponse( + url=f"/patients/edit/{patient_id}?error={str(e).replace(' ', '%20')}", + status_code=status.HTTP_303_SEE_OTHER + ) + +# =========================== +# PATIENT SOFT DELETE +# =========================== +@router.post("/patients/delete/{patient_id}") +def delete_patient(patient_id: str, request: Request, deleted_reason: str = Form(...), session: Session = Depends(get_session)): + if not require_permission(request, session, "patients", "delete"): + return RedirectResponse(url="/patients?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + + if patient: + old_values = model_to_dict(patient) + patient.is_active = False + patient.deleted_by = current_user.id if current_user else None + patient.deleted_at = datetime.now() + patient.deleted_reason = deleted_reason + session.add(patient) + + archive_deleted_record(session, "patient", patient.id, old_values, current_user, deleted_reason) + + create_audit_log( + session, + "patient", + patient.id, + "soft_delete", + current_user, + old_values=old_values, + new_values={"action": f"Patient Soft Deleted. Reason: {deleted_reason}"} + ) + log_activity_action(session, "DELETE_PATIENT", f"Deleted patient {patient.full_name} (ID: {patient_id}). Reason: {deleted_reason}", current_user, "patient", patient.id) + + # Single atomic commit + session.commit() + + return RedirectResponse(url="/patients?success=Patient deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + + return RedirectResponse(url="/patients?error=Patient not found", status_code=status.HTTP_303_SEE_OTHER) + + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/patients?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# DELETED PATIENTS +# =========================== +@router.get("/patients/deleted", response_class=HTMLResponse) +def deleted_patients_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "deleted_patients"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + search = request.query_params.get("search", "") + start_date_str = request.query_params.get("start_date") + end_date_str = request.query_params.get("end_date") + user_filter = request.query_params.get("user_id", "all") + + if not start_date_str: + start_date_str = datetime.now().strftime("%d-%m-%Y") + if not end_date_str: + end_date_str = start_date_str + + query = select(Patient).where(Patient.is_active == False) + + if search: + query = query.where( + (Patient.full_name.ilike(f"%{search}%")) | + (Patient.patient_id.ilike(f"%{search}%")) | + (Patient.phone_number.ilike(f"%{search}%")) + ) + + if start_date_str: + try: + start_date = datetime.strptime(start_date_str, "%d-%m-%Y").replace(hour=0, minute=0, second=0) + query = query.where(Patient.deleted_at >= start_date) + except ValueError: + pass + + if end_date_str: + try: + end_date = datetime.strptime(end_date_str, "%d-%m-%Y").replace(hour=23, minute=59, second=59) + query = query.where(Patient.deleted_at <= end_date) + except ValueError: + pass + + if user_filter and user_filter != "all": + query = query.where(Patient.deleted_by == int(user_filter)) + + query = query.options(selectinload(Patient.visits).selectinload(PatientVisit.orders)) + patients = session.exec(query.order_by(Patient.deleted_at.desc())).all() + + # Fetch all users for dropdown and dictionary + users = session.exec(select(User)).all() + user_dict = {u.id: u.full_name for u in users} + + patient_totals = {} + for p in patients: + total = 0.0 + # Get the latest visit for this patient + if p.visits: + latest_visit = sorted(p.visits, key=lambda v: v.visit_date, reverse=True)[0] + total = sum((o.unit_price or 0.0) for o in latest_visit.orders) - (latest_visit.discount_amount or 0.0) + (latest_visit.tax_amount or 0.0) + patient_totals[p.id] = total + + success = request.query_params.get("success") + error = request.query_params.get("error") + + return templates.TemplateResponse("deleted_patients.html", { + "request": request, + "patients": patients, + "patient_totals": patient_totals, + "search": search, + "start_date": start_date_str, + "end_date": end_date_str, + "user_filter": user_filter, + "users": users, + "user_dict": user_dict, + "message_success": success, + "message_error": error + }) + +@router.get("/patients/view-deleted/{patient_id}", response_class=HTMLResponse) +def view_deleted_patient(request: Request, patient_id: str, session: Session = Depends(get_session)): + if not require_permission(request, session, "deleted_patients"): + return RedirectResponse(url="/patients/deleted?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + + if not patient or patient.is_active: + return RedirectResponse(url="/patients/deleted?error=Patient not found", status_code=status.HTTP_303_SEE_OTHER) + + provinces = session.exec(select(Province).where(Province.is_active == True)).all() + regions = session.exec(select(Region).where(Region.province_id == patient.province_id)).all() if patient.province_id else [] + partners = session.exec(select(Partner).where(Partner.is_active == True)).all() + + visits = session.exec(select(PatientVisit).where(PatientVisit.patient_id == patient.id).order_by(PatientVisit.visit_date.desc())).all() + orders = session.exec(select(Order).where(Order.patient_id == patient.id).order_by(Order.order_date.desc())).all() + + return templates.TemplateResponse("view_deleted_patient.html", { + "request": request, + "patient": patient, + "provinces": provinces, + "regions": regions, + "partners": partners, + "visits": visits, + "orders": orders + }) + +@router.get("/patients/restore/{patient_id}") +def restore_patient(patient_id: str, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "deleted_patients", "restore"): + return RedirectResponse(url="/patients/deleted?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + + if patient: + old_values = model_to_dict(patient) + patient.is_active = True + patient.deleted_by = None + patient.deleted_at = None + patient.deleted_reason = None + patient.edited_by = current_user.id if current_user else None + patient.edited_at = datetime.now() + session.add(patient) + + create_audit_log( + session, + "patient", + patient.id, + "restore", + current_user, + old_values=old_values, + new_values={"action": "Patient Restored from Deleted Status"} + ) + + # Single atomic commit + session.commit() + + return RedirectResponse(url="/patients/deleted?success=Patient restored successfully!", status_code=status.HTTP_303_SEE_OTHER) + + return RedirectResponse(url="/patients/deleted?error=Patient not found", status_code=status.HTTP_303_SEE_OTHER) + + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/patients/deleted?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + + +# =========================== +# ADD NEW PAYMENT (AJAX or Form) +# =========================== +@router.post("/patient/{patient_id}/payment") +def add_patient_payment( + patient_id: str, + request: Request, + visit_id: int = Form(...), + amount: float = Form(...), + payment_method: str = Form("cash"), + note: Optional[str] = Form(None), + is_refund: bool = Form(False), + session: Session = Depends(get_session) +): + current_user = get_current_user(request, session) + if not current_user: + return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER) + + try: + visit = session.get(PatientVisit, visit_id) + patient_record = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + + if not visit or not patient_record or visit.patient_id != patient_record.id: + return RedirectResponse(url=f"/patient/edit/{patient_id}?error=Invalid visit", status_code=status.HTTP_303_SEE_OTHER) + + # 1. Create the payment record + payment = Payment( + visit_id=visit.id, + patient_id=patient_record.id, + amount=amount, + payment_method=payment_method, + note=note, + is_refund=is_refund, + recorded_by=current_user.id + ) + session.add(payment) + + # 2. Update the visit's total received amount + all_payments = session.exec(select(Payment).where(Payment.visit_id == visit.id)).all() + + total_received = sum([p.amount if not p.is_refund else -p.amount for p in all_payments]) + if is_refund: + total_received -= amount + else: + total_received += amount + + visit.received_amount = max(0, total_received) + + # Recalculate remaining + total_price = sum([(o.unit_price or 0.0) for o in visit.orders]) + discount_amt = visit.discount_amount or 0.0 + tax_amt = visit.tax_amount or 0.0 + final_total = total_price - discount_amt + tax_amt + visit.remaining_amount = max(0, final_total - visit.received_amount) + + session.add(visit) + session.commit() + + msg = "Refund recorded" if is_refund else "Payment recorded" + return RedirectResponse(url=f"/patient/edit/{patient_id}?success={msg} successfully", status_code=status.HTTP_303_SEE_OTHER) + + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/patient/edit/{patient_id}?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# DELETED TESTS +# =========================== +@router.get("/deleted_tests_page", response_class=HTMLResponse) +def deleted_tests_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "deleted_tests"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + start_date_str = request.query_params.get("start_date") + end_date_str = request.query_params.get("end_date") + user_filter = request.query_params.get("user_id", "all") + + if not start_date_str: + start_date_str = datetime.now().strftime("%d-%m-%Y") + if not end_date_str: + end_date_str = start_date_str + + query = select(DeletedRecord).where(DeletedRecord.source_table == "order") + + if start_date_str: + try: + start_date = datetime.strptime(start_date_str, "%d-%m-%Y").replace(hour=0, minute=0, second=0) + query = query.where(DeletedRecord.deleted_at >= start_date) + except ValueError: + pass + + if end_date_str: + try: + end_date = datetime.strptime(end_date_str, "%d-%m-%Y").replace(hour=23, minute=59, second=59) + query = query.where(DeletedRecord.deleted_at <= end_date) + except ValueError: + pass + + if user_filter and user_filter != "all": + query = query.where(DeletedRecord.deleted_by == int(user_filter)) + + deleted_records = session.exec(query.order_by(DeletedRecord.deleted_at.desc())).all() + + users = session.exec(select(User)).all() + user_map = {u.id: u.full_name for u in users} + + report_data = [] + for idx, rec in enumerate(deleted_records, 1): + try: + data = json.loads(rec.record_data) + except Exception: + data = {} + + patient_id = data.get("patient_id") + test_id = data.get("test_id") + + patient = session.get(Patient, patient_id) if patient_id else None + test = session.get(TestDefinition, test_id) if test_id else None + + # Safely determine price + try: + if "unit_price" in data and data["unit_price"] is not None: + p_val = float(data["unit_price"]) + elif "final_price" in data and data["final_price"] is not None: + p_val = float(data["final_price"]) + else: + p_val = float(test.price) if test and test.price is not None else 0.0 + except (ValueError, TypeError): + p_val = 0.0 + + report_data.append({ + "no": idx, + "deleted_at": rec.deleted_at.strftime("%d-%m-%Y %H:%M"), + "deleted_by_name": user_map.get(rec.deleted_by, "System"), + "patient_code": patient.patient_id if patient else "N/A", + "patient_name": patient.full_name if patient else "Unknown", + "age_gender": f"{patient.age} {patient.age_unit} - {patient.gender}" if patient else "N/A", + "test_name": test.test_name if test else "Unknown Test", + "price": p_val, + "reason": rec.deleted_reason or "No reason provided" + }) + + return templates.TemplateResponse("deleted_tests.html", { + "request": request, + "report_data": report_data, + "users": users, + "start_date": start_date_str, + "end_date": end_date_str, + "user_filter": user_filter + }) \ No newline at end of file diff --git a/routes/printing.py b/routes/printing.py new file mode 100644 index 0000000000000000000000000000000000000000..e02ad128a73fc6ac592ad6f0527e1b7858f98a01 --- /dev/null +++ b/routes/printing.py @@ -0,0 +1,821 @@ +# routes/printing.py +# Print barcode/receipt, designer pages, and print template API. + +from fastapi import APIRouter, Depends, Request, status, HTTPException +from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse +from sqlmodel import Session, select +from sqlalchemy.orm import selectinload +from datetime import datetime +from database import get_session +from models import ( + Patient, PatientVisit, Order, LabInfo, PrintTemplate, + Result, ResultDetail, Parameter, TestRange, TestDefinition, TestParameter, + TestResultType +) +from fastapi.encoders import jsonable_encoder +from fastapi import File, UploadFile +import os +import uuid +import logging +from routes.helpers import templates, get_current_user, generate_barcode_base64, calculate_age, log_audit_action, log_activity_action, require_permission, age_to_days, build_patient_visit_data +from fastapi.responses import RedirectResponse +from routes.generate_pdf import generate_native_barcode_pdf +from io import BytesIO + +router = APIRouter() + +# =========================== +# PRINT DESIGNER ROUTES +# =========================== +@router.get("/print-barcode-designer", response_class=HTMLResponse) +def print_barcode_designer(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "barcode_designer"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=303) + return templates.TemplateResponse("print_barcode_designer.html", {"request": request}) + +@router.get("/print-receipt-designer", response_class=HTMLResponse) +def print_receipt_designer(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "receipt_designer"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=303) + return templates.TemplateResponse("print_receipt_designer.html", {"request": request}) + +@router.get("/print-result-designer", response_class=HTMLResponse) +def print_result_designer(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "result_designer"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=303) + return templates.TemplateResponse("print_result_designer.html", {"request": request}) + +@router.get("/print-results", response_class=HTMLResponse) +def print_results_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "print_results"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=303) + + # Default status to double_authorized for printing + default_status = request.query_params.get("status", "double_authorized") + patient_data, filters, page, total_pages, total_count = build_patient_visit_data(session, request, status_filter=default_status) + + return templates.TemplateResponse("print_results.html", { + "request": request, + "patient_data": patient_data, + "filters": filters, + "page": page, + "total_pages": total_pages, + "total_count": total_count, + }) + +# =========================== +# MEDICAL REPORT PRINTING (Now Audited) +# =========================== +@router.get("/print-report/{patient_id}", response_class=HTMLResponse) +def print_report(patient_id: str, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "print_results", "print"): + return RedirectResponse(url="/print-results?error=Permission Denied", status_code=303) + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + return HTMLResponse(content="Patient not found", status_code=404) + + current_user = get_current_user(request, session) + if current_user: + log_activity_action(session, "PRINT_REPORT", f"Printed medical report for patient {patient.full_name}", current_user, "patient", patient.id) + session.commit() + + # Support visit_id query param to select a specific visit + visit_id_param = request.query_params.get("visit_id") + if visit_id_param: + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.visit_id == visit_id_param, PatientVisit.patient_id == patient.id) + ).first() + else: + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.id.desc()) + ).first() + + lab_info = session.exec(select(LabInfo).limit(1)).first() + template = session.exec(select(PrintTemplate).where(PrintTemplate.template_name == "result_report")).first() + barcode_data = generate_barcode_base64(patient_id) + + # Use jsonable_encoder but specifically ensure all dates are strings + encoded_patient = jsonable_encoder(patient) + encoded_visit = jsonable_encoder(visit) if visit else None + encoded_lab_info = jsonable_encoder(lab_info) if lab_info else None + + encoded_template = jsonable_encoder(template) if template else {} + + # --------------------------------------------------------- + # ✅ NEW: INJECT AUDIT LOG HERE (Tracking the print action) + # --------------------------------------------------------- + current_user = get_current_user(request, session) + if visit: + log_audit_action( + session=session, + table_name="patientvisit", + record_id=visit.id, + action="PRINT", + current_user=current_user, + new_values={"action": "Generated Medical Report PDF"} + ) + session.commit() # We must commit here because GET routes normally don't save + # --------------------------------------------------------- + + return templates.TemplateResponse("print_report.html", { + "request": request, + "patient": encoded_patient, + "visit": encoded_visit, + "lab_info": encoded_lab_info, + "template": encoded_template, + "barcode_data": barcode_data + }) + +@router.get("/view-results/{patient_id}", response_class=HTMLResponse) +def view_results(patient_id: str, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "print_results"): + return RedirectResponse(url="/print-results?error=Permission Denied", status_code=303) + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + return HTMLResponse(content="Patient not found", status_code=404) + + # Support visit_id query param to select a specific visit + visit_id_param = request.query_params.get("visit_id") + if visit_id_param: + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.visit_id == visit_id_param, PatientVisit.patient_id == patient.id) + ).first() + else: + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.id.desc()) + ).first() + + visit_user_name = None + if visit and visit.created_by: + from models import User + user = session.get(User, visit.created_by) + if user: + visit_user_name = user.full_name or user.username + + # Fetch all visits for the "Previous Results" bar + all_visits = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.visit_date.asc()) + ).all() + + return templates.TemplateResponse("view_results.html", { + "request": request, + "patient": patient, + "visit": visit, + "visit_user_name": visit_user_name, + "all_visits": all_visits + }) + + + +# =========================== +# PRINT TEMPLATE API ROUTES +# =========================== +@router.post("/api/print-template/save") +async def save_print_template(request: Request, session: Session = Depends(get_session)): + try: + data = await request.json() + template_name = data.get("template_name", "") + + # Check permissions based on template_name + req_page = "result_designer" + if template_name == "barcode_label": + req_page = "barcode_designer" + elif template_name == "receipt": + req_page = "receipt_designer" + + if not require_permission(request, session, req_page, "save"): + return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403) + + current_user = get_current_user(request, session) + existing = session.exec(select(PrintTemplate).where(PrintTemplate.template_name == data['template_name'])).first() + if existing: + existing.paper_width = data['paper_width'] + existing.paper_height = data['paper_height'] + existing.margin = data['margin'] + existing.elements = data['elements'] + existing.edited_by = current_user.id if current_user else None + existing.edited_at = datetime.now() + session.add(existing) + session.commit() + session.refresh(existing) + return {"success": True, "template_id": existing.id} + else: + new_template = PrintTemplate( + template_name=data['template_name'], template_type=data['template_type'], + paper_width=data['paper_width'], paper_height=data['paper_height'], + margin=data['margin'], elements=data['elements'], + created_by=current_user.id if current_user else None + ) + session.add(new_template) + session.commit() + session.refresh(new_template) + return {"success": True, "template_id": new_template.id} + except Exception as e: + return {"success": False, "error": str(e)} + +@router.get("/api/print-template/load/{template_name}") +def load_print_template(template_name: str, request: Request, session: Session = Depends(get_session)): + current_user = get_current_user(request, session) + if not current_user: + return {"success": False, "error": "Authentication required"} + try: + template = session.exec(select(PrintTemplate).where(PrintTemplate.template_name == template_name)).first() + if template: + return { + "success": True, + "template": { + "id": template.id, "template_name": template.template_name, + "paper_width": template.paper_width, "paper_height": template.paper_height, + "margin": template.margin, "elements": template.elements + } + } + return {"success": False, "error": "Template not found"} + except Exception as e: + return {"success": False, "error": str(e)} + +@router.get("/api/double-authorized-tests/{patient_id}") +def get_double_authorized_tests(patient_id: str, request: Request, session: Session = Depends(get_session)): + try: + order_ids_str = request.query_params.get("order_ids") + order_ids = [] + if order_ids_str: + order_ids = [int(x) for x in order_ids_str.split(",") if x.strip()] + + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + + if not patient: + return {"success": False, "error": "Patient not found"} + + # Support visit_id query param to select a specific visit + visit_id_param = request.query_params.get("visit_id") + if visit_id_param: + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.visit_id == visit_id_param, PatientVisit.patient_id == patient.id) + ).first() + else: + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.id.desc()) + ).first() + + if not visit: + return {"success": False, "error": "No visit found"} + + # Get double authorized orders + query = select(Order).options( + selectinload(Order.test).selectinload(TestDefinition.test_parameters).selectinload(TestParameter.parameter), + selectinload(Order.result).selectinload(Result.details).selectinload(ResultDetail.parameter) + ).where(Order.visit_id == visit.id, Order.status == "double_authorized") + + if order_ids: + query = query.where(Order.id.in_(order_ids)) + + orders = session.exec(query).all() + + test_ids = [order.test_id for order in orders if order.test_id] + all_result_types = session.exec( + select(TestResultType).where(TestResultType.test_id.in_(test_ids), TestResultType.is_active == True) + ).all() + result_type_map = {} + for rt in all_result_types: + result_type_map[(rt.test_id, rt.parameter_id)] = rt.result_type + + def get_result_type(test_id, param_id=None): + return result_type_map.get((test_id, param_id), "number") + + grid_rows = [] + for order in orders: + test = order.test + res = order.result + + # Fetch ranges for this test/patient + ranges = session.exec( + select(TestRange).where(TestRange.test_id == test.id, TestRange.is_active == True) + ).all() + + def find_range(param_id=None): + best = None + patient_days = age_to_days(patient.age, patient.age_unit) + for r in ranges: + if r.parameter_id == param_id: + gender_ok = r.gender_type == "both" or r.gender_type == patient.gender + range_from_days = age_to_days(r.age_from, r.age_from_unit or "year") + range_to_days = age_to_days(r.age_to, r.age_to_unit or "year") + age_ok = range_from_days <= patient_days <= range_to_days + if gender_ok and age_ok: + best = r + break + if not best and ranges: + for r in ranges: + if r.parameter_id == param_id: + return r + return best + + if test.test_parameters: + # Parent row + grid_rows.append({ + "type": "parent", + "test_name": test.test_name, + "order_id": order.id, + "status": order.status, + "print_separately": test.print_separately, + "note": res.note if res else "" + }) + + # Child rows + for tp in test.test_parameters: + param = tp.parameter + detail = next((d for d in res.details if d.parameter_id == param.id), None) + rng = find_range(param.id) + grid_rows.append({ + "type": "child", + "parameter_name": param.parameter_name, + "result_value": detail.result_value if detail else "", + "result_type": get_result_type(test.id, param.id), + "range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""), + "unit": rng.unit if rng else "", + "flag": detail.flag if detail else "", + "remark": detail.remark if detail else "" + }) + else: + # Standalone + rng = find_range(None) + grid_rows.append({ + "type": "standalone", + "test_name": test.test_name, + "order_id": order.id, + "result_value": res.result_value if res else "", + "result_type": get_result_type(test.id, None), + "range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""), + "unit": rng.unit if rng else "", + "flag": res.flag if res else "", + "remark": res.note if res else "", + "note": res.note if res else "", + "print_separately": test.print_separately + }) + + return { + "success": True, + "patient": { + "full_name": patient.full_name, + "patient_id": patient.patient_id, + "age": patient.age, + "age_unit": patient.age_unit, + "gender": patient.gender, + "doctor": patient.doctor, + "agent_name": patient.agent_name + }, + "visit": { + "visit_id": visit.visit_id, + "visit_date": visit.visit_date.strftime("%Y-%m-%d %H:%M") + }, + "results": grid_rows + } + except Exception as e: + import traceback + traceback.print_exc() + return {"success": False, "error": str(e)} + +@router.get("/api/all-visit-tests/{visit_id}") +def get_all_visit_tests(visit_id: str, request: Request, session: Session = Depends(get_session)): + """Returns ALL orders for a visit with their current status for the call centre view.""" + try: + visit = session.exec( + select(PatientVisit) + .options(selectinload(PatientVisit.patient)) + .where(PatientVisit.visit_id == visit_id) + ).first() + + if not visit: + return {"success": False, "error": "Visit not found"} + + patient = visit.patient + + orders = session.exec( + select(Order).options( + selectinload(Order.test).selectinload(TestDefinition.test_parameters).selectinload(TestParameter.parameter), + selectinload(Order.result).selectinload(Result.details).selectinload(ResultDetail.parameter) + ).where(Order.visit_id == visit.id, Order.status != "no_sample") + ).all() + + test_ids = [order.test_id for order in orders if order.test_id] + all_result_types = session.exec( + select(TestResultType).where(TestResultType.test_id.in_(test_ids), TestResultType.is_active == True) + ).all() + result_type_map = {} + for rt in all_result_types: + result_type_map[(rt.test_id, rt.parameter_id)] = rt.result_type + + def get_result_type(test_id, param_id=None): + return result_type_map.get((test_id, param_id), "number") + + grid_rows = [] + for order in orders: + test = order.test + res = order.result + if not test: + continue + + # Determine display status + if order.status == "double_authorized": + display_status = "Double AUTH" + elif order.status == "authorized": + display_status = "AUTH" + elif order.status == "resulted": + display_status = "Resulted" + else: + display_status = "Pending" + + # Fetch ranges for this test/patient + ranges = session.exec( + select(TestRange).where(TestRange.test_id == test.id, TestRange.is_active == True) + ).all() + + def find_range(param_id=None): + best = None + patient_days = age_to_days(patient.age, patient.age_unit) + for r in ranges: + if r.parameter_id == param_id: + gender_ok = r.gender_type == "both" or r.gender_type == patient.gender + range_from_days = age_to_days(r.age_from, r.age_from_unit or "year") + range_to_days = age_to_days(r.age_to, r.age_to_unit or "year") + age_ok = range_from_days <= patient_days <= range_to_days + if gender_ok and age_ok: + best = r + break + if not best and ranges: + for r in ranges: + if r.parameter_id == param_id: + return r + return best + + if test.test_parameters: + # Parent row + grid_rows.append({ + "type": "parent", + "test_name": test.test_name, + "order_id": order.id, + "status": order.status, + "display_status": display_status, + "print_separately": test.print_separately, + "note": res.note if res else "" + }) + # Child rows + for tp in test.test_parameters: + param = tp.parameter + detail = next((d for d in res.details if d.parameter_id == param.id), None) if res else None + rng = find_range(param.id) + grid_rows.append({ + "type": "child", + "parameter_name": param.parameter_name, + "result_value": detail.result_value if detail else "", + "result_type": get_result_type(test.id, param.id), + "range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""), + "range_type": rng.range_type if rng else None, + "unit": rng.unit if rng else "", + "flag": detail.flag if detail else "", + "remark": detail.remark if detail else "", + "display_status": display_status + }) + else: + # Standalone + rng = find_range(None) + grid_rows.append({ + "type": "standalone", + "test_name": test.test_name, + "order_id": order.id, + "status": order.status, + "display_status": display_status, + "result_value": res.result_value if res else "", + "result_type": get_result_type(test.id, None), + "range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""), + "range_type": rng.range_type if rng else None, + "unit": rng.unit if rng else "", + "flag": res.flag if res else "", + "remark": res.note if res else "", + "note": res.note if res else "", + "print_separately": test.print_separately + }) + + return { + "success": True, + "results": grid_rows + } + except Exception as e: + import traceback + traceback.print_exc() + return {"success": False, "error": str(e)} + +@router.post("/api/upload-watermark") +async def upload_watermark(file: UploadFile = File(...)): + try: + os.makedirs("uploads", exist_ok=True) + ext = os.path.splitext(file.filename)[1] + filename = f"watermark_{uuid.uuid4().hex}{ext}" + filepath = os.path.join("uploads", filename) + with open(filepath, "wb") as f: + f.write(await file.read()) + return {"success": True, "filename": filename} + except Exception as e: + return {"success": False, "error": str(e)} + +# =========================== +# PRINT ROUTES (WITH LOCAL BARCODE) +# =========================== +@router.get("/print-barcode/{patient_id}", response_class=HTMLResponse) +def print_barcode(patient_id: str, request: Request, session: Session = Depends(get_session)): + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + return HTMLResponse(content="Patient not found", status_code=404) + + current_user = get_current_user(request, session) + if current_user: + log_activity_action(session, "PRINT_BARCODE", f"Printed barcode for patient {patient.full_name}", current_user, "patient", patient.id) + session.commit() + + # Load saved barcode template design + template = session.exec(select(PrintTemplate).where(PrintTemplate.template_name == "barcode")).first() + template_data = None + if template: + template_data = { + "paper_width": template.paper_width, + "paper_height": template.paper_height, + "margin": template.margin, + "elements": template.elements + } + + # Load visit data + visit_id_param = request.query_params.get("visit_id") if request else None + if visit_id_param: + visit = session.exec(select(PatientVisit).where(PatientVisit.visit_id == visit_id_param, PatientVisit.patient_id == patient.id)).first() + else: + visit = session.exec(select(PatientVisit).where(PatientVisit.patient_id == patient.id).order_by(PatientVisit.id.desc())).first() + + visit_id = visit.visit_id if visit else "" + visit_date = visit.visit_date.strftime('%Y-%m-%d %H:%M') if visit and visit.visit_date else "" + + # Get orders with test + sample_type eagerly loaded + orders = session.exec( + select(Order).options( + selectinload(Order.test).selectinload(TestDefinition.sample_type) + ).where(Order.visit_id == visit.id) + ).all() if visit else [] + + # Build tests_by_sample_type using test_short_name + tests_by_sample_type = {} + for order in orders: + if order.test: + sample_type_name = order.test.sample_type.sample_name if order.test.sample_type else "Unknown" + if sample_type_name not in tests_by_sample_type: + tests_by_sample_type[sample_type_name] = [] + test_display = order.test.test_short_name if order.test.test_short_name else order.test.test_name + tests_by_sample_type[sample_type_name].append(test_display) + + # If no tests, still have at least one barcode + if not tests_by_sample_type: + tests_by_sample_type = {"Unknown": []} + + lab_info = session.exec(select(LabInfo).limit(1)).first() + + # Generate print_token for API image access + import hashlib + from app.config import SECRET_KEY + print_token = hashlib.sha256(SECRET_KEY.encode()).hexdigest()[:16] + + return templates.TemplateResponse("print_barcode.html", { + "request": request, + "patient": patient, + "lab_info": lab_info, + "template_data": template_data, + "tests_by_sample_type": tests_by_sample_type, + "visit_id": visit_id, + "visit_date": visit_date, + "print_token": print_token + }) + +@router.get("/api/print-barcode-pdf/{patient_id}") +def api_print_barcode_pdf(patient_id: str, request: Request, session: Session = Depends(get_session)): + """ + Returns a mathematically perfect, native PDF generation of the barcode label using ReportLab. + Bypasses all client-side browser/HTML rendering for optimal thermal printer compatibility. + """ + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + raise HTTPException(status_code=404, detail="Patient not found") + + barcode_template = session.exec(select(PrintTemplate).where(PrintTemplate.template_name == "barcode")).first() + if not barcode_template: + raise HTTPException(status_code=404, detail="No barcode template configured in the database") + + # Support visit_id query param to select a specific visit + visit_id_param = request.query_params.get("visit_id") if request else None + if visit_id_param: + visit = session.exec(select(PatientVisit).where(PatientVisit.visit_id == visit_id_param, PatientVisit.patient_id == patient.id)).first() + else: + visit = session.exec(select(PatientVisit).where(PatientVisit.patient_id == patient.id).order_by(PatientVisit.id.desc())).first() + v_id = visit.visit_id if visit else '' + v_date = visit.visit_date.strftime('%Y-%m-%d %H:%M') if visit and visit.visit_date else '' + + # Get orders with test + sample_type eagerly loaded + orders = session.exec( + select(Order).options( + selectinload(Order.test).selectinload(TestDefinition.sample_type) + ).where(Order.visit_id == visit.id) + ).all() if visit else [] + + tests_by_sample_type = {} + for order in orders: + if order.test: + sample_type_name = order.test.sample_type.sample_name if order.test.sample_type else "Unknown" + if sample_type_name not in tests_by_sample_type: + tests_by_sample_type[sample_type_name] = [] + test_display = order.test.test_short_name if order.test.test_short_name else order.test.test_name + tests_by_sample_type[sample_type_name].append(test_display) + + try: + pdf_buffer = generate_native_barcode_pdf(patient, tests_by_sample_type, barcode_template, visit_id=v_id, visit_date=v_date) + response = StreamingResponse(pdf_buffer, media_type="application/pdf") + response.headers["Content-Disposition"] = f"attachment; filename=barcode_{patient_id}.pdf" + return response + except Exception as e: + import traceback + logging.error(f"Failed to generate native barcode PDF: {e}\n{traceback.format_exc()}") + print(f"❌ Barcode PDF Error for {patient_id}: {e}") + traceback.print_exc() + raise HTTPException(status_code=500, detail=str(e)) + +@router.get("/api/print-barcode-image/{patient_id}") +def api_print_barcode_image(patient_id: str, page: int = 0, request: Request = None, session: Session = Depends(get_session)): + """ + Returns a high-DPI PNG image of the barcode label (rendered server-side with Pillow). + One page per sample type. Use ?page=N to get a specific page. + Response header X-Page-Count contains total number of pages. + """ + from app.services.barcode_image_service import generate_barcode_label_image + + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + raise HTTPException(status_code=404, detail="Patient not found") + + barcode_template = session.exec(select(PrintTemplate).where(PrintTemplate.template_name == "barcode")).first() + if not barcode_template: + raise HTTPException(status_code=404, detail="No barcode template configured") + + # Support visit_id query param to select a specific visit + visit_id_param = request.query_params.get("visit_id") if request else None + if visit_id_param: + visit = session.exec(select(PatientVisit).where(PatientVisit.visit_id == visit_id_param, PatientVisit.patient_id == patient.id)).first() + else: + visit = session.exec(select(PatientVisit).where(PatientVisit.patient_id == patient.id).order_by(PatientVisit.id.desc())).first() + v_id = visit.visit_id if visit else '' + v_date = visit.visit_date.strftime('%Y-%m-%d %H:%M') if visit and visit.visit_date else '' + + orders = session.exec( + select(Order).options( + selectinload(Order.test).selectinload(TestDefinition.sample_type) + ).where(Order.visit_id == visit.id) + ).all() if visit else [] + + tests_by_sample_type = {} + for order in orders: + if order.test: + sample_type_name = order.test.sample_type.sample_name if order.test.sample_type else "Unknown" + if sample_type_name not in tests_by_sample_type: + tests_by_sample_type[sample_type_name] = [] + test_display = order.test.test_short_name if order.test.test_short_name else order.test.test_name + tests_by_sample_type[sample_type_name].append(test_display) + + try: + pages = generate_barcode_label_image(patient, tests_by_sample_type, barcode_template, visit_id=v_id, visit_date=v_date) + if not pages: + raise HTTPException(status_code=500, detail="No barcode pages generated") + total = len(pages) + idx = max(0, min(page, total - 1)) + return StreamingResponse(pages[idx], media_type="image/png", + headers={ + "Content-Disposition": f"inline; filename=barcode_{patient_id}_p{idx}.png", + "X-Page-Count": str(total), + }) + except Exception as e: + import traceback + logging.error(f"Barcode image generation failed: {e}\n{traceback.format_exc()}") + raise HTTPException(status_code=500, detail=str(e)) + +@router.get("/print-receipt/{patient_id}", response_class=HTMLResponse) +def print_receipt(patient_id: str, request: Request, session: Session = Depends(get_session)): + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + return HTMLResponse(content="Patient not found", status_code=404) + + current_user = get_current_user(request, session) + if current_user: + log_activity_action(session, "PRINT_RECEIPT", f"Printed receipt for patient {patient.full_name}", current_user, "patient", patient.id) + session.commit() + + # Load saved receipt template design + template = session.exec(select(PrintTemplate).where(PrintTemplate.template_name == "receipt")).first() + template_data = None + if template: + template_data = { + "paper_width": template.paper_width, + "paper_height": template.paper_height, + "margin": template.margin, + "elements": template.elements + } + + # Load lab info + lab_info = session.exec(select(LabInfo).limit(1)).first() + + # Load visit data + accounting + visit_id_param = request.query_params.get("visit_id") + if visit_id_param: + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.visit_id == visit_id_param, PatientVisit.patient_id == patient.id) + ).first() + else: + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.id.desc()) + ).first() + + visit_id = visit.visit_id if visit else "" + visit_date = visit.visit_date.strftime('%d/%m/%Y %H:%M') if visit and visit.visit_date else "" + + received_amount = visit.received_amount if visit else 0.0 + discount_amount = visit.discount_amount if visit else 0.0 + tax_amount = visit.tax_amount if visit and visit.tax_amount else 0.0 + remaining_amount = visit.remaining_amount if visit else 0.0 + + # Load orders with test relationship + orders = session.exec( + select(Order).options( + selectinload(Order.test) + ).where(Order.visit_id == visit.id) + ).all() if visit else [] + + # Build orders data for template + orders_data = [] + for order in orders: + test = order.test + orders_data.append({ + "test_name": test.test_name if test else 'Unknown', + "test_short_name": test.test_short_name if test and test.test_short_name else (test.test_name if test else 'Unknown'), + "package_name": order.package_name or None, + "unit_price": order.unit_price or (test.price if test else 0), + "final_price": order.final_price or (order.unit_price or 0), + "test_id": order.test_id + }) + + # Calculate accounting totals (same logic as /api/patient/) + total_amount = sum([float(o["final_price"]) if o["final_price"] else 0 for o in orders_data]) + total_after_tax = total_amount - discount_amount + tax_amount + + # --- Compute page_size as a clean CSS string (MUST be done in Python, not Jinja inside CSS!) --- + def normalize_dim(val, default_unit='mm'): + """Ensure a CSS dimension string always has a unit (e.g., '210' -> '210mm').""" + if not val or str(val).strip() in ('auto', ''): + return None + val = str(val).strip() + import re + if re.match(r'^[\d\.]+$', val): # pure number, no unit + return val + default_unit + return val + + if template_data: + pw = normalize_dim(template_data.get("paper_width")) or "80mm" + ph = normalize_dim(template_data.get("paper_height")) + if ph: + page_size = f"{pw} {ph}" + else: + page_size = f"{pw} 210mm" + else: + page_size = "80mm 210mm" + + return templates.TemplateResponse("print_receipt_page.html", { + "request": request, + "patient": patient, + "lab_info": lab_info, + "template_data": template_data, + "orders": orders_data, + "visit_id": visit_id, + "visit_date": visit_date, + "total_amount": total_amount, + "discount_amount": discount_amount, + "tax_amount": tax_amount, + "total_after_tax": total_after_tax, + "paid_amount": received_amount, + "remain_amount": remaining_amount, + "page_size": page_size, + }) \ No newline at end of file diff --git a/routes/reports.py b/routes/reports.py new file mode 100644 index 0000000000000000000000000000000000000000..9a8665c061912c6e61cce0877b122b7e7ddb7481 --- /dev/null +++ b/routes/reports.py @@ -0,0 +1,843 @@ +# routes/reports.py +from fastapi import APIRouter, Depends, Request, status, UploadFile, File, Form +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlmodel import Session, select +from datetime import datetime, timedelta +from typing import Optional +import os +import secrets + +from database import get_session +from models import PatientVisit, Expense, User, Order, TestDefinition, Device, ExpenseType +from routes.helpers import templates, require_permission, get_current_user, create_audit_log, model_to_dict + +router = APIRouter() + +# =========================== +# DETAILED INCOME REPORT +# =========================== +@router.get("/reports/detailed-income", response_class=HTMLResponse) +def detailed_income_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "detailed_income"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + start_date_str = request.query_params.get("start_date") + end_date_str = request.query_params.get("end_date") + + if not start_date_str: + start_date_str = datetime.now().strftime("%Y-%m-%d") + + if not end_date_str: + end_date_str = start_date_str + + try: + start_date = datetime.strptime(start_date_str, "%Y-%m-%d").replace(hour=0, minute=0, second=0, microsecond=0) + end_date = datetime.strptime(end_date_str, "%Y-%m-%d").replace(hour=23, minute=59, second=59, microsecond=999999) + except ValueError: + return RedirectResponse(url="/reports/detailed-income?error=Invalid date format", status_code=status.HTTP_303_SEE_OTHER) + + # 1. Fetch Visits for the selected date + visits = session.exec( + select(PatientVisit) + .where(PatientVisit.visit_date >= start_date) + .where(PatientVisit.visit_date <= end_date) + ).all() + + # 2. Fetch Expenses for the selected date + expenses = session.exec( + select(Expense) + .where(Expense.expense_date >= start_date) + .where(Expense.expense_date <= end_date) + ).all() + + # Calculate Totals + total_received = sum((v.received_amount or 0.0) for v in visits) + total_discount = sum((v.discount_amount or 0.0) for v in visits) + total_tax = sum((v.tax_amount or 0.0) for v in visits) + total_remain = sum((v.remaining_amount or 0.0) for v in visits) + + total_amount_without_discount = total_received + total_remain + total_discount - total_tax + + total_expense = sum((e.amount or 0.0) for e in expenses) + + # Net Formulas + net_amount_1 = total_amount_without_discount - (total_discount + total_expense + total_remain) + net_amount_2 = total_amount_without_discount - (total_discount + total_expense + total_remain + total_tax) + + return templates.TemplateResponse("detailed_income.html", { + "request": request, + "start_date": start_date_str, + "end_date": end_date_str, + "total_amount_without_discount": round(total_amount_without_discount, 2), + "total_discount": round(total_discount, 2), + "total_expense": round(total_expense, 2), + "total_tax": round(total_tax, 2), + "total_remain": round(total_remain, 2), + "total_received": round(total_received, 2), + "net_amount_1": round(net_amount_1, 2), + "net_amount_2": round(net_amount_2, 2) + }) + +# =========================== +# NET AMOUNTS REPORT +# =========================== +@router.get("/reports/net-amounts", response_class=HTMLResponse) +def net_amounts_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "net_amounts"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + start_date_str = request.query_params.get("start_date") + end_date_str = request.query_params.get("end_date") + + if not start_date_str: + start_date_str = datetime.now().strftime("%Y-%m-%d") + + if not end_date_str: + end_date_str = start_date_str + + try: + start_date = datetime.strptime(start_date_str, "%Y-%m-%d").replace(hour=0, minute=0, second=0, microsecond=0) + end_date = datetime.strptime(end_date_str, "%Y-%m-%d").replace(hour=23, minute=59, second=59, microsecond=999999) + except ValueError: + return RedirectResponse(url="/reports/net-amounts?error=Invalid date format", status_code=status.HTTP_303_SEE_OTHER) + + # 1. Fetch Visits + visits = session.exec( + select(PatientVisit) + .where(PatientVisit.visit_date >= start_date) + .where(PatientVisit.visit_date <= end_date) + ).all() + + # 2. Fetch Expenses + expenses = session.exec( + select(Expense) + .where(Expense.expense_date >= start_date) + .where(Expense.expense_date <= end_date) + ).all() + + # Group by date + from collections import defaultdict + daily_data = defaultdict(lambda: { + "received": 0.0, "discount": 0.0, "tax": 0.0, "remain": 0.0, "expense": 0.0 + }) + + for v in visits: + d_str = v.visit_date.strftime("%d-%m-%Y") + daily_data[d_str]["received"] += (v.received_amount or 0.0) + daily_data[d_str]["discount"] += (v.discount_amount or 0.0) + daily_data[d_str]["tax"] += (v.tax_amount or 0.0) + daily_data[d_str]["remain"] += (v.remaining_amount or 0.0) + + for e in expenses: + d_str = e.expense_date.strftime("%d-%m-%Y") + daily_data[d_str]["expense"] += (e.amount or 0.0) + + rows = [] + total_net_with_tax = 0.0 + total_net_without_tax = 0.0 + + # Ensure dates are sorted chronologically + all_dates = sorted(list(daily_data.keys()), key=lambda x: datetime.strptime(x, "%d-%m-%Y")) + + for d_str in all_dates: + data = daily_data[d_str] + + tot_recv = data["received"] + tot_disc = data["discount"] + tot_tax = data["tax"] + tot_rem = data["remain"] + tot_exp = data["expense"] + + tot_amt_without_disc = tot_recv + tot_rem + tot_disc - tot_tax + + net_with = tot_amt_without_disc - (tot_disc + tot_exp + tot_rem) + net_without = tot_amt_without_disc - (tot_disc + tot_exp + tot_rem + tot_tax) + + rows.append({ + "date": d_str, + "net_with_tax": net_with, + "net_without_tax": net_without + }) + + total_net_with_tax += net_with + total_net_without_tax += net_without + + return templates.TemplateResponse("net_amounts.html", { + "request": request, + "start_date": start_date_str, + "end_date": end_date_str, + "rows": rows, + "total_net_with_tax": total_net_with_tax, + "total_net_with_tax": total_net_with_tax, + "total_net_without_tax": total_net_without_tax + }) + +# =========================== +# PAYMENT RECORDS REPORT +# =========================== +@router.get("/reports/payment-records", response_class=HTMLResponse) +def payment_records_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "payment_records"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + start_date_str = request.query_params.get("start_date") + start_time_str = request.query_params.get("start_time", "00:00") + end_date_str = request.query_params.get("end_date") + end_time_str = request.query_params.get("end_time", "23:59") + + record_type = request.query_params.get("record_type", "all") + user_filter = request.query_params.get("user_id", "all") + + if not start_date_str: + start_date_str = datetime.now().strftime("%Y-%m-%d") + if not end_date_str: + end_date_str = start_date_str + + try: + start_datetime = datetime.strptime(f"{start_date_str} {start_time_str}", "%Y-%m-%d %H:%M") + end_datetime = datetime.strptime(f"{end_date_str} {end_time_str}", "%Y-%m-%d %H:%M").replace(second=59, microsecond=999999) + except ValueError: + return RedirectResponse(url="/reports/payment-records?error=Invalid datetime format", status_code=status.HTTP_303_SEE_OTHER) + + # Fetch users for dropdown + users = session.exec(select(User)).all() + user_dict = {u.id: u.full_name for u in users} + + records = [] + + if record_type in ["all", "receive"]: + query = select(PatientVisit).where(PatientVisit.visit_date >= start_datetime, PatientVisit.visit_date <= end_datetime) + if user_filter != "all": + query = query.where(PatientVisit.created_by == int(user_filter)) + + visits = session.exec(query).all() + for v in visits: + if v.received_amount and v.received_amount > 0: + user_name = user_dict.get(v.created_by, "Unknown") + records.append({ + "datetime": v.visit_date, + "date_str": v.visit_date.strftime("%d-%m-%Y %H:%M"), + "user": user_name, + "patient_name": v.patient.full_name if v.patient else "-", + "type": "Receive", + "price": v.received_amount, + "id": f"visit_{v.id}" + }) + + if record_type in ["all", "expense"]: + query = select(Expense).where(Expense.expense_date >= start_datetime, Expense.expense_date <= end_datetime) + if user_filter != "all": + query = query.where(Expense.created_by == int(user_filter)) + + expenses = session.exec(query).all() + for e in expenses: + if e.amount and e.amount > 0: + user_name = user_dict.get(e.created_by, "Unknown") + records.append({ + "datetime": e.expense_date, + "date_str": e.expense_date.strftime("%d-%m-%Y %H:%M"), + "user": user_name, + "patient_name": "-", + "type": "Expense", + "price": -e.amount, + "id": f"expense_{e.id}" + }) + + # Sort descending by datetime + records.sort(key=lambda x: x["datetime"], reverse=True) + + # Add NO (1, 2, ...) + for i, r in enumerate(records): + r["no"] = i + 1 + + total_price = sum(r["price"] for r in records) + + return templates.TemplateResponse("payment_records.html", { + "request": request, + "start_date": start_date_str, + "start_time": start_time_str, + "end_date": end_date_str, + "end_time": end_time_str, + "record_type": record_type, + "user_filter": user_filter, + "users": users, + "records": records, + "total_price": total_price + }) + +# =========================== +# PATIENTS NUMBER REPORT +# =========================== +@router.get("/reports/patients-number", response_class=HTMLResponse) +def patients_number_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "patients_number"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + start_date_str = request.query_params.get("start_date") + start_time_str = request.query_params.get("start_time", "00:00") + end_date_str = request.query_params.get("end_date") + end_time_str = request.query_params.get("end_time", "23:59") + + if not start_date_str: + start_date_str = datetime.now().strftime("%Y-%m-%d") + if not end_date_str: + end_date_str = start_date_str + + try: + start_datetime = datetime.strptime(f"{start_date_str} {start_time_str}", "%Y-%m-%d %H:%M") + end_datetime = datetime.strptime(f"{end_date_str} {end_time_str}", "%Y-%m-%d %H:%M").replace(second=59, microsecond=999999) + except ValueError: + return RedirectResponse(url="/reports/patients-number?error=Invalid datetime format", status_code=status.HTTP_303_SEE_OTHER) + + query = select(PatientVisit).where(PatientVisit.visit_date >= start_datetime, PatientVisit.visit_date <= end_datetime) + visits = session.exec(query).all() + + # Group by date + from collections import defaultdict + daily_data = defaultdict(set) + + for v in visits: + # Check if the visit has at least one order, and ALL its orders have results that are double_authorized + if len(v.orders) > 0 and all((o.result and o.result.double_authorized) for o in v.orders): + d_str = v.visit_date.strftime("%d-%m-%Y") + daily_data[d_str].add(v.patient_id) + + rows = [] + total_patients = 0 + + all_dates = sorted(list(daily_data.keys()), key=lambda x: datetime.strptime(x, "%d-%m-%Y")) + + for d_str in all_dates: + p_count = len(daily_data[d_str]) + if p_count > 0: + rows.append({ + "date": d_str, + "patient_count": p_count + }) + total_patients += p_count + + return templates.TemplateResponse("patients_number.html", { + "request": request, + "start_date": start_date_str, + "start_time": start_time_str, + "end_date": end_date_str, + "end_time": end_time_str, + "rows": rows, + "total_patients": total_patients + }) + +# =========================== +# TESTS NUMBER REPORT +# =========================== +@router.get("/reports/tests-number", response_class=HTMLResponse) +def tests_number_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "tests_number"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + start_date_str = request.query_params.get("start_date") + start_time_str = request.query_params.get("start_time", "00:00") + end_date_str = request.query_params.get("end_date") + end_time_str = request.query_params.get("end_time", "23:59") + + test_filter = request.query_params.get("test_id", "all") + device_filter = request.query_params.get("device_id", "all") + + if not start_date_str: + start_date_str = datetime.now().strftime("%Y-%m-%d") + if not end_date_str: + end_date_str = start_date_str + + try: + start_datetime = datetime.strptime(f"{start_date_str} {start_time_str}", "%Y-%m-%d %H:%M") + end_datetime = datetime.strptime(f"{end_date_str} {end_time_str}", "%Y-%m-%d %H:%M").replace(second=59, microsecond=999999) + except ValueError: + return RedirectResponse(url="/reports/tests-number?error=Invalid datetime format", status_code=status.HTTP_303_SEE_OTHER) + + tests_list = session.exec(select(TestDefinition).where(TestDefinition.deleted_at == None)).all() + devices_list = session.exec(select(Device).where(Device.deleted_at == None)).all() + + query = select(Order).where(Order.order_date >= start_datetime, Order.order_date <= end_datetime) + + if test_filter != "all": + query = query.where(Order.test_id == int(test_filter)) + + orders = session.exec(query).all() + + # Group by date and test name + from collections import defaultdict + daily_data = defaultdict(int) + + for o in orders: + if o.result and o.result.double_authorized: + if device_filter != "all" and str(o.result.device_id) != device_filter: + continue + + d_str = o.order_date.strftime("%d-%m-%Y") + test_name = o.test.test_name if o.test else "Unknown" + daily_data[(d_str, test_name)] += 1 + + rows = [] + total_tests = 0 + + all_keys = sorted(list(daily_data.keys()), key=lambda x: (datetime.strptime(x[0], "%d-%m-%Y"), x[1])) + + for k in all_keys: + d_str, test_name = k + t_count = daily_data[k] + if t_count > 0: + rows.append({ + "date": d_str, + "test_name": test_name, + "test_count": t_count + }) + total_tests += t_count + + return templates.TemplateResponse("tests_number.html", { + "request": request, + "start_date": start_date_str, + "start_time": start_time_str, + "end_date": end_date_str, + "end_time": end_time_str, + "test_filter": test_filter, + "device_filter": device_filter, + "tests": tests_list, + "devices": devices_list, + "rows": rows, + "total_tests": total_tests + }) + +# =========================== +# DISCOUNT REPORT +# =========================== +@router.get("/reports/discount", response_class=HTMLResponse) +def discount_report_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "discount_report"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + start_date_str = request.query_params.get("start_date") + start_time_str = request.query_params.get("start_time", "00:00") + end_date_str = request.query_params.get("end_date") + end_time_str = request.query_params.get("end_time", "23:59") + + user_filter = request.query_params.get("user_id", "all") + patient_id_filter = request.query_params.get("patient_id", "").strip() + patient_name_filter = request.query_params.get("patient_name", "").strip() + + if not start_date_str: + start_date_str = datetime.now().strftime("%Y-%m-%d") + if not end_date_str: + end_date_str = start_date_str + + try: + start_datetime = datetime.strptime(f"{start_date_str} {start_time_str}", "%Y-%m-%d %H:%M") + end_datetime = datetime.strptime(f"{end_date_str} {end_time_str}", "%Y-%m-%d %H:%M").replace(second=59, microsecond=999999) + except ValueError: + return RedirectResponse(url="/reports/discount?error=Invalid datetime format", status_code=status.HTTP_303_SEE_OTHER) + + # Fetch users for dropdown + users = session.exec(select(User)).all() + user_dict = {u.id: u.full_name for u in users} + + # Query PatientVisit where discount_amount > 0 and within date range + from models import Patient + query = select(PatientVisit).where( + PatientVisit.discount_amount > 0, + PatientVisit.visit_date >= start_datetime, + PatientVisit.visit_date <= end_datetime + ) + + if patient_id_filter or patient_name_filter: + query = query.join(Patient) + if patient_id_filter: + query = query.where(Patient.patient_id.ilike(f"%{patient_id_filter}%")) + if patient_name_filter: + query = query.where(Patient.full_name.ilike(f"%{patient_name_filter}%")) + + if user_filter != "all": + # Check if the user either created or edited the visit + query = query.where((PatientVisit.created_by == int(user_filter)) | (PatientVisit.edited_by == int(user_filter))) + + visits = session.exec(query.order_by(PatientVisit.visit_date.desc())).all() + + records = [] + total_discount = 0.0 + + for i, v in enumerate(visits, 1): + # Determine the user responsible for the discount. + # Use edited_by if available (since discount could be added on edit), otherwise created_by. + action_user_id = v.edited_by if v.edited_by else v.created_by + user_name = user_dict.get(action_user_id, "Unknown") + + discount_amount = float(v.discount_amount) if v.discount_amount else 0.0 + + records.append({ + "no": i, + "datetime": v.visit_date.strftime("%d-%m-%Y %H:%M"), + "patient_code": v.patient.patient_id if v.patient else "-", + "patient_name": v.patient.full_name if v.patient else "-", + "user": user_name, + "discount_amount": discount_amount, + "discount_note": v.discount_note or "" + }) + total_discount += discount_amount + + return templates.TemplateResponse("discount_report.html", { + "request": request, + "start_date": start_date_str, + "start_time": start_time_str, + "end_date": end_date_str, + "end_time": end_time_str, + "user_filter": user_filter, + "patient_id_filter": patient_id_filter, + "patient_name_filter": patient_name_filter, + "users": users, + "records": records, + "total_discount": total_discount + }) + + +# =========================== +# EXPENSES REPORT +# =========================== +EXPENSES_UPLOAD_DIR = "uploads/expenses" +os.makedirs(EXPENSES_UPLOAD_DIR, exist_ok=True) + +@router.get("/reports/expenses", response_class=HTMLResponse) +def expenses_report_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "expenses_report"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + start_date_str = request.query_params.get("start_date") + end_date_str = request.query_params.get("end_date") + type_filter = request.query_params.get("type_id", "all") + user_filter = request.query_params.get("user_id", "all") + + # Default date range: first day of current month to today + today = datetime.now() + if not start_date_str: + start_date_str = today.replace(day=1).strftime("%d-%m-%Y") + if not end_date_str: + end_date_str = today.strftime("%d-%m-%Y") + + try: + start_datetime = datetime.strptime(start_date_str, "%d-%m-%Y").replace(hour=0, minute=0, second=0, microsecond=0) + end_datetime = datetime.strptime(end_date_str, "%d-%m-%Y").replace(hour=23, minute=59, second=59, microsecond=999999) + except ValueError: + return RedirectResponse(url="/reports/expenses?error=Invalid date format. Use DD-MM-YYYY", status_code=status.HTTP_303_SEE_OTHER) + + # Fetch users for dropdown and initials/full name lookup + users = session.exec(select(User)).all() + user_dict = {u.id: u.full_name for u in users} + + # Fetch expense types for dropdown + types = session.exec(select(ExpenseType).order_by(ExpenseType.type_name.asc())).all() + + # Query Expense joined with ExpenseType and user filters + query = select(Expense).where( + Expense.expense_date >= start_datetime, + Expense.expense_date <= end_datetime + ) + + if type_filter != "all": + query = query.where(Expense.type_id == int(type_filter)) + + if user_filter != "all": + query = query.where(Expense.created_by == int(user_filter)) + + expenses = session.exec(query.order_by(Expense.expense_date.desc())).all() + + # Calculate sum row total + total_amount = sum(e.amount for e in expenses) + + # Prepare serializable list for frontend js + expenses_json = [] + for e in expenses: + d = model_to_dict(e) + if d.get("expense_date"): + d["expense_date"] = e.expense_date.strftime("%Y-%m-%d") + expenses_json.append(d) + + return templates.TemplateResponse("expenses_report.html", { + "request": request, + "start_date": start_date_str, + "end_date": end_date_str, + "type_filter": type_filter, + "user_filter": user_filter, + "users": users, + "expense_types": types, + "expenses": expenses, + "expenses_json": expenses_json, + "user_dict": user_dict, + "total_amount": total_amount + }) + + +@router.post("/reports/expenses/delete/{expense_id}") +def delete_expense_from_report(expense_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "expenses_report", "delete"): + return RedirectResponse(url="/reports/expenses?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + expense = session.get(Expense, expense_id) + if expense: + old_values = model_to_dict(expense) + + # Physically delete uploaded file if it exists + if expense.file_path and os.path.exists(expense.file_path): + try: + os.remove(expense.file_path) + except Exception: + pass + + create_audit_log(session, "expense", expense.id, "delete", current_user, old_values=old_values) + session.delete(expense) + session.commit() + return RedirectResponse(url="/reports/expenses?success=Expense deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/reports/expenses?error=Expense not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/reports/expenses?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + + +@router.post("/reports/expenses/update/{expense_id}") +async def update_expense_from_report( + expense_id: int, + type_id: int = Form(...), + expense_date: str = Form(...), + amount: float = Form(...), + note: Optional[str] = Form(None), + file: Optional[UploadFile] = File(None), + request: Request = None, + session: Session = Depends(get_session) +): + if not require_permission(request, session, "expenses_report", "edit"): + return RedirectResponse(url="/reports/expenses?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + expense = session.get(Expense, expense_id) + if not expense: + return RedirectResponse(url="/reports/expenses?error=Expense not found", status_code=status.HTTP_303_SEE_OTHER) + + old_values = model_to_dict(expense) + + # Handle file upload if provided + if file and file.filename: + # Delete old file + if expense.file_path and os.path.exists(expense.file_path): + try: + os.remove(expense.file_path) + except Exception: + pass + + ext = os.path.splitext(file.filename)[1].lower() + secure_filename = f"EXP_{secrets.token_hex(8)}{ext}" + file_path = os.path.join(EXPENSES_UPLOAD_DIR, secure_filename).replace("\\", "/") + expense.file_path = file_path + expense.file_name = file.filename + + with open(file_path, "wb") as buffer: + content = await file.read() + buffer.write(content) + + # Parse date (handles both YYYY-MM-DD and DD-MM-YYYY formats) + try: + exp_dt = datetime.strptime(expense_date, "%Y-%m-%d") + expense.expense_date = exp_dt + except Exception: + try: + exp_dt = datetime.strptime(expense_date, "%d-%m-%Y") + expense.expense_date = exp_dt + except Exception: + pass + + expense.type_id = type_id + expense.amount = amount + expense.note = note + expense.edited_by = current_user.id if current_user else None + expense.edited_at = datetime.now() + + session.add(expense) + session.commit() + session.refresh(expense) + + create_audit_log(session, "expense", expense.id, "update", current_user, old_values=old_values, new_values=model_to_dict(expense)) + return RedirectResponse(url="/reports/expenses?success=Expense updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/reports/expenses?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + + +# =========================== +# REMAIN REPORT +# =========================== +@router.get("/reports/remain", response_class=HTMLResponse) +def remain_report_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "remain_report"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + start_date_str = request.query_params.get("start_date") + start_time_str = request.query_params.get("start_time", "00:00") + end_date_str = request.query_params.get("end_date") + end_time_str = request.query_params.get("end_time", "23:59") + + user_filter = request.query_params.get("user_id", "all") + patient_id_filter = request.query_params.get("patient_id", "").strip() + patient_name_filter = request.query_params.get("patient_name", "").strip() + + if not start_date_str: + start_date_str = datetime.now().strftime("%Y-%m-%d") + if not end_date_str: + end_date_str = start_date_str + + try: + start_datetime = datetime.strptime(f"{start_date_str} {start_time_str}", "%Y-%m-%d %H:%M") + end_datetime = datetime.strptime(f"{end_date_str} {end_time_str}", "%Y-%m-%d %H:%M").replace(second=59, microsecond=999999) + except ValueError: + return RedirectResponse(url="/reports/remain?error=Invalid datetime format", status_code=status.HTTP_303_SEE_OTHER) + + # Fetch users for dropdown + users = session.exec(select(User)).all() + user_dict = {u.id: u.full_name for u in users} + + # Query PatientVisit where remaining_amount > 0 and within date range + from models import Patient + query = select(PatientVisit).where( + PatientVisit.remaining_amount > 0, + PatientVisit.visit_date >= start_datetime, + PatientVisit.visit_date <= end_datetime + ) + + if patient_id_filter or patient_name_filter: + query = query.join(Patient) + if patient_id_filter: + query = query.where(Patient.patient_id.ilike(f"%{patient_id_filter}%")) + if patient_name_filter: + query = query.where(Patient.full_name.ilike(f"%{patient_name_filter}%")) + + if user_filter != "all": + query = query.where(PatientVisit.created_by == int(user_filter)) + + visits = session.exec(query.order_by(PatientVisit.visit_date.desc())).all() + + records = [] + total_remain = 0.0 + row_num = 0 + + for v in visits: + remain = round(float(v.remaining_amount), 0) if v.remaining_amount else 0.0 + + # Skip visits with no actual remaining balance (accounts for float rounding) + if remain <= 0: + continue + + row_num += 1 + + # Calculate total amount from the orders linked to this visit + visit_total = sum(o.final_price for o in v.orders) if v.orders else 0.0 + + paid = float(v.received_amount) if v.received_amount else 0.0 + discount = float(v.discount_amount) if v.discount_amount else 0.0 + + user_name = user_dict.get(v.created_by, "Unknown") + + records.append({ + "no": row_num, + "patient_code": v.patient.patient_id if v.patient else "-", + "patient_name": v.patient.full_name if v.patient else "-", + "visit_date": v.visit_date.strftime("%d-%m-%Y %H:%M"), + "total_amount": visit_total, + "paid": paid, + "discount_amount": discount, + "remain_amount": remain, + "username": user_name + }) + total_remain += remain + + return templates.TemplateResponse("remain_report.html", { + "request": request, + "start_date": start_date_str, + "start_time": start_time_str, + "end_date": end_date_str, + "end_time": end_time_str, + "user_filter": user_filter, + "patient_id_filter": patient_id_filter, + "patient_name_filter": patient_name_filter, + "users": users, + "records": records, + "total_remain": total_remain + }) + + +# =========================== +# PATIENT REGION REPORT +# =========================== +@router.get("/reports/patient-region", response_class=HTMLResponse) +def patient_region_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "patient_region"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + start_date_str = request.query_params.get("start_date") + end_date_str = request.query_params.get("end_date") + + region_filter = request.query_params.get("region_id", "all") + + if not start_date_str: + start_date_str = datetime.now().strftime("%Y-%m-%d") + if not end_date_str: + end_date_str = start_date_str + + try: + start_datetime = datetime.strptime(start_date_str, "%Y-%m-%d").replace(hour=0, minute=0, second=0, microsecond=0) + end_datetime = datetime.strptime(end_date_str, "%Y-%m-%d").replace(hour=23, minute=59, second=59, microsecond=999999) + except ValueError: + return RedirectResponse(url="/reports/patient-region?error=Invalid date format", status_code=status.HTTP_303_SEE_OTHER) + + from models import Patient, Region + + # Fetch all active regions for dropdown + regions_list = session.exec(select(Region).where(Region.is_active == True)).all() + + query = select(Patient).where(Patient.created_at >= start_datetime, Patient.created_at <= end_datetime) + + if region_filter != "all": + query = query.where(Patient.region_id == int(region_filter)) + + patients = session.exec(query).all() + + # Group by date and region name + from collections import defaultdict + daily_data = defaultdict(int) + + # Pre-fetch region names for quick lookup + region_dict = {r.id: r.region_name for r in regions_list} + + for p in patients: + d_str = p.created_at.strftime("%d-%m-%Y") + r_name = region_dict.get(p.region_id, "Unknown Region") if p.region_id else "No Region" + daily_data[(d_str, r_name)] += 1 + + rows = [] + total_patients = 0 + + all_keys = sorted(list(daily_data.keys()), key=lambda x: (datetime.strptime(x[0], "%d-%m-%Y"), x[1])) + + for k in all_keys: + d_str, r_name = k + p_count = daily_data[k] + if p_count > 0: + rows.append({ + "date": d_str, + "region_name": r_name, + "patient_count": p_count + }) + total_patients += p_count + + return templates.TemplateResponse("patient_region_report.html", { + "request": request, + "start_date": start_date_str, + "end_date": end_date_str, + "region_filter": region_filter, + "regions": regions_list, + "rows": rows, + "total_patients": total_patients + }) diff --git a/routes/results.py b/routes/results.py new file mode 100644 index 0000000000000000000000000000000000000000..770c499e85f7c1271f30e8280c2a18eb3abf7efb --- /dev/null +++ b/routes/results.py @@ -0,0 +1,890 @@ +# routes/results.py +# Result Entry routes — page render, data API, and save API. + +from fastapi import APIRouter, Depends, Request, Form +from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse +from sqlmodel import Session, select +from sqlalchemy.orm import selectinload +from datetime import datetime, timedelta +import json + +from database import get_session +from models import ( + Patient, PatientVisit, Order, TestDefinition, TestParameter, + TestDevice, TestRange, TestResultType, Result, ResultDetail, + Parameter, Device, SampleType, Formula +) +# ✅ NEW: Imported log_audit_action and require_permission +from routes.helpers import templates, get_current_user, log_audit_action, log_activity_action, require_permission, age_to_days + +router = APIRouter() + + +# =========================== +# RESULT ENTRY PATIENT LIST +# =========================== +PAGE_SIZE = 50 # Patients per page for result entry + +@router.get("/result-entry", response_class=HTMLResponse) +def result_entry_patients_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "result_entry"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=303) + today_str = datetime.today().strftime("%Y-%m-%d") + start_date = request.query_params.get("start_date", today_str) + end_date = request.query_params.get("end_date", today_str) + name = request.query_params.get("name", "") + patient_id_q = request.query_params.get("patient_id", "") + test_q = request.query_params.get("test", "") + status_q = request.query_params.get("status", "all") + + # Pagination + try: + page = max(1, int(request.query_params.get("page", 1))) + except (ValueError, TypeError): + page = 1 + + # ✅ OPTIMIZED: Single visit-based query with eager loading (eliminates N+1) + visit_query = ( + select(PatientVisit) + .options( + selectinload(PatientVisit.patient), + selectinload(PatientVisit.orders).selectinload(Order.test) + ) + .join(Patient, PatientVisit.patient_id == Patient.id) + .where(Patient.is_active == True) + ) + + if start_date: + visit_query = visit_query.where(PatientVisit.visit_date >= datetime.strptime(f"{start_date} 00:00:00", "%Y-%m-%d %H:%M:%S")) + if end_date: + visit_query = visit_query.where(PatientVisit.visit_date <= datetime.strptime(f"{end_date} 23:59:59", "%Y-%m-%d %H:%M:%S")) + if name: + visit_query = visit_query.where(Patient.full_name.ilike(f"%{name}%")) + if patient_id_q: + visit_query = visit_query.where(Patient.patient_id.ilike(f"%{patient_id_q}%")) + + if test_q or status_q != "all": + visit_query = visit_query.join(Order, Order.visit_id == PatientVisit.id).join(TestDefinition, Order.test_id == TestDefinition.id) + if test_q: + visit_query = visit_query.where( + (TestDefinition.test_name.ilike(f"%{test_q}%")) | + (TestDefinition.test_short_name.ilike(f"%{test_q}%")) + ) + if status_q == "pending": + visit_query = visit_query.where(Order.status == "ordered") + elif status_q == "received": + visit_query = visit_query.where(Order.status == "resulted") + elif status_q == "authorize": + visit_query = visit_query.where(Order.status.in_(["authorized", "double_authorized"])) + + # Fetch all matching visits ordered by date + visits = session.exec(visit_query.distinct().order_by(PatientVisit.visit_date.desc())).all() + + # Pagination on all visits (each visit is a separate row) + total_count = len(visits) + total_pages = max(1, (total_count + PAGE_SIZE - 1) // PAGE_SIZE) + page = min(page, total_pages) + offset = (page - 1) * PAGE_SIZE + page_visits = visits[offset:offset + PAGE_SIZE] + + # Build patient_data from the page slice (no extra queries needed) + patient_data = [] + for visit in page_visits: + patient = visit.patient + if not patient: + continue + + packages = {} + standalones = [] + + for order in visit.orders: + if not order.test or order.status == "no_sample": + continue + + # Explicitly hide tests that don't match the active toggle + if status_q == "pending" and order.status != "ordered": + continue + elif status_q == "received" and order.status != "resulted": + continue + elif status_q == "authorize" and order.status not in ["authorized", "double_authorized"]: + continue + + status_color = "red" + if order.status == "resulted": + status_color = "blue" + elif order.status in ["authorized", "double_authorized"]: + status_color = "green" + + test_info = { + "name": order.test.test_name, + "color": status_color} + + if order.package_name: + if order.package_name not in packages: + packages[order.package_name] = [] + packages[order.package_name].append(test_info) + else: + standalones.append(test_info) + + tests_data = [] + for pkg_name, pkg_tests in packages.items(): + tests_data.append({ + "is_package": True, + "package_name": pkg_name, + "tests": pkg_tests + }) + for t in standalones: + tests_data.append({ + "is_package": False, + "test": t + }) + + patient_data.append({ + "patient": patient, + "visit": visit, + "registration_date": visit.visit_date, + "tests": tests_data + }) + + return templates.TemplateResponse("result_entry_patients.html", { + "request": request, + "patient_data": patient_data, + "filters": { + "start_date": start_date, + "end_date": end_date, + "name": name, + "patient_id": patient_id_q, + "test": test_q, + "status": status_q, + }, + "page": page, + "total_pages": total_pages, + "total_count": total_count, + }) + +# =========================== +# RESULT ENTRY PAGE +# =========================== +@router.get("/result-entry/{patient_id}", response_class=HTMLResponse) +def result_entry_page(patient_id: str, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "result_entry"): + return RedirectResponse(url="/result-entry?error=Permission Denied", status_code=303) + current_user = get_current_user(request, session) + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + return RedirectResponse(url="/patients?error=Patient not found", status_code=303) + + # Support visit_id query param to select a specific visit + visit_id_param = request.query_params.get("visit_id") + if visit_id_param: + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.visit_id == visit_id_param, PatientVisit.patient_id == patient.id) + ).first() + else: + # Fallback: get latest visit + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.id.desc()) + ).first() + + visit_user_name = None + if visit and visit.created_by: + from models import User + user = session.get(User, visit.created_by) + if user: + visit_user_name = user.full_name or user.username + + # Fetch all visits for the "Previous Results" bar + all_visits = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.visit_date.asc()) + ).all() + + return templates.TemplateResponse("result_entry.html", { + "request": request, + "patient": patient, + "visit": visit, + "visit_user_name": visit_user_name, + "all_visits": all_visits, + }) + + +# =========================== +# RESULT ENTRY DATA API (JSON) +# =========================== +@router.get("/api/result-entry-data/{patient_id}") +def result_entry_data(patient_id: str, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "result_entry"): + return JSONResponse({"error": "Permission Denied"}, status_code=403) + try: + patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first() + if not patient: + return JSONResponse({"error": "Patient not found"}, status_code=404) + + # Support visit_id query param to select a specific visit + visit_id_param = request.query_params.get("visit_id") + if visit_id_param: + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.visit_id == visit_id_param, PatientVisit.patient_id == patient.id) + ).first() + else: + # Fallback: get latest visit + visit = session.exec( + select(PatientVisit) + .where(PatientVisit.patient_id == patient.id) + .order_by(PatientVisit.id.desc()) + ).first() + if not visit: + return JSONResponse({"error": "No visit found"}, status_code=404) + + # Get all orders for this visit with eager loading + orders = session.exec( + select(Order) + .options( + selectinload(Order.test).selectinload(TestDefinition.test_parameters).selectinload(TestParameter.parameter), + selectinload(Order.test).selectinload(TestDefinition.test_devices).selectinload(TestDevice.device), + selectinload(Order.result).selectinload(Result.details), + ) + .where(Order.visit_id == visit.id) + .order_by(Order.id) + ).all() + + # Load all ranges and result types in bulk + test_ids = list(set(o.test_id for o in orders)) + + all_ranges = session.exec( + select(TestRange).where(TestRange.test_id.in_(test_ids), TestRange.is_active == True) + ).all() + + all_result_types = session.exec( + select(TestResultType).where(TestResultType.test_id.in_(test_ids), TestResultType.is_active == True) + ).all() + + # Build range lookup: (test_id, param_id, device_id) -> range data + ranges_map = {} + for r in all_ranges: + key = (r.test_id, r.parameter_id, r.device_id) + if key not in ranges_map: + ranges_map[key] = [] + ranges_map[key].append({ + "id": r.id, + "unit": r.unit or "", + "gender_type": r.gender_type, + "age_from": r.age_from, + "age_from_unit": r.age_from_unit, + "age_to": r.age_to, + "age_to_unit": r.age_to_unit, + "age_unit": r.age_unit, + "range_type": r.range_type, + "normal_from": r.normal_from, + "normal_to": r.normal_to, + "low_from": r.low_from, + "low_to": r.low_to, + "high_from": r.high_from, + "high_to": r.high_to, + "vlow_from": r.vlow_from, + "vlow_to": r.vlow_to, + "vhigh_from": r.vhigh_from, + "vhigh_to": r.vhigh_to, + "panic_less_than": r.panic_less_than, + "panic_more_than": r.panic_more_than, + "text_range": r.text_range, + }) + + # Build result type lookup: (test_id, param_id) -> result_type info + result_type_map = {} + for rt in all_result_types: + key = (rt.test_id, rt.parameter_id) + result_type_map[key] = { + "result_type": rt.result_type, + "selection_options": rt.selection_options, + } + + # Fetch active Formulas for these tests + all_formulas = session.exec( + select(Formula).where(Formula.main_test_id.in_(test_ids), Formula.is_active == True) + ).all() + + # Build formula lookup: (test_id, param_id) -> formula expression + formulas_map = {} + for f in all_formulas: + key = (f.main_test_id, f.main_parameter_id) + formulas_map[key] = f.formula_expression + + # Build existing result details lookup: result_id -> {param_id: detail} + def build_details_map(result): + if not result or not result.details: + return {} + return {d.parameter_id: { + "id": d.id, + "result_value": d.result_value, + "rerun_result": d.rerun_result, + "flag": d.flag, + "device_id": d.device_id, + "remark": d.remark, + } for d in result.details} + + if not visit: + return [] + + grid_rows = [] + + # Exclude no_sample orders + active_orders = [o for o in orders if o.status != "no_sample"] + + for order in active_orders: + test = order.test + if not test: + continue + + # Get devices linked to this test + devices = [] + primary_device_id = None + for td in (test.test_devices or []): + if td.device: + devices.append({"id": td.device.id, "name": td.device.device_name}) + if primary_device_id is None: + primary_device_id = td.device.id + + # Get parameters for this test + params = [] + for tp in (test.test_parameters or []): + if tp.parameter: + params.append({ + "id": tp.parameter.id, + "name": tp.parameter.parameter_name, + "short_name": tp.parameter.parameter_short_name, + "is_header": tp.parameter.is_header, + }) + + existing_result = order.result + details_map = build_details_map(existing_result) + + has_params = len(params) > 0 + + def find_range(test_id, param_id, device_id): + """Find best matching range for patient gender/age.""" + candidates = [] + # Try exact match first (test_id, param_id, device_id) + for key in [(test_id, param_id, device_id), (test_id, param_id, None), (test_id, None, device_id), (test_id, None, None)]: + if key in ranges_map: + candidates.extend(ranges_map[key]) + + if not candidates: + return None + + # Filter by gender and age + best = None + patient_days = age_to_days(patient.age, patient.age_unit) + for c in candidates: + gender_ok = c["gender_type"] == "both" or c["gender_type"] == patient.gender + range_from_days = age_to_days(c["age_from"], c.get("age_from_unit", "year")) + range_to_days = age_to_days(c["age_to"], c.get("age_to_unit", "year")) + age_ok = range_from_days <= patient_days <= range_to_days + if gender_ok and age_ok: + best = c + break + return best if best else candidates[0] + + def get_result_type(test_id, param_id): + for key in [(test_id, param_id), (test_id, None)]: + if key in result_type_map: + return result_type_map[key] + return {"result_type": "number", "selection_options": None} + + if has_params: + # Parent row (read-only, no input) + parent_dev_id = existing_result.device_id if existing_result else None + grid_rows.append({ + "type": "parent", + "order_id": order.id, + "order_number": order.order_number, + "test_id": test.id, + "test_name": test.test_name, + "devices": devices, + "selected_device_id": parent_dev_id, + "result_id": existing_result.id if existing_result else None, + "authorized": existing_result.authorized if existing_result else False, + "double_authorized": existing_result.double_authorized if existing_result else False, + "unauth_reason": existing_result.unauth_reason if existing_result else "", + "status": order.status, + "note": existing_result.note if existing_result else "", + }) + # Child rows (one per parameter) + for p in params: + detail = details_map.get(p["id"], {}) + dev_id = parent_dev_id + rng = find_range(test.id, p["id"], dev_id) + rt = get_result_type(test.id, p["id"]) + grid_rows.append({ + "type": "child", + "order_id": order.id, + "test_id": test.id, + "test_name": test.test_name, + "parameter_id": p["id"], + "parameter_name": p["name"], + "parameter_short_name": p["short_name"], + "is_header": p["is_header"], + "devices": devices, + "selected_device_id": dev_id, + "range": rng, + "result_type": rt["result_type"], + "selection_options": rt["selection_options"], + "formula_expression": formulas_map.get((test.id, p["id"]), ""), + "result_value": detail.get("result_value", ""), + "rerun_result": detail.get("rerun_result", ""), + "flag": detail.get("flag", ""), + "remark": detail.get("remark", ""), + "detail_id": detail.get("id"), + "authorized": existing_result.authorized if existing_result else False, + "double_authorized": existing_result.double_authorized if existing_result else False, + "unauth_reason": existing_result.unauth_reason if existing_result else "", + }) + else: + # Standalone test (no sub-parameters) + dev_id = existing_result.device_id if existing_result else None + rng = find_range(test.id, None, dev_id) + rt = get_result_type(test.id, None) + grid_rows.append({ + "type": "standalone", + "order_id": order.id, + "order_number": order.order_number, + "test_id": test.id, + "test_name": test.test_name, + "devices": devices, + "selected_device_id": dev_id, + "range": rng, + "result_type": rt["result_type"], + "selection_options": rt["selection_options"], + "formula_expression": formulas_map.get((test.id, None), ""), + "result_id": existing_result.id if existing_result else None, + "result_value": existing_result.result_value if existing_result else "", + "rerun_result": existing_result.rerun_result if existing_result else "", + "flag": existing_result.flag if existing_result else "", + "note": existing_result.note if existing_result else "", + "authorized": existing_result.authorized if existing_result else False, + "double_authorized": existing_result.double_authorized if existing_result else False, + "unauth_reason": existing_result.unauth_reason if existing_result else "", + "status": order.status, + }) + + # Also provide the full ranges_map as flat list for client-side device-change lookups + all_ranges_flat = [] + for r in all_ranges: + all_ranges_flat.append({ + "test_id": r.test_id, + "parameter_id": r.parameter_id, + "device_id": r.device_id, + "unit": r.unit or "", + "gender_type": r.gender_type, + "age_from": r.age_from, + "age_from_unit": r.age_from_unit, + "age_to": r.age_to, + "age_to_unit": r.age_to_unit, + "age_unit": r.age_unit, + "range_type": r.range_type, + "normal_from": r.normal_from, + "normal_to": r.normal_to, + "low_from": r.low_from, + "low_to": r.low_to, + "high_from": r.high_from, + "high_to": r.high_to, + "vlow_from": r.vlow_from, + "vlow_to": r.vlow_to, + "vhigh_from": r.vhigh_from, + "vhigh_to": r.vhigh_to, + "panic_less_than": r.panic_less_than, + "panic_more_than": r.panic_more_than, + "text_range": r.text_range, + }) + + return { + "success": True, + "patient": { + "id": patient.id, + "patient_id": patient.patient_id, + "full_name": patient.full_name, + "gender": patient.gender, + "age": patient.age, + "age_unit": patient.age_unit, + }, + "visit_id": visit.visit_id if visit else None, + "grid_rows": grid_rows, + "all_ranges": all_ranges_flat, + } + + except Exception as e: + import traceback + traceback.print_exc() + return JSONResponse({"error": str(e)}, status_code=500) + + +# =========================== +# SAVE RESULTS API +# =========================== +@router.post("/api/result-entry/save") +async def save_results(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "result_entry", "save"): + return JSONResponse({"error": "Permission Denied"}, status_code=403) + try: + current_user = get_current_user(request, session) + body = await request.json() + rows = body.get("rows", []) + now = datetime.now() + user_id = current_user.id if current_user else 1 + + for row in rows: + order_id = row.get("order_id") + if not order_id: + continue + has_any_value = False + order = session.get(Order, order_id) + if not order: + continue + + # ✅ Guard: Never regress a finalized (double_authorized) order + if order.status == "double_authorized": + continue + + row_type = row.get("type") + authorized = row.get("authorized", False) + + if row_type == "standalone": + # Upsert Result for standalone test + result = session.exec( + select(Result).where(Result.order_id == order_id) + ).first() + if not result: + result = Result( + order_id=order_id, + entered_by=user_id, + entered_at=now, + ) + session.add(result) + + result.result_value = row.get("result_value", "") + result.rerun_result = row.get("rerun_result", "") + result.flag = row.get("flag", "") + result.note = row.get("remark", "") + result.device_id = row.get("device_id") + # Enforce status machine: ordered -> resulted -> authorized + # Allow authorization when result + auth are submitted together (order still "ordered") + can_authorize = authorized and order.status in ("ordered", "resulted", "authorized") + result.authorized = can_authorize + if can_authorize: + result.authorized_by = user_id + result.authorized_at = now + else: + result.authorized_by = None + result.authorized_at = None + + # Update order status + if result.result_value: + order.status = "authorized" if can_authorize else "resulted" + else: + order.status = "ordered" + + session.add(result) + session.add(order) + + elif row_type == "parent": + # Upsert Result for parent (container for details) + result = session.exec( + select(Result).where(Result.order_id == order_id) + ).first() + if not result: + result = Result( + order_id=order_id, + result_value="", + rerun_result="", + flag="", + note="", + entered_by=user_id, + entered_at=now, + ) + session.add(result) + session.flush() # Need result.id for details + + if "device_id" in row: + result.device_id = row.get("device_id") + + if "note" in row: + result.note = row.get("note") + + # Process child parameter details + children = row.get("children", []) + has_any_value = False + for child in children: + param_id = child.get("parameter_id") + if not param_id: + continue + + detail = session.exec( + select(ResultDetail).where( + ResultDetail.result_id == result.id, + ResultDetail.parameter_id == param_id + ) + ).first() + if not detail: + detail = ResultDetail( + result_id=result.id, + parameter_id=param_id, + ) + session.add(detail) + + detail.result_value = child.get("result_value", "") + detail.rerun_result = child.get("rerun_result", "") + detail.flag = child.get("flag", "") + detail.device_id = child.get("device_id") + detail.remark = child.get("remark", "") + session.add(detail) + + if detail.result_value: + has_any_value = True + + # Enforce status machine: ordered -> resulted -> authorized + # Allow authorization when result + auth are submitted together (order still "ordered") + can_authorize = authorized and order.status in ("ordered", "resulted", "authorized") + result.authorized = can_authorize + if can_authorize: + result.authorized_by = user_id + result.authorized_at = now + else: + result.authorized_by = None + result.authorized_at = None + + if has_any_value: + order.status = "authorized" if can_authorize else "resulted" + else: + order.status = "ordered" + + session.add(result) + session.add(order) + + # --------------------------------------------------------- + # ✅ NEW: INJECT AUDIT LOG HERE (Tracking Result Saves/Auths) + # --------------------------------------------------------- + log_detail = { + "status": order.status, + "test_name": order.test.test_name if order.test else "Unknown" + } + if row.get("result_value") or has_any_value: + log_detail["action"] = "Results Updated" + if authorized: + log_detail["action"] = "Test Authorized" + + log_audit_action( + session=session, + table_name="order", + record_id=order.id, + action="UPDATE", + current_user=current_user, + new_values=log_detail + ) + # --------------------------------------------------------- + + session.commit() + + # Activity Log: Result save + test_names = [] + auth_count = 0 + for row in rows: + oid = row.get("order_id") + if oid: + o = session.get(Order, oid) + if o and o.test: + test_names.append(o.test.test_name) + if row.get("authorized"): + auth_count += 1 + desc = f"Saved results for {len(rows)} test(s)" + if auth_count: + desc += f" ({auth_count} authorized)" + log_activity_action(session, "SAVE_RESULTS", desc, current_user, "patient") + session.commit() + + return {"success": True, "message": "Results saved successfully!"} + + except Exception as e: + session.rollback() + import traceback + traceback.print_exc() + return JSONResponse({"error": str(e)}, status_code=500) + + +# =========================== +# GET RANGE FOR DEVICE CHANGE (Real-time) +# =========================== +@router.get("/api/range-for-device") +def get_range_for_device( + test_id: int, device_id: int, + request: Request, + parameter_id: int = None, + gender: str = "both", age: int = 0, age_unit: str = "year", + session: Session = Depends(get_session) +): + if not require_permission(request, session, "result_entry"): + return JSONResponse({"error": "Permission Denied"}, status_code=403) + """Return the best matching range when user changes device.""" + query = select(TestRange).where( + TestRange.test_id == test_id, + TestRange.is_active == True, + ) + if parameter_id: + query = query.where(TestRange.parameter_id == parameter_id) + + # Try device-specific first, then fallback + ranges = session.exec(query.where(TestRange.device_id == device_id)).all() + if not ranges: + ranges = session.exec(query.where(TestRange.device_id == None)).all() + + best = None + patient_days = age_to_days(age, age_unit) + for r in ranges: + gender_ok = r.gender_type == "both" or r.gender_type == gender + range_from_days = age_to_days(r.age_from, r.age_from_unit or "year") + range_to_days = age_to_days(r.age_to, r.age_to_unit or "year") + age_ok = range_from_days <= patient_days <= range_to_days + if gender_ok and age_ok: + best = r + break + if not best and ranges: + best = ranges[0] + + if best: + return { + "unit": best.unit or "", + "range_type": best.range_type, + "normal_from": best.normal_from, + "normal_to": best.normal_to, + "low_from": best.low_from, + "low_to": best.low_to, + "high_from": best.high_from, + "high_to": best.high_to, + "text_range": best.text_range, + } + return {"unit": "", "range_type": "number", "normal_from": None, "normal_to": None} + +# =========================== +# NO SAMPLE ACTIONS & PAGE +# =========================== +@router.post("/api/result-entry/no-sample/{order_id}") +async def mark_no_sample(order_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "result_entry", "no_sample"): + return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403) + current_user = get_current_user(request, session) + if not current_user: + return JSONResponse({"success": False, "message": "Unauthorized"}, status_code=401) + + try: + data = await request.json() + reason = data.get("reason", "") + + order = session.get(Order, order_id) + if not order: + return JSONResponse({"success": False, "message": "Order not found"}, status_code=404) + + order.status = "no_sample" + order.no_sample_reason = reason + session.add(order) + + # --------------------------------------------------------- + # ✅ NEW: INJECT AUDIT LOG HERE (Tracking No Sample) + # --------------------------------------------------------- + log_audit_action( + session=session, + table_name="order", + record_id=order.id, + action="UPDATE", + current_user=current_user, + new_values={ + "action": "Marked as No Sample", + "test_name": order.test.test_name if order.test else "Unknown", + "reason": reason + } + ) + # --------------------------------------------------------- + + session.commit() + return {"success": True, "message": "Test moved to No Sample"} + except Exception as e: + session.rollback() + return JSONResponse({"success": False, "message": str(e)}, status_code=500) + +@router.post("/api/no-sample/receive/{order_id}") +def receive_no_sample(order_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "no_sample", "receive_sample"): + return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403) + current_user = get_current_user(request, session) + if not current_user: + return JSONResponse({"success": False, "message": "Unauthorized"}, status_code=401) + + try: + order = session.get(Order, order_id) + if not order: + return JSONResponse({"success": False, "message": "Order not found"}, status_code=404) + + # Reset order status + order.status = "ordered" + order.no_sample_reason = None # Good practice to clear the reason too + + # Look for any existing result attached to this order + existing_result = session.exec(select(Result).where(Result.order_id == order_id)).first() + + if existing_result: + # 1. Delete all child details (parameters) + if existing_result.details: + for detail in existing_result.details: + session.delete(detail) + + # 2. Delete the parent result record entirely + session.delete(existing_result) + + session.add(order) + + # --------------------------------------------------------- + # ✅ NEW: INJECT AUDIT LOG HERE (Tracking Receiving Sample back) + # --------------------------------------------------------- + log_audit_action( + session=session, + table_name="order", + record_id=order.id, + action="UPDATE", + current_user=current_user, + new_values={ + "action": "Sample Received from No Sample list", + "test_name": order.test.test_name if order.test else "Unknown", + "status": "ordered" + } + ) + # --------------------------------------------------------- + + session.commit() + return {"success": True, "message": "Sample Received successfully. Test returned to pending clean."} + except Exception as e: + session.rollback() + return JSONResponse({"success": False, "message": str(e)}, status_code=500) + +@router.get("/no-sample", response_class=HTMLResponse) +def no_sample_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "no_sample"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=303) + + cutoff_date = datetime.now() - timedelta(days=15) + query = select(Order).options( + selectinload(Order.patient), + selectinload(Order.test), + selectinload(Order.visit) + ).where( + Order.status == "no_sample", + Order.order_date >= cutoff_date + ).order_by(Order.order_date.desc()) + no_sample_orders = session.exec(query).all() + + return templates.TemplateResponse("no_sample.html", { + "request": request, + "orders": no_sample_orders + }) \ No newline at end of file diff --git a/routes/supplies.py b/routes/supplies.py new file mode 100644 index 0000000000000000000000000000000000000000..66c1503f0931f70f98b3236feb7bea2635dc191b --- /dev/null +++ b/routes/supplies.py @@ -0,0 +1,102 @@ +# routes/supplies.py +from fastapi import APIRouter, Depends, Request, Form, status +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlmodel import Session, select +from datetime import datetime +from typing import Optional +from database import get_session +from models import Supply +from routes.helpers import templates, get_current_user, create_audit_log, model_to_dict, require_permission + +router = APIRouter() + +@router.get("/supplies", response_class=HTMLResponse) +def supplies_page(request: Request, session: Session = Depends(get_session), search: Optional[str] = None): + if not require_permission(request, session, "supplies"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + + query = select(Supply).where(Supply.is_active == True) + if search: + query = query.where(Supply.name.ilike(f"%{search}%")) + + supplies = session.exec(query.order_by(Supply.id.asc())).all() + supplies_dict = [model_to_dict(s) for s in supplies] + + success = request.query_params.get("success") + error = request.query_params.get("error") + + return templates.TemplateResponse("supplies.html", { + "request": request, + "supplies": supplies, + "supplies_json": supplies_dict, + "search": search or "", + "message_success": success, + "message_error": error + }) + +@router.post("/supplies/create") +def create_supply(name: str = Form(...), note: Optional[str] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "supplies", "create"): + return RedirectResponse(url="/supplies?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + new_supply = Supply( + name=name, + note=note, + is_active=True, + created_by=current_user.id if current_user else None + ) + session.add(new_supply) + session.commit() + session.refresh(new_supply) + create_audit_log(session, "supply", new_supply.id, "create", current_user, new_values=model_to_dict(new_supply)) + return RedirectResponse(url="/supplies?success=Supply saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/supplies?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/supplies/update/{supply_id}") +def update_supply(supply_id: int, name: str = Form(...), note: Optional[str] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "supplies", "edit"): + return RedirectResponse(url="/supplies?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + supply = session.get(Supply, supply_id) + if supply: + old_values = model_to_dict(supply) + supply.name = name + supply.note = note + supply.edited_by = current_user.id if current_user else None + supply.edited_at = datetime.now() + session.add(supply) + session.commit() + session.refresh(supply) + create_audit_log(session, "supply", supply.id, "update", current_user, old_values=old_values, new_values=model_to_dict(supply)) + return RedirectResponse(url="/supplies?success=Supply updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/supplies?error=Supply not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/supplies?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/supplies/delete/{supply_id}") +def delete_supply(supply_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "supplies", "delete"): + return RedirectResponse(url="/supplies?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + supply = session.get(Supply, supply_id) + if supply: + # Soft delete or hard delete? Standard in this app seems to be hard delete for minor configs + # but let's stick to what departments.py does. + # departments.py uses session.delete(dept) which is a hard delete. + old_values = model_to_dict(supply) + create_audit_log(session, "supply", supply.id, "delete", current_user, old_values=old_values) + session.delete(supply) + session.commit() + return RedirectResponse(url="/supplies?success=Supply deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/supplies?error=Supply not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/supplies?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) diff --git a/routes/tests.py b/routes/tests.py new file mode 100644 index 0000000000000000000000000000000000000000..1ba1eff741d7f9e218a225c0636d752fdf4cde78 --- /dev/null +++ b/routes/tests.py @@ -0,0 +1,641 @@ +# routes/tests.py +# CRUD routes for: Test Definitions, Formulas, Test Ranges, Test Result Types, Packages. +# Includes N+1 fixes with selectinload. + +from fastapi import APIRouter, Depends, Request, Form, status +from fastapi.responses import HTMLResponse, RedirectResponse +from sqlmodel import Session, select +from sqlalchemy.orm import selectinload +from datetime import datetime +from typing import Optional +from database import get_session +from models import ( + TestDefinition, TestDevice, TestParameter, Department, SampleType, ReportNote, + Device, Parameter, Formula, FormulaItem, TestRange, TestResultType, + Package, PackageTest, +) +from routes.helpers import templates, get_current_user, create_audit_log, model_to_dict, require_permission + +router = APIRouter() + +# =========================== +# TEST DEFINITION ROUTES (N+1 FIX: selectinload) +# =========================== +@router.get("/tests", response_class=HTMLResponse) +def tests_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "tests"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + # ✅ N+1 FIX: eager-load test_devices and test_parameters in one query + tests = session.exec( + select(TestDefinition) + .options(selectinload(TestDefinition.test_devices), selectinload(TestDefinition.test_parameters)) + .order_by(TestDefinition.id.asc()) + ).all() + tests_json = [] + for test in tests: + test_dict = model_to_dict(test) + device_ids = [int(td.device_id) for td in test.test_devices] + parameter_ids = [int(tp.parameter_id) for tp in test.test_parameters] + test_dict['device_ids'] = device_ids + test_dict['parameter_ids'] = parameter_ids + tests_json.append(test_dict) + departments = session.exec(select(Department).where(Department.is_active == True)).all() + sample_types = session.exec(select(SampleType).where(SampleType.is_active == True)).all() + report_notes = session.exec(select(ReportNote).where(ReportNote.is_active == True)).all() + devices = session.exec(select(Device).where(Device.is_active == True)).all() + parameters = session.exec(select(Parameter)).all() + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("tests.html", { + "request": request, "tests": tests, "tests_json": tests_json, + "departments": departments, "sample_types": sample_types, "report_notes": report_notes, + "devices": devices, "parameters": parameters, + "message_success": success, "message_error": error + }) + +@router.post("/tests/create") +def create_test(test_name: str = Form(...), test_short_name: str = Form(...), + department_id: int = Form(...), sample_type_id: int = Form(...), + report_note_id: Optional[int] = Form(None), price: float = Form(...), + test_note: Optional[str] = Form(None), test_condition: Optional[str] = Form(None), + is_available: str = Form(None), print_separately: str = Form(None), + device_ids: Optional[str] = Form(""), + parameter_ids: Optional[str] = Form(""), request: Request = None, + session: Session = Depends(get_session)): + if not require_permission(request, session, "tests", "create"): + return RedirectResponse(url="/tests?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + is_available_bool = True if is_available == "on" else False + new_test = TestDefinition( + test_name=test_name, test_short_name=test_short_name.upper(), + department_id=department_id, sample_type_id=sample_type_id, + report_note_id=report_note_id if report_note_id and report_note_id != "" else None, + price=price, test_note=test_note, test_condition=test_condition, + is_available=is_available_bool, print_separately=(print_separately == "on"), + created_by=current_user.id if current_user else None + ) + session.add(new_test) + session.commit() + session.refresh(new_test) + if device_ids and device_ids.strip(): + device_id_list = [int(d.strip()) for d in device_ids.split(',') if d.strip().isdigit()] + for device_id in device_id_list: + link = TestDevice(test_id=new_test.id, device_id=device_id) + session.add(link) + if parameter_ids and parameter_ids.strip(): + parameter_id_list = [int(p.strip()) for p in parameter_ids.split(',') if p.strip().isdigit()] + for parameter_id in parameter_id_list: + link = TestParameter(test_id=new_test.id, parameter_id=parameter_id) + session.add(link) + session.commit() + create_audit_log(session, "testdefinition", new_test.id, "create", current_user, new_values=model_to_dict(new_test)) + return RedirectResponse(url="/tests?success=Test saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/tests?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/tests/update/{test_id}") +def update_test(test_id: int, test_name: str = Form(...), test_short_name: str = Form(...), + department_id: int = Form(...), sample_type_id: int = Form(...), + report_note_id: Optional[int] = Form(None), price: float = Form(...), + test_note: Optional[str] = Form(None), test_condition: Optional[str] = Form(None), + is_available: str = Form(None), print_separately: str = Form(None), + device_ids: Optional[str] = Form(""), + parameter_ids: Optional[str] = Form(""), request: Request = None, + session: Session = Depends(get_session)): + if not require_permission(request, session, "tests", "edit"): + return RedirectResponse(url="/tests?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + test = session.get(TestDefinition, test_id) + if test: + old_values = model_to_dict(test) + test.test_name = test_name + test.test_short_name = test_short_name.upper() + test.department_id = department_id + test.sample_type_id = sample_type_id + test.report_note_id = report_note_id if report_note_id and report_note_id != "" else None + test.price = price + test.test_note = test_note + test.test_condition = test_condition + test.is_available = True if is_available == "on" else False + test.print_separately = True if print_separately == "on" else False + test.edited_by = current_user.id if current_user else None + test.edited_at = datetime.now() + existing_device_links = session.exec(select(TestDevice).where(TestDevice.test_id == test_id)).all() + for link in existing_device_links: + session.delete(link) + if device_ids and device_ids.strip(): + device_id_list = [int(d.strip()) for d in device_ids.split(',') if d.strip().isdigit()] + for device_id in device_id_list: + link = TestDevice(test_id=test.id, device_id=device_id) + session.add(link) + existing_parameter_links = session.exec(select(TestParameter).where(TestParameter.test_id == test_id)).all() + for link in existing_parameter_links: + session.delete(link) + if parameter_ids and parameter_ids.strip(): + parameter_id_list = [int(p.strip()) for p in parameter_ids.split(',') if p.strip().isdigit()] + for parameter_id in parameter_id_list: + link = TestParameter(test_id=test.id, parameter_id=parameter_id) + session.add(link) + session.add(test) + session.commit() + session.refresh(test) + create_audit_log(session, "testdefinition", test.id, "update", current_user, old_values=old_values, new_values=model_to_dict(test)) + return RedirectResponse(url="/tests?success=Test updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/tests?error=Test not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/tests?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/tests/delete/{test_id}") +def delete_test(test_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "tests", "delete"): + return RedirectResponse(url="/tests?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + test = session.get(TestDefinition, test_id) + if test: + old_values = model_to_dict(test) + + # Check for existing orders referencing this test + from models import Order + order_count = session.exec( + select(Order).where(Order.test_id == test_id) + ).first() + + if order_count: + # Soft-delete: mark as unavailable to preserve order references + test.is_available = False + test.deleted_at = datetime.now() + test.deleted_by = current_user.id if current_user else None + session.add(test) + session.commit() + create_audit_log(session, "testdefinition", test.id, "soft_delete", current_user, old_values=old_values, new_values={"action": "Test deactivated (has existing orders)"}) + return RedirectResponse(url="/tests?success=Test deactivated (has existing patient orders, cannot hard-delete).", status_code=status.HTTP_303_SEE_OTHER) + else: + # Safe to hard-delete: no orders reference this test + existing_device_links = session.exec(select(TestDevice).where(TestDevice.test_id == test_id)).all() + for link in existing_device_links: + session.delete(link) + existing_parameter_links = session.exec(select(TestParameter).where(TestParameter.test_id == test_id)).all() + for link in existing_parameter_links: + session.delete(link) + session.delete(test) + session.commit() + create_audit_log(session, "testdefinition", test.id, "delete", current_user, old_values=old_values) + return RedirectResponse(url="/tests?success=Test deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/tests?error=Test not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/tests?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# FORMULA ROUTES +# =========================== +@router.get("/formulas", response_class=HTMLResponse) +def formulas_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "formulas"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + formulas = session.exec(select(Formula).order_by(Formula.id.asc())).all() + formulas_json = [model_to_dict(f) for f in formulas] + tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all() + parameters = session.exec(select(Parameter)).all() + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("formulas.html", { + "request": request, "formulas": formulas, "formulas_json": formulas_json, + "tests": tests, "parameters": parameters, + "message_success": success, "message_error": error + }) + +@router.post("/formulas/create") +def create_formula(formula_name: str = Form(...), main_test_id: int = Form(...), + main_parameter_id: Optional[int] = Form(None), gender_type: str = Form(...), + formula_expression: str = Form(""), formula_description: Optional[str] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "formulas", "create"): + return RedirectResponse(url="/formulas?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + new_formula = Formula( + formula_name=formula_name, main_test_id=main_test_id, + main_parameter_id=main_parameter_id if main_parameter_id else None, + gender_type=gender_type, formula_expression=formula_expression, + formula_description=formula_description, is_active=True, + created_by=current_user.id if current_user else None + ) + session.add(new_formula) + session.commit() + session.refresh(new_formula) + create_audit_log(session, "formula", new_formula.id, "create", current_user, new_values=model_to_dict(new_formula)) + return RedirectResponse(url="/formulas?success=Formula saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/formulas?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/formulas/update/{formula_id}") +def update_formula(formula_id: int, formula_name: str = Form(...), main_test_id: int = Form(...), + main_parameter_id: Optional[int] = Form(None), gender_type: str = Form(...), + formula_expression: str = Form(""), formula_description: Optional[str] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "formulas", "edit"): + return RedirectResponse(url="/formulas?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + formula = session.get(Formula, formula_id) + if formula: + old_values = model_to_dict(formula) + formula.formula_name = formula_name + formula.main_test_id = main_test_id + formula.main_parameter_id = main_parameter_id if main_parameter_id else None + formula.gender_type = gender_type + formula.formula_expression = formula_expression + formula.formula_description = formula_description + formula.edited_by = current_user.id if current_user else None + formula.edited_at = datetime.now() + session.add(formula) + session.commit() + session.refresh(formula) + create_audit_log(session, "formula", formula.id, "update", current_user, old_values=old_values, new_values=model_to_dict(formula)) + return RedirectResponse(url="/formulas?success=Formula updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/formulas?error=Formula not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/formulas?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/formulas/delete/{formula_id}") +def delete_formula(formula_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "formulas", "delete"): + return RedirectResponse(url="/formulas?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + formula = session.get(Formula, formula_id) + if formula: + old_values = model_to_dict(formula) + session.delete(formula) + session.commit() + create_audit_log(session, "formula", formula.id, "delete", current_user, old_values=old_values) + return RedirectResponse(url="/formulas?success=Formula deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/formulas?error=Formula not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/formulas?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# TEST RANGE ROUTES +# =========================== +@router.get("/test-ranges", response_class=HTMLResponse) +def test_ranges_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "test_ranges"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + ranges = session.exec(select(TestRange).order_by(TestRange.id.asc())).all() + ranges_json = [model_to_dict(r) for r in ranges] + tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all() + parameters = session.exec(select(Parameter)).all() + devices = session.exec(select(Device).where(Device.is_active == True)).all() + departments = session.exec(select(Department).where(Department.is_active == True)).all() + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("test_ranges.html", { + "request": request, "ranges": ranges, "ranges_json": ranges_json, + "tests": tests, "parameters": parameters, "devices": devices, "departments": departments, + "message_success": success, "message_error": error + }) + +@router.post("/test-ranges/create") +def create_test_range(test_id: int = Form(...), parameter_id: Optional[int] = Form(None), + device_id: Optional[int] = Form(None), unit: str = Form(...), + gender_type: str = Form(...), age_from: int = Form(...), + age_to: int = Form(...), age_from_unit: str = Form("year"), age_to_unit: str = Form("year"), + fasting_required: str = Form("false"), range_type: str = Form(...), + normal_from: Optional[float] = Form(None), normal_to: Optional[float] = Form(None), + vlow_from: Optional[float] = Form(None), vlow_to: Optional[float] = Form(None), + low_from: Optional[float] = Form(None), low_to: Optional[float] = Form(None), + midlow_from: Optional[float] = Form(None), midlow_to: Optional[float] = Form(None), + midhigh_from: Optional[float] = Form(None), midhigh_to: Optional[float] = Form(None), + high_from: Optional[float] = Form(None), high_to: Optional[float] = Form(None), + vhigh_from: Optional[float] = Form(None), vhigh_to: Optional[float] = Form(None), + panic_less_than: Optional[float] = Form(None), panic_more_than: Optional[float] = Form(None), + text_range: Optional[str] = Form(None), request: Request = None, + session: Session = Depends(get_session)): + if not require_permission(request, session, "test_ranges", "create"): + return RedirectResponse(url="/test-ranges?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + fasting_bool = fasting_required.lower() == "true" + new_range = TestRange( + test_id=test_id, parameter_id=parameter_id if parameter_id else None, + device_id=device_id if device_id else None, unit=unit, gender_type=gender_type, + age_from=age_from, age_to=age_to, age_from_unit=age_from_unit, age_to_unit=age_to_unit, age_unit=age_from_unit, fasting_required=fasting_bool, + range_type=range_type, normal_from=normal_from, normal_to=normal_to, + vlow_from=vlow_from, vlow_to=vlow_to, low_from=low_from, low_to=low_to, + midlow_from=midlow_from, midlow_to=midlow_to, midhigh_from=midhigh_from, + midhigh_to=midhigh_to, high_from=high_from, high_to=high_to, + vhigh_from=vhigh_from, vhigh_to=vhigh_to, panic_less_than=panic_less_than, + panic_more_than=panic_more_than, text_range=text_range if range_type == "text" else None, + is_active=True, created_by=current_user.id if current_user else None + ) + session.add(new_range) + session.commit() + session.refresh(new_range) + create_audit_log(session, "testrange", new_range.id, "create", current_user, new_values=model_to_dict(new_range)) + return RedirectResponse(url="/test-ranges?success=Test range saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/test-ranges?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/test-ranges/update/{range_id}") +def update_test_range(range_id: int, test_id: int = Form(...), parameter_id: Optional[int] = Form(None), + device_id: Optional[int] = Form(None), unit: str = Form(...), + gender_type: str = Form(...), age_from: int = Form(...), + age_to: int = Form(...), age_from_unit: str = Form("year"), age_to_unit: str = Form("year"), + fasting_required: str = Form("false"), range_type: str = Form(...), + normal_from: Optional[float] = Form(None), normal_to: Optional[float] = Form(None), + vlow_from: Optional[float] = Form(None), vlow_to: Optional[float] = Form(None), + low_from: Optional[float] = Form(None), low_to: Optional[float] = Form(None), + midlow_from: Optional[float] = Form(None), midlow_to: Optional[float] = Form(None), + midhigh_from: Optional[float] = Form(None), midhigh_to: Optional[float] = Form(None), + high_from: Optional[float] = Form(None), high_to: Optional[float] = Form(None), + vhigh_from: Optional[float] = Form(None), vhigh_to: Optional[float] = Form(None), + panic_less_than: Optional[float] = Form(None), panic_more_than: Optional[float] = Form(None), + text_range: Optional[str] = Form(None), request: Request = None, + session: Session = Depends(get_session)): + if not require_permission(request, session, "test_ranges", "edit"): + return RedirectResponse(url="/test-ranges?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + range_item = session.get(TestRange, range_id) + if range_item: + old_values = model_to_dict(range_item) + fasting_bool = fasting_required.lower() == "true" + range_item.test_id = test_id + range_item.parameter_id = parameter_id if parameter_id else None + range_item.device_id = device_id if device_id else None + range_item.unit = unit + range_item.gender_type = gender_type + range_item.age_from = age_from + range_item.age_to = age_to + range_item.age_from_unit = age_from_unit + range_item.age_to_unit = age_to_unit + range_item.age_unit = age_from_unit + range_item.fasting_required = fasting_bool + range_item.range_type = range_type + range_item.normal_from = normal_from + range_item.normal_to = normal_to + range_item.vlow_from = vlow_from + range_item.vlow_to = vlow_to + range_item.low_from = low_from + range_item.low_to = low_to + range_item.midlow_from = midlow_from + range_item.midlow_to = midlow_to + range_item.midhigh_from = midhigh_from + range_item.midhigh_to = midhigh_to + range_item.high_from = high_from + range_item.high_to = high_to + range_item.vhigh_from = vhigh_from + range_item.vhigh_to = vhigh_to + range_item.panic_less_than = panic_less_than + range_item.panic_more_than = panic_more_than + range_item.text_range = text_range if range_type == "text" else None + range_item.edited_by = current_user.id if current_user else None + range_item.edited_at = datetime.now() + session.add(range_item) + session.commit() + session.refresh(range_item) + create_audit_log(session, "testrange", range_item.id, "update", current_user, old_values=old_values, new_values=model_to_dict(range_item)) + return RedirectResponse(url="/test-ranges?success=Test range updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/test-ranges?error=Test range not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/test-ranges?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/test-ranges/delete/{range_id}") +def delete_test_range(range_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "test_ranges", "delete"): + return RedirectResponse(url="/test-ranges?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + range_item = session.get(TestRange, range_id) + if range_item: + old_values = model_to_dict(range_item) + session.delete(range_item) + session.commit() + create_audit_log(session, "testrange", range_item.id, "delete", current_user, old_values=old_values) + return RedirectResponse(url="/test-ranges?success=Test range deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/test-ranges?error=Test range not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/test-ranges?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# TEST RESULT TYPE ROUTES +# =========================== +@router.get("/test-result-types", response_class=HTMLResponse) +def test_result_types_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "test_result_types"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + result_types = session.exec(select(TestResultType).order_by(TestResultType.id.asc())).all() + result_types_json = [model_to_dict(rt) for rt in result_types] + # Eager-load test_parameters for building test→parameter mapping + tests = session.exec( + select(TestDefinition) + .where(TestDefinition.is_available == True) + .options(selectinload(TestDefinition.test_parameters)) + ).all() + # Build test→parameter_ids mapping for dynamic parameter filtering + import json + test_param_map = {} + for test in tests: + test_param_map[str(test.id)] = [tp.parameter_id for tp in test.test_parameters] + parameters = session.exec(select(Parameter)).all() + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("test_result_types.html", { + "request": request, "result_types": result_types, "result_types_json": result_types_json, + "tests": tests, "parameters": parameters, + "test_param_map_json": json.dumps(test_param_map), + "message_success": success, "message_error": error + }) + +@router.post("/test-result-types/create") +def create_test_result_type(test_id: int = Form(...), parameter_id: Optional[int] = Form(None), + result_type: str = Form(...), selection_options: Optional[str] = Form(None), + request: Request = None, session: Session = Depends(get_session)): + if not require_permission(request, session, "test_result_types", "create"): + return RedirectResponse(url="/test-result-types?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + new_result_type = TestResultType( + test_id=test_id, parameter_id=parameter_id if parameter_id else None, + result_type=result_type, selection_options=selection_options if result_type == "selection" else None, + is_active=True, created_by=current_user.id if current_user else None + ) + session.add(new_result_type) + session.commit() + session.refresh(new_result_type) + create_audit_log(session, "testresulttype", new_result_type.id, "create", current_user, new_values=model_to_dict(new_result_type)) + return RedirectResponse(url="/test-result-types?success=Result type saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/test-result-types?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/test-result-types/update/{result_type_id}") +def update_test_result_type(result_type_id: int, test_id: int = Form(...), + parameter_id: Optional[int] = Form(None), result_type: str = Form(...), + selection_options: Optional[str] = Form(None), request: Request = None, + session: Session = Depends(get_session)): + if not require_permission(request, session, "test_result_types", "edit"): + return RedirectResponse(url="/test-result-types?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + rt = session.get(TestResultType, result_type_id) + if rt: + old_values = model_to_dict(rt) + rt.test_id = test_id + rt.parameter_id = parameter_id if parameter_id else None + rt.result_type = result_type + rt.selection_options = selection_options if result_type == "selection" else None + rt.edited_by = current_user.id if current_user else None + rt.edited_at = datetime.now() + session.add(rt) + session.commit() + session.refresh(rt) + create_audit_log(session, "testresulttype", rt.id, "update", current_user, old_values=old_values, new_values=model_to_dict(rt)) + return RedirectResponse(url="/test-result-types?success=Result type updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/test-result-types?error=Result type not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/test-result-types?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/test-result-types/delete/{result_type_id}") +def delete_test_result_type(result_type_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "test_result_types", "delete"): + return RedirectResponse(url="/test-result-types?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + rt = session.get(TestResultType, result_type_id) + if rt: + old_values = model_to_dict(rt) + session.delete(rt) + session.commit() + create_audit_log(session, "testresulttype", rt.id, "delete", current_user, old_values=old_values) + return RedirectResponse(url="/test-result-types?success=Result type deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/test-result-types?error=Result type not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/test-result-types?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# PACKAGE ROUTES (N+1 FIX: selectinload) +# =========================== +@router.get("/packages", response_class=HTMLResponse) +def packages_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "packages"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + # ✅ N+1 FIX: eager-load package_tests in one query + packages = session.exec( + select(Package) + .options(selectinload(Package.package_tests)) + .order_by(Package.id.asc()) + ).all() + packages_json = [] + for pkg in packages: + pkg_dict = model_to_dict(pkg) + test_ids = [pt.test_id for pt in pkg.package_tests] + pkg_dict['test_ids'] = test_ids + packages_json.append(pkg_dict) + tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all() + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("packages.html", { + "request": request, "packages": packages, "packages_json": packages_json, + "tests": tests, "message_success": success, "message_error": error + }) + +@router.post("/packages/create") +def create_package(package_name: str = Form(...), package_short_name: str = Form(...), + price: float = Form(...), package_note: Optional[str] = Form(None), + test_ids: Optional[str] = Form(""), request: Request = None, + session: Session = Depends(get_session)): + if not require_permission(request, session, "packages", "create"): + return RedirectResponse(url="/packages?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + new_package = Package( + package_name=package_name, package_short_name=package_short_name.upper(), + price=price, package_note=package_note, is_active=True, + created_by=current_user.id if current_user else None + ) + session.add(new_package) + session.commit() + session.refresh(new_package) + if test_ids and test_ids.strip(): + test_id_list = [int(t.strip()) for t in test_ids.split(',') if t.strip().isdigit()] + for test_id in test_id_list: + link = PackageTest(package_id=new_package.id, test_id=test_id) + session.add(link) + session.commit() + create_audit_log(session, "package", new_package.id, "create", current_user, new_values=model_to_dict(new_package)) + return RedirectResponse(url="/packages?success=Package saved successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/packages?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/packages/update/{package_id}") +def update_package(package_id: int, package_name: str = Form(...), package_short_name: str = Form(...), + price: float = Form(...), package_note: Optional[str] = Form(None), + test_ids: Optional[str] = Form(""), request: Request = None, + session: Session = Depends(get_session)): + if not require_permission(request, session, "packages", "edit"): + return RedirectResponse(url="/packages?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + pkg = session.get(Package, package_id) + if pkg: + old_values = model_to_dict(pkg) + pkg.package_name = package_name + pkg.package_short_name = package_short_name.upper() + pkg.price = price + pkg.package_note = package_note + pkg.edited_by = current_user.id if current_user else None + pkg.edited_at = datetime.now() + existing_links = session.exec(select(PackageTest).where(PackageTest.package_id == package_id)).all() + for link in existing_links: + session.delete(link) + if test_ids and test_ids.strip(): + test_id_list = [int(t.strip()) for t in test_ids.split(',') if t.strip().isdigit()] + for test_id in test_id_list: + link = PackageTest(package_id=pkg.id, test_id=test_id) + session.add(link) + session.add(pkg) + session.commit() + session.refresh(pkg) + create_audit_log(session, "package", pkg.id, "update", current_user, old_values=old_values, new_values=model_to_dict(pkg)) + return RedirectResponse(url="/packages?success=Package updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/packages?error=Package not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/packages?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +@router.post("/packages/delete/{package_id}") +def delete_package(package_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "packages", "delete"): + return RedirectResponse(url="/packages?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + pkg = session.get(Package, package_id) + if pkg: + old_values = model_to_dict(pkg) + existing_links = session.exec(select(PackageTest).where(PackageTest.package_id == package_id)).all() + for link in existing_links: + session.delete(link) + session.delete(pkg) + session.commit() + create_audit_log(session, "package", pkg.id, "delete", current_user, old_values=old_values) + return RedirectResponse(url="/packages?success=Package deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + return RedirectResponse(url="/packages?error=Package not found", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/packages?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) diff --git a/routes/users.py b/routes/users.py new file mode 100644 index 0000000000000000000000000000000000000000..6d45a0182fae3559b2711f71046f70d0abcf3c47 --- /dev/null +++ b/routes/users.py @@ -0,0 +1,489 @@ +# routes/users.py +# User Management: CRUD + Granular Page/Button Permissions + +from fastapi import APIRouter, Depends, Request, Form, status +from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse +from sqlmodel import Session, select +from datetime import datetime +from typing import Optional +import json + +from database import get_session +from models import User, UserPermission +from routes.helpers import templates, get_current_user, create_audit_log, model_to_dict, require_permission, pwd_context + +router = APIRouter() + +# =========================== +# PAGES REGISTRY — All pages and their actual buttons (audited from templates) +# =========================== +PAGES_REGISTRY = { + # --- Main --- + "dashboard": {"label": "Dashboard", "group": "Main", "buttons": []}, + # --- Patient Management --- + "patient_registration": {"label": "Patient Registration", "group": "Patient Management", "buttons": [ + {"key": "save_registration", "label": "Save Registration"}, + {"key": "discount", "label": "Discount"}, + {"key": "print_barcode", "label": "Print Barcode"}, + {"key": "print_receipt", "label": "Print Receipt"}, + ]}, + "patients": {"label": "Patients", "group": "Patient Management", "buttons": [ + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + {"key": "print_barcode", "label": "Print Barcode"}, + {"key": "print_receipt", "label": "Print Receipt"}, + {"key": "result_entry", "label": "Result Entry"}, + ]}, + "patient_edit": {"label": "Patient Edit", "group": "Patient Management", "buttons": [ + {"key": "save", "label": "Save Changes"}, + {"key": "print_barcode", "label": "Print Barcode"}, + {"key": "print_receipt", "label": "Print Receipt"}, + {"key": "discount", "label": "Discount"}, + ]}, + "deleted_patients": {"label": "Deleted Patients", "group": "Patient Management", "buttons": [ + {"key": "restore", "label": "Restore"}, + {"key": "view", "label": "View"}, + ]}, + "deleted_tests": {"label": "Deleted Tests", "group": "Patient Management", "buttons": []}, + "patient_history": {"label": "Patient History", "group": "Patient Management", "buttons": []}, + "patient_status": {"label": "Patient Status", "group": "Patient Management", "buttons": []}, + # --- Results --- + "result_entry": {"label": "Result Entry", "group": "Results", "buttons": [ + {"key": "save", "label": "Save Result"}, + {"key": "authorize", "label": "Authorize"}, + {"key": "duplicate", "label": "Duplicate"}, + {"key": "rerun", "label": "ReRun"}, + {"key": "no_sample", "label": "No Sample"}, + ]}, + "double_auth": {"label": "Double Authorisation", "group": "Results", "buttons": [ + {"key": "double_authorize", "label": "Double Authorize"}, + {"key": "rerun", "label": "ReRun"}, + {"key": "unauthorize", "label": "UnAUTH"}, + ]}, + "no_sample": {"label": "No Sample", "group": "Results", "buttons": [ + {"key": "mark_no_sample", "label": "Mark No Sample"}, + {"key": "receive_sample", "label": "Receive Sample"}, + ]}, + # --- Printing & Design --- + "print_barcode": {"label": "Print Barcode", "group": "Printing & Design", "buttons": [ + {"key": "print", "label": "Print"}, + ]}, + "barcode_designer": {"label": "Barcode Designer", "group": "Printing & Design", "buttons": [ + {"key": "save", "label": "Save Design"}, + ]}, + "print_receipt": {"label": "Print Receipt", "group": "Printing & Design", "buttons": [ + {"key": "print", "label": "Print"}, + ]}, + "receipt_designer": {"label": "Receipt Designer", "group": "Printing & Design", "buttons": [ + {"key": "save", "label": "Save Design"}, + ]}, + "print_results": {"label": "Print Results", "group": "Printing & Design", "buttons": [ + {"key": "print", "label": "Print"}, + {"key": "view", "label": "View"}, + ]}, + "call_centre": {"label": "Call Centre", "group": "Printing & Design", "buttons": [ + {"key": "mark_called", "label": "Mark Called"}, + {"key": "send_whatsapp", "label": "Send WhatsApp"}, + ]}, + "result_designer": {"label": "Result Designer", "group": "Printing & Design", "buttons": [ + {"key": "save", "label": "Save Design"}, + ]}, + # --- Lab Setup --- + "departments": {"label": "Departments", "group": "Lab Setup", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + "sample_types": {"label": "Sample Types", "group": "Lab Setup", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + "devices": {"label": "Devices", "group": "Lab Setup", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + "parameters": {"label": "Parameters", "group": "Lab Setup", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + "report_notes": {"label": "Report Notes", "group": "Lab Setup", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + # --- Tests & Packages --- + "tests": {"label": "Tests", "group": "Tests & Packages", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + "formulas": {"label": "Formulas", "group": "Tests & Packages", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + "test_ranges": {"label": "Test Ranges", "group": "Tests & Packages", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + "test_result_types": {"label": "Result Types", "group": "Tests & Packages", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + "packages": {"label": "Packages", "group": "Tests & Packages", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + # --- Financials --- + "expenses_types": {"label": "Expenses Types", "group": "Financials", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + "expenses_entry": {"label": "Expenses Entry", "group": "Financials", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + # --- Reports --- + "discount_report": {"label": "Discount Report", "group": "Reports", "buttons": [ + {"key": "view", "label": "View Report"}, + ]}, + "detailed_income": {"label": "Detailed Income", "group": "Reports", "buttons": [ + {"key": "view", "label": "View Report"}, + ]}, + "net_amounts": {"label": "Net Amounts", "group": "Reports", "buttons": [ + {"key": "view", "label": "View Report"}, + ]}, + "payment_records": {"label": "Payment Records", "group": "Reports", "buttons": [ + {"key": "view", "label": "View Report"}, + ]}, + "patients_number": {"label": "Patients Number", "group": "Reports", "buttons": [ + {"key": "view", "label": "View Report"}, + ]}, + "tests_number": {"label": "Tests Number", "group": "Reports", "buttons": [ + {"key": "view", "label": "View Report"}, + ]}, + "expenses_report": {"label": "Expenses Report", "group": "Reports", "buttons": [ + {"key": "view", "label": "View Report"}, + {"key": "edit", "label": "Edit Expense"}, + {"key": "delete", "label": "Delete Expense"}, + ]}, + "remain_report": {"label": "Remain Report", "group": "Reports", "buttons": [ + {"key": "view", "label": "View Report"}, + ]}, + # --- Geography & Partners --- + "partners": {"label": "Partners", "group": "Geography & Partners", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + "provinces": {"label": "Provinces", "group": "Geography & Partners", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + "regions": {"label": "Regions", "group": "Geography & Partners", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + # --- Settings --- + "lab_info": {"label": "Lab Info", "group": "Settings", "buttons": [ + {"key": "edit", "label": "Edit"}, + {"key": "save", "label": "Save"}, + ]}, + "user_management": {"label": "User Management", "group": "Settings", "buttons": [ + {"key": "create", "label": "Create"}, + {"key": "edit", "label": "Edit"}, + {"key": "delete", "label": "Delete"}, + ]}, + "activity_logs": {"label": "Activity Logs", "group": "Settings", "buttons": [ + {"key": "view", "label": "View"}, + ]}, +} + + +# =========================== +# USERS PAGE +# =========================== +@router.get("/users", response_class=HTMLResponse) +def users_page(request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "user_management"): + return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + current_user = get_current_user(request, session) + users = session.exec(select(User).order_by(User.id.asc())).all() + success = request.query_params.get("success") + error = request.query_params.get("error") + return templates.TemplateResponse("users.html", { + "request": request, + "users": users, + "pages_registry": PAGES_REGISTRY, + "message_success": success, + "message_error": error, + "current_user": current_user + }) + +# =========================== +# CREATE USER +# =========================== +@router.post("/users/create") +def create_user( + full_name: str = Form(...), + username: str = Form(...), + password: str = Form(...), + role: str = Form("user"), + date_of_birth: Optional[str] = Form(None), + phone_number: Optional[str] = Form(None), + address: Optional[str] = Form(None), + permissions: Optional[str] = Form(None), + request: Request = None, + session: Session = Depends(get_session) +): + if not require_permission(request, session, "user_management", "create"): + return RedirectResponse(url="/users?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + + # Check duplicate username + existing = session.exec(select(User).where(User.username == username)).first() + if existing: + return RedirectResponse(url=f"/users?error=Username '{username}' already exists", status_code=status.HTTP_303_SEE_OTHER) + + # Parse DOB + dob = None + if date_of_birth and date_of_birth.strip(): + try: + dob = datetime.strptime(date_of_birth.strip(), "%d-%m-%Y") + except ValueError: + try: + dob = datetime.strptime(date_of_birth.strip(), "%Y-%m-%d") + except ValueError: + pass + + new_user = User( + full_name=full_name, + username=username, + hashed_password=pwd_context.hash(password), + role=role, + is_active=True, + date_of_birth=dob, + phone_number=phone_number if phone_number else None, + address=address if address else None, + ) + session.add(new_user) + session.commit() + session.refresh(new_user) + + # Save permissions + if permissions: + _save_permissions(session, new_user.id, permissions) + + create_audit_log(session, "user", new_user.id, "create", current_user, new_values={"username": username, "full_name": full_name}) + session.commit() + + return RedirectResponse(url="/users?success=User created successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/users?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# UPDATE USER +# =========================== +@router.post("/users/update/{user_id}") +def update_user( + user_id: int, + full_name: str = Form(...), + username: str = Form(...), + password: Optional[str] = Form(None), + role: str = Form("user"), + date_of_birth: Optional[str] = Form(None), + phone_number: Optional[str] = Form(None), + address: Optional[str] = Form(None), + is_active: Optional[str] = Form(None), + permissions: Optional[str] = Form(None), + request: Request = None, + session: Session = Depends(get_session) +): + if not require_permission(request, session, "user_management", "edit"): + return RedirectResponse(url="/users?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + + user = session.get(User, user_id) + if not user: + return RedirectResponse(url="/users?error=User not found", status_code=status.HTTP_303_SEE_OTHER) + + # Prevent editing admin's role/username + if user.username == "admin" and username != "admin": + return RedirectResponse(url="/users?error=Cannot change admin username", status_code=status.HTTP_303_SEE_OTHER) + + # Check duplicate username (exclude current user) + existing = session.exec(select(User).where(User.username == username, User.id != user_id)).first() + if existing: + return RedirectResponse(url=f"/users?error=Username '{username}' already exists", status_code=status.HTTP_303_SEE_OTHER) + + old_values = model_to_dict(user) + + # Parse DOB + dob = None + if date_of_birth and date_of_birth.strip(): + try: + dob = datetime.strptime(date_of_birth.strip(), "%d-%m-%Y") + except ValueError: + try: + dob = datetime.strptime(date_of_birth.strip(), "%Y-%m-%d") + except ValueError: + pass + + user.full_name = full_name + user.username = username + user.role = role + user.date_of_birth = dob + user.phone_number = phone_number if phone_number else None + user.address = address if address else None + user.is_active = is_active == "on" or is_active == "true" + user.edited_by = current_user.id if current_user else None + user.edited_at = datetime.now() + + # Update password only if provided + if password and password.strip(): + user.hashed_password = pwd_context.hash(password.strip()) + user.session_token = None # Force logout on password change + + # If user is deactivated, force logout + if not user.is_active: + user.session_token = None + + session.add(user) + session.commit() + + # Save permissions (delete old, insert new) + if permissions is not None: + _save_permissions(session, user_id, permissions) + session.commit() + + create_audit_log(session, "user", user.id, "update", current_user, old_values=old_values, new_values=model_to_dict(user)) + session.commit() + + return RedirectResponse(url="/users?success=User updated successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/users?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# DELETE USER +# =========================== +@router.post("/users/delete/{user_id}") +def delete_user(user_id: int, request: Request, session: Session = Depends(get_session)): + if not require_permission(request, session, "user_management", "delete"): + return RedirectResponse(url="/users?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER) + try: + current_user = get_current_user(request, session) + user = session.get(User, user_id) + + if not user: + return RedirectResponse(url="/users?error=User not found", status_code=status.HTTP_303_SEE_OTHER) + + # Prevent deleting admin + if user.username == "admin": + return RedirectResponse(url="/users?error=Cannot delete the admin account", status_code=status.HTTP_303_SEE_OTHER) + + old_values = model_to_dict(user) + + # Delete permissions first + perms = session.exec(select(UserPermission).where(UserPermission.user_id == user_id)).all() + for p in perms: + session.delete(p) + + session.delete(user) + session.commit() + + create_audit_log(session, "user", user_id, "delete", current_user, old_values=old_values) + session.commit() + + return RedirectResponse(url="/users?success=User deleted successfully!", status_code=status.HTTP_303_SEE_OTHER) + except Exception as e: + session.rollback() + return RedirectResponse(url=f"/users?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER) + +# =========================== +# API: Get user permissions +# =========================== +@router.get("/api/users/{user_id}/permissions") +def get_user_permissions(user_id: int, request: Request, session: Session = Depends(get_session)): + # Since checking permissions could be sensitive, just ensure session exists + if not require_permission(request, session, "user_management"): + return JSONResponse({"success": False, "error": "Permission Denied"}) + + user = session.get(User, user_id) + if not user: + return JSONResponse({"success": False, "error": "User not found"}) + + perms = session.exec(select(UserPermission).where(UserPermission.user_id == user_id)).all() + + permissions = {} + for p in perms: + buttons = [] + if p.allowed_buttons: + try: + buttons = json.loads(p.allowed_buttons) + except Exception: + buttons = [] + permissions[p.page_key] = buttons + + return JSONResponse({ + "success": True, + "user": { + "id": user.id, + "username": user.username, + "full_name": user.full_name, + "role": user.role, + "is_active": user.is_active, + "date_of_birth": user.date_of_birth.strftime("%d-%m-%Y") if user.date_of_birth else "", + "phone_number": user.phone_number or "", + "address": user.address or "", + }, + "permissions": permissions, + "pages_registry": PAGES_REGISTRY + }) + +# =========================== +# API: Get pages registry +# =========================== +@router.get("/api/pages-registry") +def get_pages_registry(): + return JSONResponse({"success": True, "pages_registry": PAGES_REGISTRY}) + +# =========================== +# Helper: Save permissions +# =========================== +def _save_permissions(session: Session, user_id: int, permissions_json: str): + """Delete old permissions and insert new ones from JSON.""" + # Delete existing + old_perms = session.exec(select(UserPermission).where(UserPermission.user_id == user_id)).all() + for p in old_perms: + session.delete(p) + session.flush() + + # Parse and insert new + try: + perms_data = json.loads(permissions_json) + # perms_data = {"page_key": ["btn1", "btn2"], ...} + if isinstance(perms_data, dict): + for page_key, buttons in perms_data.items(): + if page_key in PAGES_REGISTRY: + perm = UserPermission( + user_id=user_id, + page_key=page_key, + allowed_buttons=json.dumps(buttons) if buttons else "[]" + ) + session.add(perm) + except (json.JSONDecodeError, TypeError): + pass diff --git a/routes/websockets.py b/routes/websockets.py new file mode 100644 index 0000000000000000000000000000000000000000..b536a35f7df7847956334c5150edb61aa3f7c406 --- /dev/null +++ b/routes/websockets.py @@ -0,0 +1,309 @@ +from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Depends +from typing import Dict, List, Any +import json +import datetime +from sqlmodel import Session, select +from database import get_session +from models import User, Chat, ChatMember, Message, MessageReceipt + +router = APIRouter(prefix="/ws", tags=["WebSockets"]) + +# Simple in-memory connection manager +class ConnectionManager: + def __init__(self): + # Maps user_id to a list of active websocket connections (user can have multiple tabs) + self.active_connections: Dict[int, List[WebSocket]] = {} + # Maps user_id to active call info {target_id, start_time, call_type} + self.active_calls: Dict[int, Dict[str, Any]] = {} + + async def connect(self, user_id: int, websocket: WebSocket): + await websocket.accept() + if user_id not in self.active_connections: + self.active_connections[user_id] = [] + self.active_connections[user_id].append(websocket) + + def disconnect(self, user_id: int, websocket: WebSocket): + if user_id in self.active_connections: + self.active_connections[user_id].remove(websocket) + if not self.active_connections[user_id]: + del self.active_connections[user_id] + + async def send_personal_message(self, message: str, user_id: int): + if user_id in self.active_connections: + for connection in self.active_connections[user_id]: + await connection.send_text(message) + + async def broadcast_to_users(self, message: str, user_ids: List[int]): + for user_id in user_ids: + if user_id in self.active_connections: + for connection in self.active_connections[user_id]: + await connection.send_text(message) + +manager = ConnectionManager() + +# This is a public websocket endpoint, so client should pass some secure token +# For simplicity, we assume client passes user_id in path and validates session cookie if needed. +# Since FastAPI websocket dependencies can be tricky, we handle auth via the first message or query param. + +@router.websocket("/{user_id}") +async def websocket_endpoint(websocket: WebSocket, user_id: int): + # In a production app, validate user_id using the session cookie or token from headers. + await manager.connect(user_id, websocket) + + # Update user status to online + from database import engine + with Session(engine) as session: + user = session.get(User, user_id) + if user: + user.is_online = True + session.add(user) + session.commit() + + # Notify everyone that this user is online + await manager.broadcast_to_users( + json.dumps({"type": "status", "user_id": user_id, "is_online": True, "last_seen": None}), + list(manager.active_connections.keys()) + ) + + try: + while True: + data = await websocket.receive_text() + payload = json.loads(data) + + # Handle different event types + event_type = payload.get("type") + + with Session(engine) as session: + + if event_type == "message": + chat_id = payload.get("chat_id") + text = payload.get("text") + attachment = payload.get("attachment") + voice = payload.get("voice") + reply_to = payload.get("reply_to_id") + + # Create message + new_msg = Message( + chat_id=chat_id, + sender_id=user_id, + text=text, + reply_to_id=reply_to, + created_at=datetime.datetime.now() + ) + + if attachment: + new_msg.attachment_path = attachment.get("path") + new_msg.attachment_name = attachment.get("name") + new_msg.attachment_type = attachment.get("type") + + if voice: + new_msg.voice_note_path = voice.get("path") + new_msg.voice_note_duration = voice.get("duration") + + session.add(new_msg) + session.commit() + session.refresh(new_msg) + + # Get members of this chat to broadcast + members = session.exec(select(ChatMember).where(ChatMember.chat_id == chat_id)).all() + member_ids = [m.user_id for m in members] + + # Create receipts + for m_id in member_ids: + if m_id != user_id: + status = "delivered" if m_id in manager.active_connections else "sent" + receipt = MessageReceipt( + message_id=new_msg.id, + user_id=m_id, + chat_id=chat_id, + status=status + ) + session.add(receipt) + session.commit() + + # Broadcast + await manager.broadcast_to_users( + json.dumps({ + "type": "new_message", + "chat_id": chat_id, + "message": { + "id": new_msg.id, + "sender_id": user_id, + "text": text, + "attachment_path": getattr(new_msg, 'attachment_path', None), + "attachment_name": getattr(new_msg, 'attachment_name', None), + "attachment_type": getattr(new_msg, 'attachment_type', None), + "voice_note_path": getattr(new_msg, 'voice_note_path', None), + "voice_note_duration": getattr(new_msg, 'voice_note_duration', None), + "created_at": new_msg.created_at.isoformat(), + "status": "delivered" + } + }), + member_ids + ) + + elif event_type == "read": + chat_id = payload.get("chat_id") + message_ids = payload.get("message_ids", []) + + if message_ids: + receipts = session.exec(select(MessageReceipt).where( + MessageReceipt.message_id.in_(message_ids), + MessageReceipt.user_id == user_id + )).all() + for r in receipts: + r.status = "read" + r.updated_at = datetime.datetime.now() + session.add(r) + session.commit() + + # Find who sent these to notify them + for msg_id in message_ids: + m = session.get(Message, msg_id) + if m and m.sender_id: + await manager.send_personal_message( + json.dumps({ + "type": "receipt", + "chat_id": chat_id, + "message_id": msg_id, + "status": "read" + }), + m.sender_id + ) + + elif event_type == "typing": + chat_id = payload.get("chat_id") + members = session.exec(select(ChatMember).where(ChatMember.chat_id == chat_id)).all() + member_ids = [m.user_id for m in members if m.user_id != user_id] + await manager.broadcast_to_users( + json.dumps({ + "type": "typing", + "chat_id": chat_id, + "user_id": user_id + }), + member_ids + ) + + # WebRTC Signaling + elif event_type in ["offer", "answer", "ice-candidate", "call-end"]: + target_id = payload.get("target_id") + if target_id: + payload["sender_id"] = user_id + + # Handle call persistence + if event_type == "offer": + manager.active_calls[user_id] = { + "target_id": target_id, + "type": payload.get("callType", "voice"), + "start_time": None, + "initiator_id": user_id + } + # Also track for target so they can hang up/decline + manager.active_calls[target_id] = { + "target_id": user_id, + "type": payload.get("callType", "voice"), + "start_time": None, + "initiator_id": user_id + } + elif event_type == "answer": + # Mark call as started for both + start_time = datetime.datetime.now() + if user_id in manager.active_calls: + manager.active_calls[user_id]["start_time"] = start_time + if target_id in manager.active_calls: + manager.active_calls[target_id]["start_time"] = start_time + + elif event_type == "call-end": + # Call finished, save log + call_info = manager.active_calls.get(user_id) + if not call_info: # Fallback + call_info = manager.active_calls.get(target_id) + + if call_info: + status = "answered" if call_info.get("start_time") else "missed" + duration = 0 + if call_info.get("start_time"): + duration = int((datetime.datetime.now() - call_info["start_time"]).total_seconds()) + + initiator_id = call_info.get("initiator_id", user_id) + + # Find common chat robustly + chats_a = session.exec(select(ChatMember.chat_id).where(ChatMember.user_id == user_id)).all() + chats_b = session.exec(select(ChatMember.chat_id).where(ChatMember.user_id == target_id)).all() + common_ids = list(set(chats_a) & set(chats_b)) + + chat = None + if common_ids: + chat = session.exec(select(Chat).where( + Chat.id.in_(common_ids), + Chat.is_group == False + )).first() + + if chat: + call_msg = Message( + chat_id=chat.id, + sender_id=initiator_id, # Caller is always the sender for logs + text=f"{call_info.get('type','voice').capitalize()} Call", + is_call=True, + call_type=call_info.get("type", "voice"), + call_status=status, + call_duration=duration, + created_at=datetime.datetime.now() + ) + session.add(call_msg) + session.commit() + session.refresh(call_msg) + + # Broadcast call message + members = session.exec(select(ChatMember).where(ChatMember.chat_id == chat.id)).all() + member_ids = [m.user_id for m in members] + await manager.broadcast_to_users( + json.dumps({ + "type": "new_message", + "chat_id": chat.id, + "message": { + "id": call_msg.id, + "sender_id": call_msg.sender_id, + "text": call_msg.text, + "is_call": True, + "call_status": status, + "call_duration": duration, + "created_at": call_msg.created_at.isoformat(), + "status": "delivered" + } + }), + member_ids + ) + + # Cleanup for BOTH + manager.active_calls.pop(user_id, None) + manager.active_calls.pop(target_id, None) + # Ensure other side's key is also removed if it exists + manager.active_calls.pop(call_info.get("target_id"), None) + + await manager.send_personal_message( + json.dumps(payload), + target_id + ) + + except WebSocketDisconnect: + manager.disconnect(user_id, websocket) + # Update user status to offline + from database import engine + with Session(engine) as session: + user = session.get(User, user_id) + if user: + user.is_online = False + user.last_seen = datetime.datetime.now() + session.add(user) + session.commit() + + # Notify everyone + # (Ignore awaits in sync block, but wait, the inner engine loop isn't strict sync outside if we use safe session handling) + pass + + # Send offline status update + await manager.broadcast_to_users( + json.dumps({"type": "status", "user_id": user_id, "is_online": False, "last_seen": datetime.datetime.now().isoformat()}), + list(manager.active_connections.keys()) + ) diff --git a/routes/whatsapp_utils.py b/routes/whatsapp_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..85981eebd43e40924e66098030e2a60b0dbe0a9a --- /dev/null +++ b/routes/whatsapp_utils.py @@ -0,0 +1,219 @@ +import os +import base64 +import requests +import traceback +from fastapi.templating import Jinja2Templates +from playwright.sync_api import sync_playwright + +# Setup Jinja2 to point to your templates folder +templates = Jinja2Templates(directory="templates") + +def send_wati_pdf(phone_number, pdf_bytes, filename, caption, lab_info_dict): + """Sends the generated PDF via Wati API using dynamic database credentials.""" + try: + # Dynamically fetch from the LabInfo dictionary + wati_endpoint = lab_info_dict.get("whatsapp_api", "") if lab_info_dict else "" + token = lab_info_dict.get("whatsapp_token", "") if lab_info_dict else "" + + # Clean token just in case user pasted 'Bearer ' with it + if token.lower().startswith("bearer "): + token = token[7:].strip() + + # If no credentials exist in the database, abort and return a clear error + if not wati_endpoint or not token: + print("⚠️ Wati credentials missing from LabInfo database.") + return {"status": "error", "message": "WhatsApp API credentials are not configured in settings."} + + # Ensure the endpoint does not end with a slash and has https:// + wati_endpoint = wati_endpoint.strip() + if wati_endpoint and not wati_endpoint.startswith("http"): + wati_endpoint = f"https://{wati_endpoint}" + + # If the user included /api/v1 in the URL, strip it to prevent duplication + if "/api/v1" in wati_endpoint: + wati_endpoint = wati_endpoint.split("/api/v1")[0] + + base_url = wati_endpoint.rstrip("/") + + # Wati API expects the phone number without the '+' sign + clean_phone = phone_number.replace("+", "") + + url = f"{base_url}/api/v1/sendSessionFile/{clean_phone}" + + headers = { + "Authorization": f"Bearer {token}" + # Requests will set Content-Type correctly for multipart/form-data + } + + files = { + 'file': (filename, pdf_bytes, 'application/pdf') + } + + # Wati generally expects caption as a query parameter for sendSessionFile + params = { + "caption": caption + } + + response = requests.post(url, headers=headers, params=params, files=files) + + print("WATI API RESPONSE CODE:", response.status_code) + print("WATI API RESPONSE TEXT:", response.text) + + res_json = {} + try: + res_json = response.json() + except Exception: + res_json = {"status": "success" if response.status_code in [200, 201] else "error", "message": response.text} + + if response.status_code not in [200, 201] or str(res_json.get("result", "")).lower() == "error" or res_json.get("error"): + res_json["status"] = "error" + + return res_json + except Exception as e: + print(f"WhatsApp sending failed: {e}") + traceback.print_exc() + return {"status": "error", "message": str(e)} + +def send_wati_text(phone_number, message_text, lab_info_dict, template_name=None): + """Sends a WhatsApp message via Wati API. + Tries session message first. If contact is new (hasn't messaged first), + automatically falls back to template message.""" + try: + wati_endpoint = lab_info_dict.get("whatsapp_api", "") if lab_info_dict else "" + token = lab_info_dict.get("whatsapp_token", "") if lab_info_dict else "" + + if token.lower().startswith("bearer "): + token = token[7:].strip() + + if not wati_endpoint or not token: + return {"status": "error", "message": "WhatsApp API credentials are not configured."} + + wati_endpoint = wati_endpoint.strip() + if not wati_endpoint.startswith("http"): + wati_endpoint = f"https://{wati_endpoint}" + if "/api/v1" in wati_endpoint: + wati_endpoint = wati_endpoint.split("/api/v1")[0] + base_url = wati_endpoint.rstrip("/") + + clean_phone = phone_number.replace("+", "") + headers = {"Authorization": f"Bearer {token}"} + + # --- Step 1: Try session message (works if contact messaged before) --- + url = f"{base_url}/api/v1/sendSessionMessage/{clean_phone}" + response = requests.post(url, headers=headers, params={"messageText": message_text}) + + print("WATI SESSION RESPONSE:", response.status_code, response.text[:200]) + + res_json = {} + try: + res_json = response.json() + except Exception: + res_json = {"status": "success" if response.status_code in [200, 201] else "error"} + + # Check if session message succeeded + is_invalid_contact = "invalid contact" in str(res_json.get("info", "")).lower() + session_ok = response.status_code in [200, 201] and res_json.get("result") != False and not is_invalid_contact + + if session_ok: + return res_json + + # --- Step 2: Fallback to template message (works for new contacts) --- + if not template_name: + template_name = lab_info_dict.get("welcome_template_name", "") if lab_info_dict else "" + + if not template_name: + print("⚠️ No template name configured — cannot send to new contact") + return {"status": "error", "message": "Contact hasn't messaged first and no Wati template name is configured."} + + print(f"📨 Falling back to template message: {template_name}") + template_url = f"{base_url}/api/v1/sendTemplateMessage/{clean_phone}" + template_payload = { + "template_name": template_name, + "broadcast_name": "welcome_registration" + } + + tmpl_response = requests.post(template_url, headers={**headers, "Content-Type": "application/json"}, json=template_payload) + + print("WATI TEMPLATE RESPONSE:", tmpl_response.status_code, tmpl_response.text[:200]) + + tmpl_json = {} + try: + tmpl_json = tmpl_response.json() + except Exception: + tmpl_json = {"status": "success" if tmpl_response.status_code in [200, 201] else "error", "message": tmpl_response.text} + + if tmpl_response.status_code not in [200, 201] or str(tmpl_json.get("result", "")).lower() == "error": + tmpl_json["status"] = "error" + + return tmpl_json + except Exception as e: + print(f"WhatsApp text sending failed: {e}") + traceback.print_exc() + return {"status": "error", "message": str(e)} + +def generate_report_pdf(patient, visit, results, lab_info, template_data, barcode_data=None): + """ + Optimized Playwright PDF generator for maximum speed. + """ + print("🚀🚀🚀 PLAYWRIGHT ENGINE IS STARTING (OPTIMIZED)! 🚀🚀🚀") + try: + # Fetch formatted results quickly + try: + patient_id = patient.get("patient_id") + api_url = f"http://127.0.0.1:8000/api/double-authorized-tests/{patient_id}" + + api_resp = requests.get(api_url, timeout=3) + if api_resp.status_code == 200: + api_data = api_resp.json() + if api_data.get("success"): + results = api_data.get("results", []) + except Exception as api_err: + print(f"⚠️ Local API fetch failed: {api_err}") + + # Render Template + template = templates.get_template("print_report.html") + html_content = template.render({ + "patient": patient, + "visit": visit, + "lab_info": lab_info, + "template": template_data, + "barcode_data": barcode_data, + "results": results + }) + + paper_size = template_data.get('paperSize', 'A4').upper() + os.makedirs("tmp", exist_ok=True) + html_content = html_content.replace("", "h?l[c][f]=s+1:n.charAt(c-1)===i.charAt(f-1)?l[c][f]=l[c-1][f-1]:l[c][f]=Math.min(l[c-1][f-1]+1,Math.min(l[c][f-1]+1,l[c-1][f]+1)),l[c][f] Monitor recent operational events and user actions across the system. (Top 500) {{ message_success }} {{ message_error }} Record a calibration or control process. Tests will be automatically deducted from inventory. No records found matching your criteria. Select filters and click search to view calibration and control records. No records found Try adjusting your search criteria or toggles
+ Showing {{ patient_data|length }} of {{ total_count }} visit(s)
+ Clear filters
+ Fetching patient results... Done Patients Called Patients Pending Call No critical value alerts found. No tests logged yet. By: Ali Saleem View and restore deactivated patients Audit log of tests removed during patient registration edits No deleted tests found Try adjusting your filters or date range. Define laboratory departments and sections Get started by adding a new department. Total Amount Without Discount {{ "{:,.0f}".format(total_amount_without_discount) }} Total Discounts {{ "{:,.0f}".format(total_discount) }} Total Expenses {{ "{:,.0f}".format(total_expense) }} Total Remains {{ "{:,.0f}".format(total_remain) }} Received Amounts {{ "{:,.0f}".format(total_received) }} {{ "{:,.0f}".format(net_amount_2) }} Manage laboratory equipment and analyzers Get started by adding a new device. No orders found for this patient visit Register tests for the patient first. No patients found Try adjusting your search criteria
+ Showing {{ patient_data|length }} of {{ total_count }} visit(s)
+ Clear filters
+ Add an expense using the form above. Define categories for laboratory expenses Get started by defining your first expense category. Define calculation formulas for derived test results Get started by adding a new formula definition. Manage lab staff and their details {% if emp.username %}@{{ emp.username }}{% else %}Employee{% endif %} No employees found. Track and manage tests and supplies
+ {% if search or expires_soon %}
+ Try adjusting your filters to find what you're looking for.
+ {% else %}
+ Get started by adding your first material.
+ {% endif %}
+ Configure your laboratory details and branding {{ lab_info.lab_name if lab_info.lab_name else '-' }} {{ lab_info.lab_title if lab_info.lab_title else '-' }} {{ lab_info.welcome_message if lab_info.welcome_message else '-' }} {{ lab_info.welcome_template_name if lab_info.welcome_template_name else '-' }} {{ province_name if province_name else '-' }} {{ lab_info.first_doctor_name if lab_info.first_doctor_name else '-' }} {{ lab_info.second_doctor_name if lab_info.second_doctor_name else '-' }} {{ lab_info.lab_address if lab_info.lab_address else '-' }} {{ lab_info.lab_phone_1 if lab_info.lab_phone_1 else '-' }} {{ lab_info.lab_phone_2 if lab_info.lab_phone_2 else '-' }} {{ lab_info.lab_email if lab_info.lab_email else '-' }} {{ lab_info.lab_website if lab_info.lab_website else '-' }} {{ lab_info.tax_percentage if lab_info.tax_percentage else '0' }}% {{ lab_info.whatsapp_api if lab_info.whatsapp_api else '-' }} {{ lab_info.whatsapp_token if lab_info.whatsapp_token else '-' }} {{ lab_info.telegram_api if lab_info.telegram_api else '-' }} {{ lab_info.telegram_token if lab_info.telegram_token else '-' }} {{ lab_info.lab_note_1 if lab_info.lab_note_1 else '-' }} {{ lab_info.lab_note_2 if lab_info.lab_note_2 else '-' }} Click Edit to add your laboratory details. Select a chat to start messaging, or create a new one. There are no tests missing samples in the holding queue. Are you sure you want to mark this sample as received? Define test packages with multiple tests Get started by adding a new package definition. Define test parameters and headers Get started by adding a new parameter. Define laboratory partners and referral centers Get started by adding a new partner definition. Patient ID: {{ patient.patient_id }} Patient ID: {{ last_patient_id }} This patient has already been registered today with all of the selected tests. No patients found Try adjusting your search criteria
+ {{ patient_data|length }} visit(s) found
+ Clear filters
+
+ Showing {{ patient_visits|length }} of {{ total_count }} visit(s)
+ {% if search or test_filter %}
+ | Clear filters
+ {% endif %}
+ Drag elements here to design your barcode Select an element to edit properties Drag elements here to design your receipt Select an element to edit properties Drag elements here to design your receipt Please create and save a receipt design in the Receipt Designer first. Drag Elements Here Select an element to edit No patients found Try adjusting your search criteria
+ Showing {{ patient_data|length }} of {{ total_count }} visit(s)
+ Clear filters
+ Define provinces for patient locations Get started by adding a new province definition. Define regions within provinces for patient locations Get started by adding a new region definition. Define rich text notes for laboratory reports Get started by adding a new report note. No orders found for this patient visit Register tests for the patient first. No patients found Try adjusting your search criteria
+ Showing {{ patient_data|length }} of {{ total_count }} visit(s)
+ Clear filters
+ Define laboratory sample types Get started by adding a new sample type. Define and manage laboratory supplies
+ {% if search %}
+ Try adjusting your search terms or clear the filter.
+ {% else %}
+ Get started by adding your first laboratory supply.
+ {% endif %}
+ Define laboratory tests with parameters and devices Get started by adding a new test definition. Manage users and their page/button permissions Get started by creating a new user. Patient ID: {{ patient.patient_id }} {{ patient.patient_id }} {{ patient.full_name }} {{ patient.gender|capitalize }} {{ patient.age }} {{ patient.age_unit or 'year' }}{{ 's' if patient.age and patient.age > 1 else '' }} {{ patient.phone_key }} {{ patient.phone_number }} {{ patient.weight }} kg / {{ patient.height }} cm Loading results...{u();function Xg(r,e){var t=r.type,i=r.value,n,s;return e&&(s=e(r))!==void 0?s:t==="word"||t==="space"?i:t==="string"?(n=r.quote||"",n+i+(r.unclosed?"":n)):t==="comment"?"/*"+i+(r.unclosed?"":"*/"):t==="div"?(r.before||"")+i+(r.after||""):Array.isArray(r.nodes)?(n=Zg(r.nodes,e),t!=="function"?n:i+"("+(r.before||"")+n+(r.after||"")+(r.unclosed?"":")")):i}function Zg(r,e){var t,i;if(Array.isArray(r)){for(t="",i=r.length-1;~i;i-=1)t=Xg(r[i],e)+t;return t}return Xg(r,e)}Jg.exports=Zg});var ry=x((lq,ty)=>{u();var Cs="-".charCodeAt(0),_s="+".charCodeAt(0),Fl=".".charCodeAt(0),j2="e".charCodeAt(0),z2="E".charCodeAt(0);function U2(r){var e=r.charCodeAt(0),t;if(e===_s||e===Cs){if(t=r.charCodeAt(1),t>=48&&t<=57)return!0;var i=r.charCodeAt(2);return t===Fl&&i>=48&&i<=57}return e===Fl?(t=r.charCodeAt(1),t>=48&&t<=57):e>=48&&e<=57}ty.exports=function(r){var e=0,t=r.length,i,n,s;if(t===0||!U2(r))return!1;for(i=r.charCodeAt(e),(i===_s||i===Cs)&&e++;e{u();function Gy(r,e){var t=r.type,i=r.value,n,s;return e&&(s=e(r))!==void 0?s:t==="word"||t==="space"?i:t==="string"?(n=r.quote||"",n+i+(r.unclosed?"":n)):t==="comment"?"/*"+i+(r.unclosed?"":"*/"):t==="div"?(r.before||"")+i+(r.after||""):Array.isArray(r.nodes)?(n=Qy(r.nodes,e),t!=="function"?n:i+"("+(r.before||"")+n+(r.after||"")+(r.unclosed?"":")")):i}function Qy(r,e){var t,i;if(Array.isArray(r)){for(t="",i=r.length-1;~i;i-=1)t=Gy(r[i],e)+t;return t}return Gy(r,e)}Yy.exports=Qy});var Zy=x((o$,Xy)=>{u();var $s="-".charCodeAt(0),Ls="+".charCodeAt(0),su=".".charCodeAt(0),vO="e".charCodeAt(0),xO="E".charCodeAt(0);function kO(r){var e=r.charCodeAt(0),t;if(e===Ls||e===$s){if(t=r.charCodeAt(1),t>=48&&t<=57)return!0;var i=r.charCodeAt(2);return t===su&&i>=48&&i<=57}return e===su?(t=r.charCodeAt(1),t>=48&&t<=57):e>=48&&e<=57}Xy.exports=function(r){var e=0,t=r.length,i,n,s;if(t===0||!kO(r))return!1;for(i=r.charCodeAt(e),(i===Ls||i===$s)&&e++;eSystem Activity Logs
+
+
+
+
+
+
+
+ {% for log in activities %}
+ Timestamp
+ User
+ Action Type
+ Description
+ Target Details
+
+
+ {% else %}
+ {{ log.created_at.strftime('%Y-%m-%d %H:%M:%S') }}
+ {{ log.username }}
+
+ {% if "LOGIN" in log.action_type %}
+
+ {{ log.action_type }}
+
+ {% elif "LOGOUT" in log.action_type %}
+
+ {{ log.action_type }}
+
+ {% elif "PRINT" in log.action_type %}
+
+ {{ log.action_type }}
+
+ {% else %}
+
+ {{ log.action_type }}
+
+ {% endif %}
+
+ {{ log.description }}
+
+ {% if log.target_type %}
+ {{ log.target_type }}
+ {% if log.target_id %}#{{ log.target_id }}{% endif %}
+ {% else %}-{% endif %}
+
+
+
+ {% endfor %}
+
+
+
+ {% block page_title %}Dashboard{% endblock %}
+ Record Cal / Control
+ Cal & Control History
+
+
+
+
+
+
+
+ {% for item in history %}
+ Date
+ Process
+ Test Name
+ Device
+ Qty Deducted
+ Note
+
+
+ {% endfor %}
+
+
+ {{ item.created_at.strftime('%Y-%m-%d %H:%M') }}
+
+
+ {% if item.process_type == 'Cal' %}
+ Calibration
+ {% else %}
+ Control
+ {% endif %}
+
+
+ {{ item.test.test_name if item.test else 'Unknown' }}
+
+
+ {{ item.device.device_name if item.device else 'Unknown' }}
+
+
+ -{{ item.quantity }}
+
+
+ {{ item.note or '---' }}
+
+ Search History
+
+
+
+
+
+
+
+ {% for item in patient_data %}
+
+ Registration Date
+ Patient
+ ID
+ Name
+
+
+ Age/Gender
+ Phone
+
+ Tests
+
+ Status
+
+ Alarm
+
+
+
+ {% else %}
+
+ {{ item.registration_date.strftime('%Y-%m-%d %H:%M') if item.registration_date else '' }}
+
+ {{ item.patient.patient_id
+ }}
+ {{ item.patient.full_name
+ }}
+
+
+
+
+
+ {{ item.patient.phone_key }}{{ item.patient.phone_number }}
+
+
+
+
+
+
+ {{ item.status }}
+
+
+
+
+
+
+ {% endfor %}
+
+
+
+ Name:{{ patient.full_name }}
+
+
+
+
+
+
+
+
+
+
+ Test / Parameter
+ Result
+ Range
+ Unit
+ Status
+ Remark
+
+
+
+
+
+
+ Patients Numbers Section
+ Call Centre Section
+ Total
+ Sent
+ Not Sent
+ General Info Section
+
+
+ Critical Value Alerts
+
+
+
+
+ {% else %}
+
+
+
+
+ {% for alert in dash.critical_alerts %}
+ Patient
+
+ Test
+ Value
+ Date
+
+
+ {% endfor %}
+
+ {{
+ alert.patient_name }} ({{ alert.patient_id
+ }})
+ {{ alert.test_name }}
+
+ {{
+ alert.value }}
+ {{ alert.date }}
+ Patient Demographics
+ Top Requested Tests
+
+ {% for tt in dash.top_tests %}
+
+ {% else %}
+
+
+ Scan to visit website
+ Deleted Patients
+
+
+
+
+
+
+
+ {% for patient in patients %}
+ Patient ID
+ Name
+ Phone
+ Total Amount
+ Deleted Date
+ User
+ Deletion Reason
+ Actions
+
+
+ {% else %}
+ {{ patient.patient_id }}
+ {{ patient.full_name }}
+ {{ patient.phone_key }} {{ patient.phone_number }}
+ {{ '{:,.0f}'.format(patient_totals.get(patient.id, 0)) }}
+ {{ patient.deleted_at.strftime('%Y-%m-%d %H:%M') if patient.deleted_at else 'N/A' }}
+ {{ user_dict.get(patient.deleted_by, 'Unknown') }}
+ {{ patient.deleted_reason or '—' }}
+
+
+
+
+ {% endfor %}
+ {% if patients %}
+ No deleted patients found
+
+
+ {% endif %}
+
+ Total:
+
+ {% set ns = namespace(total=0) %}
+ {% for patient in patients %}
+ {% set ns.total = ns.total + patient_totals.get(patient.id, 0) %}
+ {% endfor %}
+ {{ '{:,.0f}'.format(ns.total) }}
+
+
+
+
+ Deleted Tests
+
+
+
+
+
+
+
+
+ {% if report_data %}
+ {% for row in report_data %}
+ No.
+ Date & Time
+ User Name
+ Patient ID
+ Patient Name
+ Age-Gender
+ Deleted Test
+ Price
+ Reason
+
+
+ {% endfor %}
+ {{ row.no }}
+ {{ row.deleted_at }}
+
+
+ {{ row.deleted_by_name }}
+
+
+ {{ row.patient_code }}
+ {{ row.patient_name }}
+ {{ row.age_gender }}
+
+
+ {{ row.test_name }}
+
+
+ {{ '{:,.0f}'.format(row.price) }}
+ {{ row.reason }}
+
+
+ {% else %}
+ Total:
+
+ {% set ns = namespace(total=0) %}
+ {% for row in report_data %}
+ {% set ns.total = ns.total + (row.price or 0) %}
+ {% endfor %}
+ {{ '{:,.0f}'.format(ns.total) }}
+
+
+
+
+ {% endif %}
+
+
+
+ Department Definition
+
+
+
+
+
+
+
+ {% for dept in departments %}
+ ID
+ Department Name
+ Note
+ Created
+ Actions
+
+
+ {% endfor %}
+
+ #{{ dept.id }}
+ {{ dept.department_name }}
+ {{ dept.department_note if dept.department_note else '-' }}
+ {{ dept.created_at.strftime('%Y-%m-%d') }}
+
+
+ No departments
+ Net Amount Without Tax
+ Device Definition
+
+
+
+
+
+
+
+ {% for device in devices %}
+
+ {% endfor %}
+
+ ID
+ Device Name
+ Serial Number
+ Install Date
+ Installer
+ Created
+ Actions
+ No devices
+
+
+
+
+
+
+
+ {% if records %}
+ {% for row in records %}
+ No
+ Date and Time
+ Patient ID
+ Patient Name
+ User
+ Discount Amount
+ Discount Note
+
+
+ {% endfor %}
+ {% else %}
+ {{ row.no }}
+ {{ row.datetime }}
+
+ {{ row.patient_code }}
+
+ {{ row.patient_name }}
+ {{ row.user }}
+ {{ row.discount_amount }}
+ {{ row.discount_note }}
+
+
+ {% endif %}
+
+ {% if records %}
+
+ No discounts found for the selected criteria.
+
+
+
+ {% endif %}
+ Total Summary
+ {{ total_discount }}
+
+ Name:{{ patient.full_name }}
+
+
+
+
+
+
+
+
+
+
+ Test / Parameter
+ Result
+ Unit
+ Device
+ Range
+ AUTH status
+ Status
+ ReRun Result
+ Remark
+ Actions
+
+
+
+
+
+
+
+ {% for item in patient_data %}
+ Patient ID
+ Registration Date
+ Name
+ Age
+ Gender
+ Patient tests
+ Action
+
+
+ {% else %}
+ {{ item.patient.patient_id }}
+ {{ item.registration_date.strftime('%Y-%m-%d %H:%M') if item.registration_date else '' }}
+ {{ item.patient.full_name }}
+
+ {{ item.patient.age }} {{ item.patient.age_unit or 'year' }}{{ 's' if item.patient.age and item.patient.age > 1 else '' }}
+
+
+
+ {{ item.patient.gender|capitalize }}
+
+
+
+
+
+
+
+ Enter
+
+
+
+
+ {% endfor %}
+
+
+
+ New Expense Entry
+
+ Recent Expenses
+
+
+
+
+
+
+
+ {% for exp in expenses %}
+ ID
+ Type
+ Date
+ Amount
+ Notes
+ File
+ Actions
+
+
+ {% endfor %}
+
+ #{{ exp.id }}
+ {{ exp.expense_type.type_name }}
+ {{ exp.expense_date.strftime('%Y-%m-%d') }}
+ {{ "{:,.2f}".format(exp.amount) }}
+ {{ exp.note if exp.note else '-' }}
+
+ {% if exp.file_path %}
+
+
+ View File
+
+ {% else %}
+ No File
+ {% endif %}
+
+
+
+ No expenses recorded
+
+
+
+
+
+
+
+ {% if expenses %}
+ {% for exp in expenses %}
+ ID
+ Type
+ Date
+ Amount
+ Notes
+ File
+ User
+
+
+ {% endfor %}
+ {% else %}
+ #{{ exp.id }}
+ {{ exp.expense_type.type_name }}
+ {{ exp.expense_date.strftime('%d-%m-%Y') }}
+ {{ "{:,.2f}".format(exp.amount) }}
+
+ {{ exp.note if exp.note else '-' }}
+
+
+ {% if exp.file_path %}
+
+
+ View File
+
+ {% else %}
+
+
+ No File
+
+ {% endif %}
+
+
+
+
+
+ {% endif %}
+
+ {% if expenses %}
+
+ No expenses matching the selected criteria.
+
+
+
+ {% endif %}
+ Total Summary
+ {{ "{:,.2f}".format(total_amount) }}
+ Expenses Types Definition
+
+
+
+
+
+
+
+ {% for etype in expense_types %}
+ Type ID
+ Type Name
+ Created
+ Actions
+
+
+ {% endfor %}
+
+ #{{ etype.id }}
+ {{ etype.type_name }}
+ {{ etype.created_at.strftime('%Y-%m-%d') }}
+
+
+ No expense types
+ Formula Definition
+
+
+
+
+
+
+
+ {% for formula in formulas %}
+ ID
+ Name
+ Main Test
+ Parameter
+ Gender
+ Created
+ Actions
+
+
+ {% endfor %}
+
+ #{{ formula.id }}
+ {{ formula.formula_name }}
+ {{ formula.main_test.test_name }}
+ {{ formula.main_parameter.parameter_name if formula.main_parameter else '-' }}
+
+
+ {{ formula.gender_type|capitalize }}
+
+
+ {{ formula.created_at.strftime('%Y-%m-%d') }}
+
+
+ No formulas defined
+ Employees
+
+ {% else %}
+ {{ emp.full_name[0] }}
+ {% endif %}
+
{{ emp.full_name }}
+ Inventory Items
+
+
+
+
+
+
+
+ {% for item in inventory_items %}
+ Item Name
+ Type
+ Quantity
+ Unit
+ Expiration Date
+ Note
+ Actions
+
+
+ {% endfor %}
+
+
+ {{ item.name }}
+
+
+ {% if item.material_type == 'Test' %}
+ Test
+ {% else %}
+ Supply
+ {% endif %}
+
+
+
+ {{ item.quantity }}
+
+
+
+ {{ item.unit }}
+
+
+
+ {{ item.expiration_date.strftime('%d-%m-%Y') }}
+
+
+
+ {{ item.note or '---' }}
+
+
+
+ No inventory found
+ Lab Information
+
+
+ Basic Information
+
+
+
+ Contact Information
+
+
+
+ Messaging APIs
+
+ WhatsApp
+ Telegram
+
+
+ Images & Branding
+
+
+ {% else %}
+
+
+ Notes
+
+ No lab information configured
+ Chats
+
+ NexLab Messenger
+
+
+
+
+
+
+
+ {% if rows %}
+ {% for row in rows %}
+ Date
+ Net Amount With Tax
+ Net Amount Without Tax
+
+
+ {% endfor %}
+ {% else %}
+ {{ row.date }}
+ {{ "{:,.0f}".format(row.net_with_tax) }}
+ {{ "{:,.0f}".format(row.net_without_tax) }}
+
+
+ {% endif %}
+
+ {% if rows %}
+
+ No data found for the selected date range.
+
+
+
+ {% endif %}
+ Total Summary
+ {{ "{:,.0f}".format(total_net_with_tax) }}
+ {{ "{:,.0f}".format(total_net_without_tax) }}
+ 🚫 No Sample Holding Area
+
+ {{ orders|length }} Missing Samples
+
+
+
+
+
+
+
+
+ {% for order in orders %}
+ Order Date
+ Patient Name
+ Patient ID
+ Test / Package
+ Reason
+ Actions
+
+
+ {% else %}
+
+ {{ order.order_date.strftime('%Y-%m-%d %H:%M') }}
+
+
+
+ {{ order.patient.full_name }}
+
+
+ {{ order.patient.patient_id }}
+
+
+
+
+
+
+ {{ order.no_sample_reason or 'No reason provided' }}
+
+
+
+
+
+
+
+ {% endfor %}
+
+
+
+ All Clear!
+
The test will be sent cleanly back to the Result Entry workflows.Package Definition
+ Search Packages
+
+
+
+
+
+
+
+ {% for package in packages %}
+ Package Name
+ Short Name
+ Tests
+ Price
+ Note
+ Actions
+
+
+ {% endfor %}
+
+ {{ package.package_name }}
+ {{ package.package_short_name }}
+
+
+ ${{ "%.2f"|format(package.price) }}
+ {{ package.package_note if package.package_note else '-' }}
+
+
+ No packages defined
+ Parameter Definition
+
+
+
+
+
+
+
+ {% for param in parameters %}
+
+ {% endfor %}
+
+ ID
+ Parameter Name
+ Short Name
+ Type
+ Created
+ Actions
+ No parameters
+ Partner Definition
+ Search Partners
+
+
+
+
+
+
+
+ {% for partner in partners %}
+ ID
+ Partner Name
+ Contact
+ Weight
+ Note
+ Actions
+
+
+ {% endfor %}
+
+ #{{ partner.id }}
+ {{ partner.partner_name }}
+ {{ partner.partner_contact if partner.partner_contact else '-' }}
+ {{ partner.partner_weight if partner.partner_weight else '-' }}
+ {{ partner.partner_note if partner.partner_note else '-' }}
+
+
+ No partners defined
+ Edit Patient
+ {{ patient.full_name }}
+ Complete Action Ledger
+
+
+
+
+
+
+
+ {% for log in logs %}
+ Date and
+ Time
+ Action
+ Type
+ Username
+
+ Action
+ Detail
+
+
+ {% else %}
+
+ {{ log.date.strftime('%Y-%m-%d %H:%M:%S') if log.date else 'N/A' }}
+
+
+
+ {{ log.action_type }}
+
+
+
+ {{ log.username }}
+
+
+ {{ log.detail }}
+
+
+
+ {% endfor %}
+
+
+ No tracking history found for this patient.
+
+
+
+
+
+
+
+
+ {% for p in patients %}
+ Patient ID
+
+ Name
+ Gender /
+ Age
+ Action
+
+
+
+ {% else %}
+ {{ p.patient_id
+ }}
+ {{ p.full_name }}
+
+ {{ p.gender|capitalize }} / {{ p.age }} {{ p.age_unit }}
+
+
+
+ View History
+
+
+
+
+ {% endfor %}
+
+ No patients found matching
+ the criteria.
+
+
+
+
+
+
+
+ {% if rows %}
+ {% for row in rows %}
+ Date
+ Region
+ Patient Count
+
+
+ {% endfor %}
+ {% else %}
+ {{ row.date }}
+ {{ row.region_name }}
+
+
+ {{ row.patient_count }}
+
+
+
+
+ {% endif %}
+
+ {% if rows %}
+
+ No patients found for the selected dates and region.
+
+
+
+ {% endif %}
+ Total Summary
+ {{ total_patients }}
+ Patient Registered Successfully!
+ Duplicate Detection
+
+
+
+
+
+
+
+ {% for item in patient_data %}
+ Patient ID
+ Name
+ Phone
+ Age/Gender
+ Test Details & Status
+
+
+ {% else %}
+ {{ item.patient.patient_id }}
+ {{ item.patient.full_name }}
+ {{ item.patient.phone_key }}{{ item.patient.phone_number }}
+
+ {{ item.patient.age }}Y-
+
+ {{ item.patient.gender|capitalize }}
+
+
+
+
+
+
+ {% endfor %}
+
+
+
+
+
+
+
+
+
+
+ {% for item in patient_visits %}
+ Patient ID
+ Name
+ Gender
+ Age
+ Phone
+ Registered
+ Actions
+
+
+ {% else %}
+ {{ item.patient.patient_id }}
+ {{ item.patient.full_name }}
+
+
+ {{ item.patient.gender|capitalize }}
+
+
+
+ {{ item.patient.age }} {{ item.patient.age_unit or 'year' }}{{ 's' if item.patient.age and item.patient.age > 1 else '' }}
+
+
+ {{ item.patient.phone_key }} {{ item.patient.phone_number }}
+
+
+ {{ item.visit_date.strftime('%Y-%m-%d %H:%M') if item.visit_date else item.patient.created_at.strftime('%Y-%m-%d %H:%M') }}
+
+
+
+
+
+ {% endfor %}
+
+
+ No patients found. Register a new patient
+
+
+
+
+
+
+
+
+ {% if rows %}
+ {% for row in rows %}
+ Date
+ Total
+
+
+ {% endfor %}
+ {% else %}
+ {{ row.date }}
+
+
+ {{ row.patient_count }}
+
+
+
+
+ {% endif %}
+
+ {% if rows %}
+
+ No fully double authorized
+ patients found for the selected dates.
+
+
+
+ {% endif %}
+ Total Summary
+ {{ total_patients }}
+
+
+
+
+
+
+
+ {% if records %}
+ {% for row in records %}
+ NO
+ Date & Time
+ Patient Name
+ User
+ Record Type
+ Price
+
+
+ {% endfor %}
+ {% else %}
+ {{ row.no }}
+ {{ row.date_str }}
+ {{ row.patient_name }}
+ {{ row.user }}
+
+ {% if row.type == "Receive" %}
+
+ Receive
+
+ {% else %}
+
+ Expense
+
+ {% endif %}
+
+
+ {{ "{:,.0f}".format(row.price) }}
+
+
+
+ {% endif %}
+
+ {% if records %}
+
+ No records found for the selected criteria.
+
+
+
+ {% endif %}
+ Total sum
+ {{ "{:,.0f}".format(total_price) }}
+ Barcode Designer
+Available Elements
+
+Design Preview
+Element Properties
+
+Receipt Designer
+Available Elements
+
+
+Receipt Preview
+Element Properties
+
+Receipt Designer
+Available Elements
+
+
+Receipt Preview
+Element Properties
+
+⚠️ No Receipt Design Found
+ Result Designer
+
+ Components
+
+ Properties
+
+
+
+
+
+
+
+
+
+
+
+ {% for item in patient_data %}
+ Patient ID
+ Registration Date
+ Name
+ Age
+ Gender
+ Patient tests
+ Action
+
+
+ {% else %}
+ {{ item.patient.patient_id }}
+ {{ item.registration_date.strftime('%Y-%m-%d %H:%M') if item.registration_date else '' }}
+ {{ item.patient.full_name }}
+
+ {{ item.patient.age }} {{ item.patient.age_unit or 'year' }}{{ 's' if item.patient.age and item.patient.age > 1 else '' }}
+
+
+
+ {{ item.patient.gender|capitalize }}
+
+
+
+
+
+
+
+ View
+
+
+
+
+ {% endfor %}
+
+
+
+ Province Definition
+ Search Provinces
+
+
+
+
+
+
+
+ {% for province in provinces %}
+ ID
+ Province Name
+ Actions
+
+
+ {% endfor %}
+
+ #{{ province.id }}
+ {{ province.province_name }}
+
+
+ No provinces defined
+ Region Definition
+ Search Regions
+
+
+
+
+
+
+
+ {% for region in regions %}
+ ID
+ Region Name
+ Province
+ Actions
+
+
+ {% endfor %}
+
+ #{{ region.id }}
+ {{ region.region_name }}
+ {{ region.province.province_name }}
+
+
+ No regions defined
+
+
+
+
+
+
+
+ {% if records %}
+ {% for row in records %}
+ No
+ Patient ID
+ Patient Name
+ Visit Date
+ Total Amount
+ Paid
+ Discount
+ Remain
+ Username
+
+
+ {% endfor %}
+ {% else %}
+ {{ row.no }}
+
+ {{ row.patient_code }}
+
+ {{ row.patient_name }}
+ {{ row.visit_date }}
+ {{ "{:,.0f}".format(row.total_amount) }}
+ {{ "{:,.0f}".format(row.paid) }}
+ {{ "{:,.0f}".format(row.discount_amount) }}
+ {{ "{:,.0f}".format(row.remain_amount) }}
+ {{ row.username }}
+
+
+ {% endif %}
+
+ {% if records %}
+
+ No remaining balances found for the selected criteria.
+
+
+
+ {% endif %}
+ Total Remaining
+ {{ "{:,.0f}".format(total_remain) }}
+
+ Report Note Definition
+
+
+
+
+
+
+
+ {% for note in report_notes %}
+ ID
+ Note Name
+ Preview
+ Created
+ Actions
+
+
+ {% endfor %}
+
+ #{{ note.id }}
+ {{ note.note_name }}
+
+
+ {{ note.created_at.strftime('%Y-%m-%d') }}
+
+
+ No report notes
+ Name:{{ patient.full_name }}
+
+
+
+
+
+
+
+
+
+
+ Test /
+ Parameter
+ Result
+ Unit
+ Device
+ Range
+
+
+
+ Status
+ ReRun Result
+
+ Remark
+ Actions
+
+
+
+
+
+
+
+ {% for item in patient_data %}
+ Patient ID
+ Registration Date
+ Name
+ Age
+ Gender
+ Patient tests
+ Action
+
+
+ {% else %}
+ {{ item.patient.patient_id }}
+ {{ item.registration_date.strftime('%Y-%m-%d %H:%M') if item.registration_date else '' }}
+ {{ item.patient.full_name }}
+
+ {{ item.patient.age }} {{ item.patient.age_unit or 'year' }}{{ 's' if item.patient.age and item.patient.age > 1 else '' }}
+
+
+
+ {{ item.patient.gender|capitalize }}
+
+
+
+
+
+
+
+ Enter
+
+
+
+
+ {% endfor %}
+
+
+
+ Sample Type Definition
+
+
+
+
+
+
+
+ {% for sample in sample_types %}
+
+ {% endfor %}
+
+ ID
+ Sample Name
+ Note
+ Created
+ Actions
+ No sample types
+ Supply Management
+
+
+
+
+
+
+
+ {% for supply in supplies %}
+ ID
+ Supply Name
+ Note
+ Actions
+
+
+ {% endfor %}
+
+ #{{ supply.id }}
+
+ {{ supply.name }}
+
+
+ {{ supply.note or '---' }}
+
+
+
+ No supplies found
+ Test Definition
+
+
+
+
+
+
+
+ {% for test in tests %}
+
+ {% endfor %}
+
+ ID
+ Test
+ Name
+ Short
+
+
+ Department
+ Report
+ Note
+ Price
+
+
+ Available
+
+ No tests defined
+
+
+
+
+
+
+
+ {% if rows %}
+ {% for row in rows %}
+ Date
+ Test Name
+ Total
+
+
+ {% endfor %}
+ {% else %}
+ {{ row.date }}
+ {{ row.test_name }}
+
+
+ {{ row.test_count }}
+
+
+
+
+ {% endif %}
+
+ {% if rows %}
+
+ No fully double authorized tests
+ found for the selected dates.
+
+
+
+ {% endif %}
+ Total
+ Summary
+ {{ total_tests }}
+ User Management
+
+
+
+ {% if not users %}
+
+
+
+
+ {% for user in users %}
+ User
+ Username
+ Role
+ Phone
+ DOB
+ Status
+ Actions
+
+
+ {% endfor %}
+
+
+
+
+ {{ user.username }}
+
+
+
+ {{ user.role|capitalize }}
+
+
+
+ {{ user.phone_number if user.phone_number else '-' }}
+
+
+ {{ user.date_of_birth.strftime('%d-%m-%Y') if user.date_of_birth else '-' }}
+
+
+ {% if user.is_active %}
+ Active
+ {% else %}
+ Inactive
+ {% endif %}
+
+
+
+ No users
+ Deleted Patient Details
+ Patient Information
+ ⚠️ Deletion Information
+ Name:{{ patient.full_name }}
+
+
+
+
+
+
+
+
+
+
+
+ Test / Parameter
+ Result
+ Unit
+ Range
+ Remark
+
+
+
+
+
+
+
+
+
+
+
+ Patient Name:
+ {{ patient.full_name }}
+ Patient ID:
+ {{ patient.patient_id }}
+
+
+ Age/Gender:
+ {{ patient.age }} {{ patient.age_unit }} / {{ patient.gender|upper }}
+ Visit ID:
+ {{ visit.visit_id }}
+
+
+ Date:
+ {{ visit.visit_date.strftime('%Y-%m-%d %H:%M') }}
+ Doctor:
+ {{ patient.doctor or 'N/A' }}
+
+
+
+
+
+
+
diff --git a/tools/backup_db.py b/tools/backup_db.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5f0b23127f736125086ef034499ac6b6709ca78
--- /dev/null
+++ b/tools/backup_db.py
@@ -0,0 +1,63 @@
+import os
+import sqlite3
+from datetime import datetime
+
+def backup_database():
+ """
+ Safe database backup using SQLite's built-in backup API.
+ Unlike shutil.copy2, this handles active connections and WAL mode correctly,
+ producing a consistent, non-corrupted backup every time.
+ """
+ project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ db_file = os.path.join(project_root, "lab_database.db")
+ backup_dir = os.path.join(project_root, "backups")
+
+ if not os.path.exists(db_file):
+ print(f"❌ Error: Database file '{db_file}' not found.")
+ return False
+
+ if not os.path.exists(backup_dir):
+ os.makedirs(backup_dir)
+ print(f"📁 Created backup directory: {backup_dir}")
+
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ backup_file = os.path.join(backup_dir, f"lab_database_{timestamp}.db")
+
+ try:
+ # Connect to the live database
+ source = sqlite3.connect(db_file)
+ # Connect to the backup destination
+ dest = sqlite3.connect(backup_file)
+
+ # Use SQLite's built-in backup API — safe even during active writes
+ source.backup(dest)
+
+ dest.close()
+ source.close()
+
+ size_mb = os.path.getsize(backup_file) / (1024 * 1024)
+ print(f"✅ Success: Database backed up to {backup_file} ({size_mb:.2f} MB)")
+
+ # Cleanup: keep only last 30 backups
+ cleanup_old_backups(backup_dir, keep=30)
+
+ return True
+ except Exception as e:
+ print(f"❌ Error during backup: {e}")
+ return False
+
+def cleanup_old_backups(backup_dir, keep=30):
+ """Remove old backups, keeping only the most recent 'keep' files."""
+ try:
+ backups = sorted(
+ [f for f in os.listdir(backup_dir) if f.startswith("lab_database_") and f.endswith(".db")],
+ reverse=True
+ )
+ for old_backup in backups[keep:]:
+ os.remove(os.path.join(backup_dir, old_backup))
+ print(f"🗑️ Removed old backup: {old_backup}")
+ except Exception as e:
+ print(f"⚠️ Cleanup warning: {e}")
+
+if __name__ == "__main__":
+ backup_database()
diff --git a/tools/clean_patients.py b/tools/clean_patients.py
new file mode 100644
index 0000000000000000000000000000000000000000..0271abb3e91df51d3109184d3bd0c1fed0be1076
--- /dev/null
+++ b/tools/clean_patients.py
@@ -0,0 +1,147 @@
+"""
+NexLab LIS — Clean Patients Tool
+=================================
+Deletes ALL patients and their related data from the database.
+
+Affected tables (deleted in order):
+ 1. ResultDetail (child of Result)
+ 2. Result (child of Order)
+ 3. Payment (child of PatientVisit)
+ 4. Attachment (child of Patient)
+ 5. Order (child of Patient / PatientVisit)
+ 6. PatientVisit (child of Patient)
+ 7. Patient
+
+NOT affected:
+ - Users, Departments, Tests, Devices, Parameters, Packages, Partners
+ - Provinces, Regions, LabInfo, PrintTemplates
+ - Formulas, Supplies, Inventory, CalControl
+ - AuditLog, ActivityLog, DeletedRecord (historical records preserved)
+ - Chat, Messages, Expenses
+
+Usage:
+ python tools/clean_patients.py
+"""
+
+import sys
+import os
+
+# Ensure project root is in the path
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from sqlmodel import Session, select, func
+from app.database import engine
+from app.models import (
+ Patient, PatientVisit, Order, Result, ResultDetail,
+ Payment, Attachment,
+)
+
+
+def count_records(session):
+ """Count all patient-related records."""
+ counts = {
+ "Patient": session.exec(select(func.count(Patient.id))).one(),
+ "PatientVisit": session.exec(select(func.count(PatientVisit.id))).one(),
+ "Order": session.exec(select(func.count(Order.id))).one(),
+ "Result": session.exec(select(func.count(Result.id))).one(),
+ "ResultDetail": session.exec(select(func.count(ResultDetail.id))).one(),
+ "Payment": session.exec(select(func.count(Payment.id))).one(),
+ "Attachment": session.exec(select(func.count(Attachment.id))).one(),
+ }
+ return counts
+
+
+def clean_patients():
+ """Delete all patient data in the correct FK order."""
+
+ with Session(engine) as session:
+ # --- Show what will be deleted ---
+ counts = count_records(session)
+ total = sum(counts.values())
+
+ if total == 0:
+ print("\n No patient data found. The system is already clean.")
+ return
+
+ print("\n ============================================")
+ print(" NexLab LIS - Clean Patients Tool")
+ print(" ============================================")
+ print()
+ print(" The following records will be PERMANENTLY deleted:\n")
+ for table, count in counts.items():
+ print(f" {table:<20} {count:>6} records")
+ print(f" {'':-<20} {'':->6}---------")
+ print(f" {'TOTAL':<20} {total:>6} records")
+ print()
+
+ # --- Safety confirmation ---
+ print(" WARNING: This action is IRREVERSIBLE!")
+ print(" Tip: Run 'python tools/backup_db.py' first to create a backup.\n")
+
+ confirm = input(" Type 'DELETE ALL PATIENTS' to confirm: ").strip()
+ if confirm != "DELETE ALL PATIENTS":
+ print("\n Cancelled. No data was deleted.")
+ return
+
+ # --- Delete in FK order (children first) ---
+ print("\n Deleting records...")
+
+ # 1. ResultDetail (depends on Result)
+ deleted = session.exec(select(ResultDetail)).all()
+ for r in deleted:
+ session.delete(r)
+ print(f" ResultDetail: {len(deleted)} deleted")
+
+ # 2. Result (depends on Order)
+ deleted = session.exec(select(Result)).all()
+ for r in deleted:
+ session.delete(r)
+ print(f" Result: {len(deleted)} deleted")
+
+ # 3. Payment (depends on PatientVisit / Patient)
+ deleted = session.exec(select(Payment)).all()
+ for r in deleted:
+ session.delete(r)
+ print(f" Payment: {len(deleted)} deleted")
+
+ # 4. Attachment (depends on Patient)
+ deleted = session.exec(select(Attachment)).all()
+ for r in deleted:
+ session.delete(r)
+ print(f" Attachment: {len(deleted)} deleted")
+
+ # 5. Order (depends on Patient / PatientVisit)
+ deleted = session.exec(select(Order)).all()
+ for r in deleted:
+ session.delete(r)
+ print(f" Order: {len(deleted)} deleted")
+
+ # 6. PatientVisit (depends on Patient)
+ deleted = session.exec(select(PatientVisit)).all()
+ for r in deleted:
+ session.delete(r)
+ print(f" PatientVisit: {len(deleted)} deleted")
+
+ # 7. Patient
+ deleted = session.exec(select(Patient)).all()
+ for r in deleted:
+ session.delete(r)
+ print(f" Patient: {len(deleted)} deleted")
+
+ # --- Commit ---
+ session.commit()
+ print("\n All patient data has been deleted successfully.")
+
+ # --- Verify ---
+ remaining = count_records(session)
+ total_remaining = sum(remaining.values())
+ if total_remaining == 0:
+ print(" Verification: OK - all patient tables are empty.")
+ else:
+ print(f" WARNING: {total_remaining} records still remain. Check for orphaned data.")
+
+ print()
+
+
+if __name__ == "__main__":
+ clean_patients()
diff --git a/tools/excel_files/Departments.xlsx b/tools/excel_files/Departments.xlsx
new file mode 100644
index 0000000000000000000000000000000000000000..58c0280d1c4fcbe8ce1139e4b2c6d427c319ecad
Binary files /dev/null and b/tools/excel_files/Departments.xlsx differ
diff --git a/tools/excel_files/Devices.xlsx b/tools/excel_files/Devices.xlsx
new file mode 100644
index 0000000000000000000000000000000000000000..db3cc74133ecd3768746c083cf2272fa46f5b1e6
Binary files /dev/null and b/tools/excel_files/Devices.xlsx differ
diff --git a/tools/excel_files/Ranges.xlsx b/tools/excel_files/Ranges.xlsx
new file mode 100644
index 0000000000000000000000000000000000000000..fcb1ad937ea710d6417de35c1842596b6e973c1c
Binary files /dev/null and b/tools/excel_files/Ranges.xlsx differ
diff --git a/tools/excel_files/ReportNote.xlsx b/tools/excel_files/ReportNote.xlsx
new file mode 100644
index 0000000000000000000000000000000000000000..c963c91098597af7efc32307d09adbf5ab88b001
Binary files /dev/null and b/tools/excel_files/ReportNote.xlsx differ
diff --git a/tools/excel_files/SampleType.xlsx b/tools/excel_files/SampleType.xlsx
new file mode 100644
index 0000000000000000000000000000000000000000..e8a66f6f634b3c412864a463b3339532d5c800c8
Binary files /dev/null and b/tools/excel_files/SampleType.xlsx differ
diff --git a/tools/excel_files/Tests.xlsx b/tools/excel_files/Tests.xlsx
new file mode 100644
index 0000000000000000000000000000000000000000..9fdfbbd637a14032e186c61108a623cc0d987ab0
Binary files /dev/null and b/tools/excel_files/Tests.xlsx differ
diff --git a/tools/excel_files/parmeters.xlsx b/tools/excel_files/parmeters.xlsx
new file mode 100644
index 0000000000000000000000000000000000000000..4083ced7aa071425efe9ad0b61798473277654c8
Binary files /dev/null and b/tools/excel_files/parmeters.xlsx differ
diff --git a/tools/schema_audit.py b/tools/schema_audit.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a3626f6257975bcbc3c45f47b6fd9e534ee5e76
--- /dev/null
+++ b/tools/schema_audit.py
@@ -0,0 +1,64 @@
+"""Schema audit: compare model definitions vs actual database columns."""
+import sys, os
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+import sqlite3
+from sqlmodel import SQLModel
+# Import all models to register them
+from app.models import *
+
+project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+DB_PATH = os.path.join(project_root, "lab_database.db")
+conn = sqlite3.connect(DB_PATH)
+
+# 1. Get DB schema
+db_schema = {}
+tables = [r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").fetchall()]
+for t in tables:
+ cols = set(r[1] for r in conn.execute(f"PRAGMA table_info(\"{t}\")").fetchall())
+ db_schema[t.lower()] = cols
+
+# 2. Get model schema
+model_schema = {}
+for table_name, table_obj in SQLModel.metadata.tables.items():
+ model_schema[table_name.lower()] = set(col.name for col in table_obj.columns)
+
+# 3. Compare
+print("=" * 60)
+print(" NexLab Schema Audit: Models vs Database")
+print("=" * 60)
+
+issues = []
+
+# Tables in models but not in DB
+for table in sorted(model_schema.keys()):
+ if table not in db_schema:
+ issues.append(f"MISSING TABLE: '{table}' exists in models but NOT in database")
+ print(f"\n[MISSING TABLE] {table}")
+ print(f" Columns needed: {sorted(model_schema[table])}")
+
+# Columns comparison
+for table in sorted(model_schema.keys()):
+ if table in db_schema:
+ model_cols = model_schema[table]
+ db_cols = db_schema[table]
+
+ missing_in_db = model_cols - db_cols
+ extra_in_db = db_cols - model_cols
+
+ if missing_in_db or extra_in_db:
+ print(f"\n[MISMATCH] {table}")
+ for col in sorted(missing_in_db):
+ issues.append(f"MISSING COLUMN: {table}.{col}")
+ print(f" MISSING in DB: {col}")
+ for col in sorted(extra_in_db):
+ print(f" EXTRA in DB (not in model): {col}")
+
+if not issues:
+ print("\n [OK] All models match the database schema perfectly!")
+else:
+ print(f"\n{'=' * 60}")
+ print(f" TOTAL ISSUES: {len(issues)}")
+ print(f"{'=' * 60}")
+
+conn.close()
diff --git a/tools/seeding.py b/tools/seeding.py
new file mode 100644
index 0000000000000000000000000000000000000000..21b16efa625b4c6fb279f3262c65b09bce4005b9
--- /dev/null
+++ b/tools/seeding.py
@@ -0,0 +1,576 @@
+"""
+LIS V1 → V2 Migration / Seeding Script (FIXED)
+=================================================
+Seeds in order:
+ 1. Parameters
+ 2. Departments
+ 3. SampleTypes
+ 4. Devices (V1 "Methods")
+ 5. ReportNotes (V1 "Notes") – "None" inserted first as id=1
+ 6. Tests
+ 7. Ranges (V1 "TestRange")
+
+Key fix applied
+───────────────
+• PRAGMA foreign_keys is turned OFF for the duration of the migration.
+ This prevents SQLite from silently dropping (INSERT OR IGNORE) rows
+ whose created_by=1 FK cannot be resolved until a User row exists,
+ which previously left earlier tables empty and caused the
+ "FOREIGN KEY constraint failed" error on the TestDefinition insert.
+ Data integrity is guaranteed by the old→new ID maps built in code.
+• Ranges that reference ParameterIds absent from parmeters.xlsx are
+ inserted with parameter_id = NULL (orphaned V1 records).
+• Row-level error reporting: any single-row failure is printed with the
+ offending row data rather than aborting the whole batch.
+"""
+
+import os
+import sqlite3
+import pandas as pd
+from datetime import datetime
+
+# ─────────────────────────────────────────────
+# CONFIG – resolved dynamically relative to project root
+# ─────────────────────────────────────────────
+project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+DB_PATH = os.path.join(project_root, "lab_database.db")
+EXCEL_DIR = os.path.join(project_root, "excel_files")
+
+NOW = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+CREATED_BY = 1
+
+
+# ── helpers ──────────────────────────────────
+
+def xls(filename: str) -> pd.DataFrame:
+ path = os.path.join(EXCEL_DIR, filename)
+ df = pd.read_excel(path)
+ df.columns = df.columns.str.strip()
+ return df
+
+
+def clean(val):
+ if val is None:
+ return None
+ s = str(val).strip()
+ return None if s.lower() in ("", "nan", "none", "null") else s
+
+
+def gender_map(v) -> str:
+ return {1: "male", 2: "female", 3: "both"}.get(int(v), "both")
+
+
+def age_unit_map(v) -> str:
+ return {1: "year", 2: "month", 3: "day"}.get(int(v), "year")
+
+
+def range_type_map(v) -> str:
+ return {1: "number", 2: "text"}.get(int(v), "number")
+
+
+def opt_float(val):
+ try:
+ f = float(val)
+ return None if pd.isna(f) else f
+ except (TypeError, ValueError):
+ return None
+
+
+def safe_executemany(cur, sql: str, rows: list, label: str) -> int:
+ """
+ Insert rows one-by-one so a single bad row is reported and skipped
+ instead of aborting the whole batch. Returns the number inserted.
+ """
+ inserted = 0
+ for row in rows:
+ try:
+ cur.execute(sql, row)
+ inserted += 1
+ except sqlite3.IntegrityError as exc:
+ print(f" ⚠️ Skipped {label} row (IntegrityError: {exc}): {row[:4]}")
+ except Exception as exc:
+ print(f" ⚠️ Skipped {label} row (Error: {exc}): {row[:4]}")
+ return inserted
+
+
+# ── main ─────────────────────────────────────
+
+def main():
+ conn = sqlite3.connect(DB_PATH)
+
+ # ──────────────────────────────────────────────────────────────────
+ # CRITICAL FIX: disable FK enforcement for the migration.
+ # All FK integrity is enforced by the old→new ID maps in this script.
+ # Re-enabled at the very end after all data is committed.
+ # ──────────────────────────────────────────────────────────────────
+ conn.execute("PRAGMA foreign_keys = OFF;")
+ cur = conn.cursor()
+
+ # ══════════════════════════════════════════
+ # 1. PARAMETERS
+ # ══════════════════════════════════════════
+ print("\n── 1. Seeding Parameters ──")
+ df = xls("parmeters.xlsx")
+ df = df.dropna(subset=["ParameterName"])
+ df = df[df["ParameterName"].astype(str).str.strip() != ""]
+
+ param_old_to_new: dict[int, int] = {}
+ new_id = 1
+ rows = []
+
+ for _, r in df.iterrows():
+ old_id = int(r["ParameterId"])
+ param_old_to_new[old_id] = new_id
+ rows.append((
+ new_id,
+ str(r["ParameterName"]).strip(),
+ str(r["ShortName"]).strip() if clean(r["ShortName"]) else str(r["ParameterName"]).strip(),
+ 1 if int(r["IsHeader"]) == 1 else 0,
+ CREATED_BY, NOW,
+ None, None,
+ None, None,
+ ))
+ new_id += 1
+
+ sql = """
+ INSERT OR IGNORE INTO parameter
+ (id, parameter_name, parameter_short_name, is_header,
+ created_by, created_at, edited_by, edited_at, deleted_by, deleted_at)
+ VALUES (?,?,?,?,?,?,?,?,?,?)
+ """
+ inserted = safe_executemany(cur, sql, rows, "parameter")
+ conn.commit()
+ print(f" ✅ {inserted} / {len(rows)} parameters inserted.")
+
+ # ══════════════════════════════════════════
+ # 2. DEPARTMENTS
+ # ══════════════════════════════════════════
+ print("\n── 2. Seeding Departments ──")
+ df = xls("Departments.xlsx")
+ df = df.dropna(subset=["DepartmentName"])
+
+ dept_old_to_new: dict[int, int] = {}
+ new_id = 1
+ rows = []
+
+ for _, r in df.iterrows():
+ old_id = int(r["DepartmentId"])
+ dept_old_to_new[old_id] = new_id
+ rows.append((
+ new_id,
+ str(r["DepartmentName"]).strip(),
+ clean(r["DepartmentNote"]),
+ 1,
+ CREATED_BY, NOW,
+ None, None,
+ None, None,
+ None, None,
+ None, None,
+ ))
+ new_id += 1
+
+ sql = """
+ INSERT OR IGNORE INTO department
+ (id, department_name, department_note, is_active,
+ created_by, created_at, edited_by, edited_at,
+ deleted_by, deleted_at, activated_by, activated_at,
+ deactivated_by, deactivated_at)
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
+ """
+ inserted = safe_executemany(cur, sql, rows, "department")
+ conn.commit()
+ print(f" ✅ {inserted} / {len(rows)} departments inserted.")
+
+ # ══════════════════════════════════════════
+ # 3. SAMPLE TYPES
+ # ══════════════════════════════════════════
+ print("\n── 3. Seeding Sample Types ──")
+ df = xls("SampleType.xlsx")
+ df = df.dropna(subset=["SampleTypeName"])
+
+ sample_old_to_new: dict[int, int] = {}
+ new_id = 1
+ rows = []
+
+ for _, r in df.iterrows():
+ old_id = int(r["SampleTypeId"])
+ sample_old_to_new[old_id] = new_id
+ rows.append((
+ new_id,
+ str(r["SampleTypeName"]).strip(),
+ clean(r["SampleTypeNote"]),
+ 1,
+ CREATED_BY, NOW,
+ None, None,
+ None, None,
+ None, None,
+ None, None,
+ ))
+ new_id += 1
+
+ sql = """
+ INSERT OR IGNORE INTO sampletype
+ (id, sample_name, sample_note, is_active,
+ created_by, created_at, edited_by, edited_at,
+ deleted_by, deleted_at, activated_by, activated_at,
+ deactivated_by, deactivated_at)
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
+ """
+ inserted = safe_executemany(cur, sql, rows, "sampletype")
+ conn.commit()
+ print(f" ✅ {inserted} / {len(rows)} sample types inserted.")
+
+ # ══════════════════════════════════════════
+ # 4. DEVICES (V1 "Methods")
+ # ══════════════════════════════════════════
+ print("\n── 4. Seeding Devices (from V1 Methods) ──")
+ df = xls("Devices.xlsx")
+ df = df.dropna(subset=["MethodName"])
+
+ device_old_to_new: dict[int, int] = {}
+ new_id = 1
+ rows = []
+
+ for _, r in df.iterrows():
+ old_id = int(r["MethodId"])
+ device_old_to_new[old_id] = new_id
+ rows.append((
+ new_id,
+ str(r["MethodName"]).strip(),
+ "N/A",
+ NOW,
+ "N/A",
+ "N/A",
+ clean(r["MethodNote"]),
+ 1,
+ CREATED_BY, NOW,
+ None, None,
+ None, None,
+ None, None,
+ None, None,
+ ))
+ new_id += 1
+
+ sql = """
+ INSERT OR IGNORE INTO device
+ (id, device_name, serial_number, install_date,
+ installer_name, installer_phone, note, is_active,
+ created_by, created_at, edited_by, edited_at,
+ deleted_by, deleted_at, activated_by, activated_at,
+ deactivated_by, deactivated_at)
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
+ """
+ inserted = safe_executemany(cur, sql, rows, "device")
+ conn.commit()
+ print(f" ✅ {inserted} / {len(rows)} devices inserted.")
+
+ # ══════════════════════════════════════════
+ # 5. REPORT NOTES (V1 "Note")
+ # "None" is forced to be id=1
+ # ══════════════════════════════════════════
+ print("\n── 5. Seeding Report Notes ──")
+ df = xls("ReportNote.xlsx")
+ df = df.dropna(subset=["NoteName"])
+
+ mask_none = df["NoteName"].astype(str).str.strip().str.lower() == "none"
+ df_ordered = pd.concat(
+ [df[mask_none], df[~mask_none].sort_values("NoteId")],
+ ignore_index=True,
+ )
+
+ note_old_to_new: dict[int, int] = {}
+ new_id = 1
+ rows = []
+
+ for _, r in df_ordered.iterrows():
+ old_id = int(r["NoteId"])
+ note_old_to_new[old_id] = new_id
+ rows.append((
+ new_id,
+ str(r["NoteName"]).strip(),
+ clean(r["TheNote"]) or "",
+ 1,
+ CREATED_BY, NOW,
+ None, None,
+ None, None,
+ ))
+ new_id += 1
+
+ sql = """
+ INSERT OR IGNORE INTO reportnote
+ (id, note_name, note_content, is_active,
+ created_by, created_at, edited_by, edited_at,
+ deleted_by, deleted_at)
+ VALUES (?,?,?,?,?,?,?,?,?,?)
+ """
+ inserted = safe_executemany(cur, sql, rows, "reportnote")
+ conn.commit()
+ print(f" ✅ {inserted} / {len(rows)} report notes inserted (id=1 → 'None').")
+
+ # ══════════════════════════════════════════
+ # 6. TESTS
+ # ══════════════════════════════════════════
+ print("\n── 6. Seeding Tests ──")
+ df = xls("Tests.xlsx")
+ df = df.dropna(subset=["TestName"])
+
+ test_old_to_new: dict[int, int] = {}
+ new_id = 1
+ rows = []
+
+ for _, r in df.iterrows():
+ old_id = int(r["TestId"])
+ old_dept_id = int(r["DepartmentId"])
+ old_sample_id = int(r["SampleTypeId"])
+ old_note_id = int(r["NoteId"]) if clean(r["NoteId"]) else None
+
+ new_dept_id = dept_old_to_new.get(old_dept_id)
+ new_sample_id = sample_old_to_new.get(old_sample_id)
+ new_note_id = note_old_to_new.get(old_note_id) if old_note_id else None
+
+ if new_dept_id is None:
+ print(f" ⚠️ TestId={old_id} skipped: DepartmentId={old_dept_id} not found in map.")
+ continue
+ if new_sample_id is None:
+ print(f" ⚠️ TestId={old_id} skipped: SampleTypeId={old_sample_id} not found in map.")
+ continue
+
+ test_old_to_new[old_id] = new_id
+ rows.append((
+ new_id,
+ str(r["TestName"]).strip(),
+ str(r["ShortTestName"]).strip() if clean(r["ShortTestName"]) else str(r["TestName"]).strip(),
+ new_dept_id,
+ new_sample_id,
+ new_note_id,
+ float(r["Price"]) if clean(r["Price"]) else 0.0,
+ clean(r["TestNotes"]),
+ clean(r["TestConditions"]),
+ 1,
+ CREATED_BY, NOW,
+ None, None,
+ None, None,
+ ))
+ new_id += 1
+
+ sql = """
+ INSERT OR IGNORE INTO testdefinition
+ (id, test_name, test_short_name, department_id, sample_type_id,
+ report_note_id, price, test_note, test_condition, is_available,
+ created_by, created_at, edited_by, edited_at, deleted_by, deleted_at)
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
+ """
+ inserted = safe_executemany(cur, sql, rows, "testdefinition")
+ conn.commit()
+ print(f" ✅ {inserted} / {len(rows)} tests inserted.")
+
+ # ══════════════════════════════════════════
+ # 7. TEST-PARAMETER LINKS (from Ranges)
+ # Source: unique (TestId, ParameterId) pairs in Ranges.xlsx
+ # where ParameterId != 0 and ParameterId exists in parmeters.xlsx
+ # ══════════════════════════════════════════
+ print("\n── 7. Seeding Test-Parameter links ──")
+ df_ranges = xls("Ranges.xlsx")
+
+ seen_tp = set() # (new_test_id, new_param_id) dedup
+ rows = []
+ new_id = 1
+ tp_skip_test = 0
+ tp_skip_param = 0
+
+ for _, r in df_ranges.iterrows():
+ old_test_id = int(r["TestId"])
+ old_param_id = int(r["ParameterId"])
+
+ if old_param_id == 0:
+ continue # test-level range, no parameter link
+
+ new_test_id = test_old_to_new.get(old_test_id)
+ if new_test_id is None:
+ tp_skip_test += 1
+ continue
+
+ new_param_id = param_old_to_new.get(old_param_id)
+ if new_param_id is None:
+ tp_skip_param += 1 # orphaned V1 parameter — skip
+ continue
+
+ pair = (new_test_id, new_param_id)
+ if pair in seen_tp:
+ continue # already added this link
+ seen_tp.add(pair)
+
+ rows.append((new_id, new_test_id, new_param_id))
+ new_id += 1
+
+ sql = """
+ INSERT OR IGNORE INTO testparameter (id, test_id, parameter_id)
+ VALUES (?,?,?)
+ """
+ inserted = safe_executemany(cur, sql, rows, "testparameter")
+ conn.commit()
+ if tp_skip_test:
+ print(f" ℹ️ {tp_skip_test} rows skipped (TestId not in test map).")
+ if tp_skip_param:
+ print(f" ℹ️ {tp_skip_param} rows skipped (ParameterId orphaned in V1).")
+ print(f" ✅ {inserted} / {len(rows)} test-parameter links inserted.")
+
+ # ══════════════════════════════════════════
+ # 8. TEST-DEVICE LINKS (from Ranges)
+ # Source: unique (TestId, MethodId) pairs in Ranges.xlsx
+ # ══════════════════════════════════════════
+ print("\n── 8. Seeding Test-Device links ──")
+
+ seen_td = set() # (new_test_id, new_device_id) dedup
+ rows = []
+ new_id = 1
+ td_skip_test = 0
+ td_skip_device = 0
+
+ for _, r in df_ranges.iterrows():
+ old_test_id = int(r["TestId"])
+ old_device_id = int(r["MethodId"])
+
+ new_test_id = test_old_to_new.get(old_test_id)
+ if new_test_id is None:
+ td_skip_test += 1
+ continue
+
+ new_device_id = device_old_to_new.get(old_device_id)
+ if new_device_id is None:
+ td_skip_device += 1
+ continue
+
+ pair = (new_test_id, new_device_id)
+ if pair in seen_td:
+ continue
+ seen_td.add(pair)
+
+ rows.append((new_id, new_test_id, new_device_id))
+ new_id += 1
+
+ sql = """
+ INSERT OR IGNORE INTO testdevice (id, test_id, device_id)
+ VALUES (?,?,?)
+ """
+ inserted = safe_executemany(cur, sql, rows, "testdevice")
+ conn.commit()
+ if td_skip_test:
+ print(f" ℹ️ {td_skip_test} rows skipped (TestId not in test map).")
+ if td_skip_device:
+ print(f" ℹ️ {td_skip_device} rows skipped (MethodId not in device map).")
+ print(f" ✅ {inserted} / {len(rows)} test-device links inserted.")
+
+ # ══════════════════════════════════════════
+ # 9. RANGES (V1 "TestRange")
+ # ══════════════════════════════════════════
+ print("\n── 9. Seeding Ranges ──")
+ df = df_ranges # already loaded above — no need to re-read from disk
+
+ new_id = 1
+ rows = []
+ skipped = 0
+ orphaned_params = 0
+
+ for _, r in df.iterrows():
+ old_test_id = int(r["TestId"])
+ new_test_id = test_old_to_new.get(old_test_id)
+ if new_test_id is None:
+ skipped += 1
+ continue
+
+ old_param_id = int(r["ParameterId"])
+ if old_param_id == 0:
+ new_param_id = None
+ else:
+ new_param_id = param_old_to_new.get(old_param_id)
+ if new_param_id is None:
+ # ParameterId exists in Ranges but not in parmeters.xlsx
+ # (orphaned V1 record) — insert with parameter_id = NULL
+ orphaned_params += 1
+ new_param_id = None
+
+ old_device_id = int(r["MethodId"])
+ new_device_id = device_old_to_new.get(old_device_id)
+
+ rtype = range_type_map(r["RangeTypeId"])
+
+ rows.append((
+ new_id,
+ new_test_id,
+ new_param_id,
+ new_device_id,
+ clean(r["UnitName"]) or "",
+ gender_map(r["Gender"]),
+ int(r["AgeFrom"]),
+ int(r["AgeTo"]),
+ age_unit_map(r["AgeFromTypeId"]),
+ 1 if int(r["Fasting"]) == 1 else 0,
+ rtype,
+ opt_float(r["NormalFrom"]),
+ opt_float(r["NormalTo"]),
+ None, None, # vlow
+ None, None, # low
+ None, None, # midlow
+ None, None, # midhigh
+ None, None, # high
+ None, None, # vhigh
+ None, None, # panic
+ clean(r["TextRange"]) if rtype == "text" else None,
+ 1,
+ CREATED_BY, NOW,
+ None, None,
+ None, None,
+ ))
+ new_id += 1
+
+ sql = """
+ INSERT OR IGNORE INTO testrange
+ (id, test_id, parameter_id, device_id,
+ unit, gender_type, age_from, age_to, age_unit,
+ fasting_required, range_type,
+ normal_from, normal_to,
+ vlow_from, vlow_to, low_from, low_to,
+ midlow_from, midlow_to, midhigh_from, midhigh_to,
+ high_from, high_to, vhigh_from, vhigh_to,
+ panic_less_than, panic_more_than,
+ text_range,
+ is_active, created_by, created_at,
+ edited_by, edited_at, deleted_by, deleted_at)
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
+ """
+ inserted = safe_executemany(cur, sql, rows, "testrange")
+ conn.commit()
+
+ if skipped:
+ print(f" ℹ️ {skipped} ranges skipped (TestId had no matching test in V1 export).")
+ if orphaned_params:
+ print(f" ℹ️ {orphaned_params} ranges had orphaned ParameterIds → inserted with parameter_id=NULL.")
+ print(f" ✅ {inserted} / {len(rows)} ranges inserted.")
+
+ # ══════════════════════════════════════════
+ # Re-enable FK enforcement now that all data is in place
+ # ══════════════════════════════════════════
+ conn.execute("PRAGMA foreign_keys = ON;")
+ conn.close()
+
+ print("\n🎉 Migration complete — all tables seeded successfully.")
+ print("\n── Summary ──────────────────────────────")
+ print(f" Parameters : {len(param_old_to_new)}")
+ print(f" Departments : {len(dept_old_to_new)}")
+ print(f" Sample Types : {len(sample_old_to_new)}")
+ print(f" Devices : {len(device_old_to_new)}")
+ print(f" Report Notes : {len(note_old_to_new)} (id=1 is 'None')")
+ print(f" Tests : {len(test_old_to_new)}")
+ print(f" Test-Param links : {len(seen_tp)}")
+ print(f" Test-Device links : {len(seen_td)}")
+ print(f" Ranges : {new_id - 1} (inserted: {inserted})")
+
+
+if __name__ == "__main__":
+ try:
+ main()
+ except Exception as exc:
+ import traceback
+ print(f"\n💥 Migration failed: {exc}")
+ traceback.print_exc()
\ No newline at end of file
diff --git a/tools/set_admin_perm.py b/tools/set_admin_perm.py
new file mode 100644
index 0000000000000000000000000000000000000000..1cae11c32dfbe6d5a9be88e96a69bffd35534bbf
--- /dev/null
+++ b/tools/set_admin_perm.py
@@ -0,0 +1,82 @@
+import sqlite3
+import json
+import os
+
+def set_perms():
+ project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ db_path = os.path.join(project_root, 'lab_database.db')
+ conn = sqlite3.connect(db_path)
+ cursor = conn.cursor()
+
+ # Get admin ID
+ cursor.execute("SELECT id FROM user WHERE username='admin'")
+ row = cursor.fetchone()
+ if not row:
+ print("Admin user not found")
+ return
+ admin_id = row[0]
+
+ # Complete list of all pages and their buttons
+ pages = {
+ 'dashboard': [],
+ 'patient_registration': ["save_registration", "discount", "print_barcode", "print_receipt"],
+ 'patients': ["edit", "delete", "print_barcode", "result_entry"],
+ 'patient_edit': ["save", "print_barcode", "print_receipt", "discount"],
+ 'deleted_patients': ["restore", "view"],
+ 'deleted_tests': [],
+ 'patient_history': [],
+ 'patient_status': [],
+ 'result_entry': ["save", "authorize", "duplicate", "rerun", "no_sample"],
+ 'double_auth': ["double_authorize", "rerun", "unauthorize"],
+ 'no_sample': ["mark_no_sample", "receive_sample"],
+ 'print_barcode': ["print"],
+ 'barcode_designer': ["save"],
+ 'print_receipt': ["print"],
+ 'receipt_designer': ["save"],
+ 'print_results': ["print", "view"],
+ 'call_centre': ["mark_called", "send_whatsapp"],
+ 'result_designer': ["save"],
+ 'departments': ["create", "edit", "delete"],
+ 'sample_types': ["create", "edit", "delete"],
+ 'devices': ["create", "edit", "delete"],
+ 'parameters': ["create", "edit", "delete"],
+ 'report_notes': ["create", "edit", "delete"],
+ 'supplies': ["create", "edit", "delete"],
+ 'inventory': ["create", "edit", "delete"],
+ 'tests': ["create", "edit", "delete"],
+ 'formulas': ["create", "edit", "delete"],
+ 'test_ranges': ["create", "edit", "delete"],
+ 'test_result_types': ["create", "edit", "delete"],
+ 'packages': ["create", "edit", "delete"],
+ 'expenses_types': ["create", "edit", "delete"],
+ 'expenses_entry': ["create", "edit", "delete"],
+ 'discount_report': ["view"],
+ 'detailed_income': ["view"],
+ 'net_amounts': ["view"],
+ 'payment_records': ["view"],
+ 'patients_number': ["view"],
+ 'patient_region': ["view"],
+ 'tests_number': ["view"],
+ 'expenses_report': ["view", "edit", "delete"],
+ 'remain_report': ["view"],
+ 'partners': ["create", "edit", "delete"],
+ 'provinces': ["create", "edit", "delete"],
+ 'regions': ["create", "edit", "delete"],
+ 'lab_info': ["edit", "save"],
+ 'user_management': ["create", "edit", "delete"],
+ 'activity_logs': ["view"],
+ }
+
+ # Delete existing admin permissions and re-insert all
+ cursor.execute("DELETE FROM userpermission WHERE user_id = ?", (admin_id,))
+
+ for page, perms in pages.items():
+ cursor.execute("INSERT INTO userpermission (user_id, page_key, allowed_buttons) VALUES (?, ?, ?)",
+ (admin_id, page, json.dumps(perms)))
+
+ conn.commit()
+ conn.close()
+ print(f"Successfully updated admin permissions for {len(pages)} pages")
+
+if __name__ == "__main__":
+ set_perms()
diff --git a/update_system.bat b/update_system.bat
new file mode 100644
index 0000000000000000000000000000000000000000..31db0a01431cf7da396ef8046cf92f86eb66fc2d
--- /dev/null
+++ b/update_system.bat
@@ -0,0 +1,50 @@
+@echo off
+setlocal
+set "VENV_PATH=venv"
+set "PYTHON_EXE=%VENV_PATH%\Scripts\python.exe"
+
+echo ==========================================
+echo NexLab System Update Tool
+echo ==========================================
+echo.
+
+:: Step 1: Backup Database
+echo [Step 1/3] Backing up database...
+"%PYTHON_EXE%" tools\backup_db.py
+if %ERRORLEVEL% NEQ 0 (
+ echo ERROR: Database backup failed. Update cancelled for safety.
+ pause
+ exit /b %ERRORLEVEL%
+)
+echo.
+
+:: Step 2: Inform User about Code Updates
+echo [Step 2/3] Code Updates
+echo Please ensure you have copied the new system files into this folder.
+echo (If you are using Git, you would 'git pull' now.)
+echo.
+set /p confirm="Have you updated the system files? (y/n): "
+if /i "%confirm%" NEQ "y" (
+ echo Update paused. Please copy the new files and run this script again.
+ pause
+ exit /b 0
+)
+echo.
+
+:: Step 3: Run Migrations
+echo [Step 3/3] Running database migrations...
+"%PYTHON_EXE%" migrations\run_all.py
+if %ERRORLEVEL% NEQ 0 (
+ echo ERROR: Migrations failed. Please check the logs.
+ pause
+ exit /b %ERRORLEVEL%
+)
+echo.
+
+echo ==========================================
+echo System Update Completed Successfully!
+echo ==========================================
+echo.
+echo You can now restart the system using 'start_nexlab.bat'.
+echo.
+pause
diff --git a/upload_to_hf.py b/upload_to_hf.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c1d152c467917f4b95e787d7b6e35a6e7635a98
--- /dev/null
+++ b/upload_to_hf.py
@@ -0,0 +1,60 @@
+# upload_to_hf.py
+# ===================================================================
+# Helper script to upload NexLab to Hugging Face Spaces.
+# Bypasses Git to avoid committing large executables like NexPrint.exe.
+# ===================================================================
+
+import os
+import sys
+
+def upload():
+ try:
+ from huggingface_hub import HfApi
+ except ImportError:
+ print("huggingface_hub library is not installed.")
+ print("Installing it now via pip...")
+ import subprocess
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "huggingface_hub"])
+ from huggingface_hub import HfApi
+
+ # Ask the user for their token if not already stored
+ print("\n--- Hugging Face Spaces Direct Uploader ---")
+ token = input("Enter your Hugging Face Write Token: ").strip()
+ if not token:
+ print("❌ Token is required. You can get one from: https://huggingface.co/settings/tokens")
+ return
+
+ repo_id = "alisaleem97/NexLab_System"
+ print(f"Uploading files to Space: {repo_id}...")
+
+ api = HfApi()
+
+ # Ignore patterns to skip local virtual environments, large files, and Git history
+ ignore_patterns = [
+ "print_client/**",
+ ".git/**",
+ "venv/**",
+ ".env",
+ "**/*.log",
+ "**/__pycache__/**",
+ "backups/**",
+ "tmp/**",
+ "NexLab_Published/**"
+ ]
+
+ try:
+ api.upload_folder(
+ folder_path=".",
+ repo_id=repo_id,
+ repo_type="space",
+ token=token,
+ ignore_patterns=ignore_patterns
+ )
+ print("\n🎉 Upload Completed Successfully!")
+ print("Your Space will now build and start automatically.")
+ print(f"Visit it at: https://huggingface.co/spaces/{repo_id}")
+ except Exception as e:
+ print(f"\n❌ Error during upload: {e}")
+
+if __name__ == "__main__":
+ upload()
diff --git a/uploads/Cairo.ttf b/uploads/Cairo.ttf
new file mode 100644
index 0000000000000000000000000000000000000000..4edf50949ddb9fc0baf2b4086e59962da3371a02
--- /dev/null
+++ b/uploads/Cairo.ttf
@@ -0,0 +1,1471 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {% for row in results %}
+ {% if row.type == 'parent' %}
+ Test / Parameter
+ Result
+ Unit
+ Ref. Range
+ Flag
+
+
+ {% elif row.type == 'child' %}
+ {{ row.test_name }}
+
+
+ {% else %}
+ {{ row.parameter_name }}
+ {{ row.result_value }}
+ {{ row.unit }}
+ {{ row.range }}
+
+ {{ row.flag or '' }}
+
+
+
+ {% endif %}
+ {% endfor %}
+
+ {{ row.test_name }}
+ {{ row.result_value }}
+ {{ row.unit }}
+ {{ row.range }}
+
+ {{ row.flag or '' }}
+
+ Navigation Menu
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+