Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +11 -0
- .gitignore +59 -0
- Dockerfile +55 -0
- System_Update_Guide.md +53 -0
- app/__init__.py +2 -0
- app/config.py +68 -0
- app/database.py +51 -0
- app/main.py +146 -0
- app/middleware.py +45 -0
- app/models/__init__.py +35 -0
- app/models/audit.py +39 -0
- app/models/department.py +92 -0
- app/models/finance.py +42 -0
- app/models/formula.py +43 -0
- app/models/geography.py +35 -0
- app/models/hr.py +48 -0
- app/models/inventory.py +48 -0
- app/models/lab.py +61 -0
- app/models/messaging.py +52 -0
- app/models/order.py +71 -0
- app/models/package.py +49 -0
- app/models/patient.py +93 -0
- app/models/test.py +120 -0
- app/models/user.py +39 -0
- app/routes/__init__.py +2 -0
- app/routes/template_helpers.py +94 -0
- app/services/__init__.py +2 -0
- app/services/audit_service.py +74 -0
- app/services/auth_service.py +48 -0
- app/services/barcode_image_service.py +206 -0
- app/services/barcode_service.py +20 -0
- app/services/patient_service.py +180 -0
- app/services/pdf_service.py +172 -0
- app/services/permission_service.py +44 -0
- backup_db.py +63 -0
- database.py +7 -0
- deployment_guide.md +43 -0
- device_interfacing/CBC/failed/alh.txt +23 -0
- device_interfacing/CBC/processed/20260426_204913_alh.txt +23 -0
- device_interfacing/device_watcher.py +517 -0
- excel_files/Departments.xlsx +0 -0
- excel_files/Devices.xlsx +0 -0
- excel_files/Ranges.xlsx +0 -0
- excel_files/ReportNote.xlsx +0 -0
- excel_files/SampleType.xlsx +0 -0
- excel_files/Tests.xlsx +0 -0
- excel_files/parmeters.xlsx +0 -0
- main.py +7 -0
- migrations/migrate_calcontrol.py +11 -0
- migrations/migrate_double_auth.py +39 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,14 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
static/vendor/font-awesome/webfonts/fa-brands-400.ttf filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
static/vendor/font-awesome/webfonts/fa-brands-400.woff2 filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
static/vendor/font-awesome/webfonts/fa-solid-900.ttf filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
static/vendor/font-awesome/webfonts/fa-solid-900.woff2 filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
static/vendor/fonts/Inter-300.ttf filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
static/vendor/fonts/Inter-400.ttf filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
static/vendor/fonts/Inter-500.ttf filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
static/vendor/fonts/Inter-600.ttf filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
static/vendor/fonts/Inter-700.ttf filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
uploads/attachments/14_e8137e8fb27f236b.pdf filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
uploads/chat_media/1ff26a15-52ee-4896-b8a9-1b2fd8f87d86.png filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
*.so
|
| 6 |
+
*.egg-info/
|
| 7 |
+
dist/
|
| 8 |
+
build/
|
| 9 |
+
*.egg
|
| 10 |
+
|
| 11 |
+
# Virtual Environment
|
| 12 |
+
venv/
|
| 13 |
+
.venv/
|
| 14 |
+
ENV/
|
| 15 |
+
|
| 16 |
+
# IDE
|
| 17 |
+
.idea/
|
| 18 |
+
.vscode/
|
| 19 |
+
*.swp
|
| 20 |
+
*.swo
|
| 21 |
+
*~
|
| 22 |
+
|
| 23 |
+
# Database files
|
| 24 |
+
*.db
|
| 25 |
+
*.db-journal
|
| 26 |
+
*.db-shm
|
| 27 |
+
*.db-wal
|
| 28 |
+
|
| 29 |
+
# Uploads & temp files
|
| 30 |
+
uploads/
|
| 31 |
+
tmp/
|
| 32 |
+
|
| 33 |
+
# OS
|
| 34 |
+
.DS_Store
|
| 35 |
+
Thumbs.db
|
| 36 |
+
desktop.ini
|
| 37 |
+
|
| 38 |
+
# Environment variables (SECRETS!)
|
| 39 |
+
.env
|
| 40 |
+
.env.local
|
| 41 |
+
|
| 42 |
+
# Logs
|
| 43 |
+
*.log
|
| 44 |
+
|
| 45 |
+
# Published output
|
| 46 |
+
NexLab_Published/
|
| 47 |
+
|
| 48 |
+
# Backups
|
| 49 |
+
backups/
|
| 50 |
+
|
| 51 |
+
# Binary archives
|
| 52 |
+
*.rar
|
| 53 |
+
*.zip
|
| 54 |
+
|
| 55 |
+
# Test/scratch files
|
| 56 |
+
test_*.py
|
| 57 |
+
test_*.html
|
| 58 |
+
scratch/
|
| 59 |
+
scratch.txt
|
Dockerfile
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use the official Python 3.11 slim image
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
+
|
| 4 |
+
# Install system dependencies required for Playwright (Chromium) and PDF generation
|
| 5 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 6 |
+
wget \
|
| 7 |
+
gnupg \
|
| 8 |
+
libnss3 \
|
| 9 |
+
libatk1.0-0 \
|
| 10 |
+
libatk-bridge2.0-0 \
|
| 11 |
+
libcups2 \
|
| 12 |
+
libdrm2 \
|
| 13 |
+
libxkbcommon0 \
|
| 14 |
+
libxcomposite1 \
|
| 15 |
+
libxdamage1 \
|
| 16 |
+
libxext6 \
|
| 17 |
+
libxfixes3 \
|
| 18 |
+
librandr2 \
|
| 19 |
+
libgbm1 \
|
| 20 |
+
libpango-1.0-0 \
|
| 21 |
+
libcairo2 \
|
| 22 |
+
libasound2 \
|
| 23 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 24 |
+
|
| 25 |
+
# Create a non-root user (required by Hugging Face Spaces and best practice for security)
|
| 26 |
+
RUN useradd -m -u 1000 user
|
| 27 |
+
WORKDIR /home/user/app
|
| 28 |
+
|
| 29 |
+
# Copy requirements first to leverage Docker cache
|
| 30 |
+
COPY --chown=user:user requirements.txt .
|
| 31 |
+
|
| 32 |
+
# Install Python packages and Playwright browsers
|
| 33 |
+
RUN pip install --no-cache-dir -r requirements.txt && \
|
| 34 |
+
playwright install chromium
|
| 35 |
+
|
| 36 |
+
# Copy the rest of the application files
|
| 37 |
+
COPY --chown=user:user . .
|
| 38 |
+
|
| 39 |
+
# Ensure directory permissions are correct for temporary files and uploads
|
| 40 |
+
RUN mkdir -p tmp uploads/attachments uploads/chat_media backups && \
|
| 41 |
+
chown -R user:user /home/user/app
|
| 42 |
+
|
| 43 |
+
# Switch to the non-root user
|
| 44 |
+
USER user
|
| 45 |
+
|
| 46 |
+
# Set environment variables
|
| 47 |
+
ENV PORT=7860
|
| 48 |
+
ENV DATABASE_URL=sqlite:///home/user/app/lab_database.db
|
| 49 |
+
ENV PYTHONUNBUFFERED=1
|
| 50 |
+
|
| 51 |
+
# Expose the port (Hugging Face Spaces uses 7860 by default)
|
| 52 |
+
EXPOSE 7860
|
| 53 |
+
|
| 54 |
+
# Command to run the application
|
| 55 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
System_Update_Guide.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NexLab System Update Guide
|
| 2 |
+
|
| 3 |
+
This guide ensures you can update your NexLab Laboratory Information System (LIS) without losing any patient data or system settings.
|
| 4 |
+
|
| 5 |
+
## 🕒 Best Practices
|
| 6 |
+
- Always update when the lab is quiet (e.g., end of the day).
|
| 7 |
+
- Ensure no one is currently using the system before starting.
|
| 8 |
+
- Keep a backup of your `lab_database.db` file in a safe location.
|
| 9 |
+
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
## 🚀 The Automatic Way (Recommended)
|
| 13 |
+
We have provided an automated tool to handle backups and database migrations for you.
|
| 14 |
+
|
| 15 |
+
1. **Close the System**: Stop the server (close the window opened by `start_nexlab.bat`).
|
| 16 |
+
2. **Run the Update Tool**: Double-click `update_system.bat`.
|
| 17 |
+
3. **Follow the Prompts**:
|
| 18 |
+
* The tool will automatically create a backup in the `backups/` folder.
|
| 19 |
+
* It will ask you to confirm that you have replaced the system files with the new version.
|
| 20 |
+
* It will automatically run all database migrations (`migrate_*.py`).
|
| 21 |
+
4. **Restart**: Once completed, run `start_nexlab.bat` as usual.
|
| 22 |
+
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
## 🛠️ The Manual Way (Step-by-Step)
|
| 26 |
+
If you prefer to perform the update manually, follow these steps exactly:
|
| 27 |
+
|
| 28 |
+
### 1. Backup your Database
|
| 29 |
+
- Go to your system folder (`lab_system`).
|
| 30 |
+
- Locate the file `lab_database.db`.
|
| 31 |
+
- Copy this file and paste it into a folder named `backups`. Rename it to something like `lab_database_backup_DATE.db`.
|
| 32 |
+
|
| 33 |
+
### 2. Replace System Files
|
| 34 |
+
- Delete the old files (except for `lab_database.db`, `backups/`, and `venv/`).
|
| 35 |
+
- Copy the new files from the update package into the `lab_system` folder.
|
| 36 |
+
|
| 37 |
+
### 3. Run Database Migrations
|
| 38 |
+
- If the new system version includes new database columns or features, you must run the migration scripts.
|
| 39 |
+
- Open a Command Prompt in the folder.
|
| 40 |
+
- Type: `venv\Scripts\python.exe run_all_migrations.py`
|
| 41 |
+
- Press Enter.
|
| 42 |
+
|
| 43 |
+
### 4. Restart the Server
|
| 44 |
+
- Double-click `start_nexlab.bat` to bring the system back online.
|
| 45 |
+
|
| 46 |
+
---
|
| 47 |
+
|
| 48 |
+
## 🆘 Troubleshooting
|
| 49 |
+
- **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.
|
| 50 |
+
- **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`.
|
| 51 |
+
|
| 52 |
+
> [!WARNING]
|
| 53 |
+
> DO NOT delete or overwrite `lab_database.db` during an update. This file contains all your data.
|
app/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/__init__.py
|
| 2 |
+
# NexLab LIS Application Package
|
app/config.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/config.py
|
| 2 |
+
# Centralised configuration — single source of truth for all settings.
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import logging
|
| 6 |
+
|
| 7 |
+
# Load .env file if python-dotenv is available
|
| 8 |
+
try:
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
# Look for .env in project root (parent of app/)
|
| 11 |
+
_project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 12 |
+
_env_path = os.path.join(_project_root, ".env")
|
| 13 |
+
if os.path.exists(_env_path):
|
| 14 |
+
load_dotenv(_env_path)
|
| 15 |
+
except ImportError:
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 19 |
+
|
| 20 |
+
# ===========================
|
| 21 |
+
# SECRET KEY
|
| 22 |
+
# ===========================
|
| 23 |
+
_env_secret = os.environ.get("NEXLAB_SECRET_KEY")
|
| 24 |
+
if _env_secret:
|
| 25 |
+
SECRET_KEY = _env_secret
|
| 26 |
+
else:
|
| 27 |
+
import uuid
|
| 28 |
+
SECRET_KEY = uuid.uuid4().hex + uuid.uuid4().hex
|
| 29 |
+
logging.getLogger("nexlab.security").warning(
|
| 30 |
+
"NEXLAB_SECRET_KEY not set! Using auto-generated key. "
|
| 31 |
+
"Sessions will NOT persist across restarts. "
|
| 32 |
+
"Set NEXLAB_SECRET_KEY in .env for production use."
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# ===========================
|
| 36 |
+
# DATABASE
|
| 37 |
+
# ===========================
|
| 38 |
+
DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///./lab_database.db")
|
| 39 |
+
|
| 40 |
+
# If it is a relative sqlite URL, make it absolute relative to PROJECT_ROOT
|
| 41 |
+
if DATABASE_URL.startswith("sqlite:///"):
|
| 42 |
+
db_path = DATABASE_URL[10:]
|
| 43 |
+
if not (db_path.startswith("/") or db_path.startswith("\\") or (len(db_path) > 1 and db_path[1] == ":")):
|
| 44 |
+
if db_path.startswith("./") or db_path.startswith(".\\"):
|
| 45 |
+
db_path = db_path[2:]
|
| 46 |
+
abs_db_path = os.path.abspath(os.path.join(PROJECT_ROOT, db_path))
|
| 47 |
+
DATABASE_URL = f"sqlite:///{abs_db_path}"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# ===========================
|
| 51 |
+
# PATHS
|
| 52 |
+
# ===========================
|
| 53 |
+
TEMPLATE_DIR = os.path.join(PROJECT_ROOT, "templates")
|
| 54 |
+
STATIC_DIR = os.path.join(PROJECT_ROOT, "static")
|
| 55 |
+
UPLOAD_DIR = os.path.join(PROJECT_ROOT, "uploads")
|
| 56 |
+
TMP_DIR = os.path.join(PROJECT_ROOT, "tmp")
|
| 57 |
+
BACKUP_DIR = os.path.join(PROJECT_ROOT, "backups")
|
| 58 |
+
|
| 59 |
+
# ===========================
|
| 60 |
+
# SERVER
|
| 61 |
+
# ===========================
|
| 62 |
+
PORT = int(os.environ.get("PORT", 8000))
|
| 63 |
+
|
| 64 |
+
# ===========================
|
| 65 |
+
# PASSWORD HASHING
|
| 66 |
+
# ===========================
|
| 67 |
+
from passlib.context import CryptContext
|
| 68 |
+
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
app/database.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/database.py
|
| 2 |
+
# Database engine, session factory, and SQLite performance pragmas.
|
| 3 |
+
# Hardened for multi-user concurrent access (4+ PCs).
|
| 4 |
+
|
| 5 |
+
from sqlmodel import create_engine, SQLModel, Session
|
| 6 |
+
from sqlalchemy import event
|
| 7 |
+
from sqlalchemy.pool import StaticPool
|
| 8 |
+
|
| 9 |
+
from app.config import DATABASE_URL
|
| 10 |
+
|
| 11 |
+
# Create engine with StaticPool — optimal for SQLite with multi-threaded access.
|
| 12 |
+
# StaticPool uses a single connection that is reused across all threads,
|
| 13 |
+
# which is the safest strategy for SQLite + FastAPI (single worker).
|
| 14 |
+
engine = create_engine(
|
| 15 |
+
DATABASE_URL,
|
| 16 |
+
echo=False,
|
| 17 |
+
connect_args={"check_same_thread": False},
|
| 18 |
+
poolclass=StaticPool,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# Enable performance & concurrency PRAGMAs for every SQLite connection
|
| 23 |
+
@event.listens_for(engine, "connect")
|
| 24 |
+
def _set_sqlite_pragma(dbapi_connection, connection_record):
|
| 25 |
+
cursor = dbapi_connection.cursor()
|
| 26 |
+
cursor.execute("PRAGMA foreign_keys=ON")
|
| 27 |
+
# WAL mode: allows concurrent reads during writes (critical for multi-user)
|
| 28 |
+
cursor.execute("PRAGMA journal_mode=WAL")
|
| 29 |
+
# Busy timeout: wait up to 10 seconds instead of failing immediately on lock
|
| 30 |
+
# Increased from 5s for multi-PC environments
|
| 31 |
+
cursor.execute("PRAGMA busy_timeout=10000")
|
| 32 |
+
# Synchronous NORMAL: safe with WAL, faster than FULL
|
| 33 |
+
cursor.execute("PRAGMA synchronous=NORMAL")
|
| 34 |
+
# Cache size: ~32MB in memory for faster reads
|
| 35 |
+
cursor.execute("PRAGMA cache_size=-32000")
|
| 36 |
+
# Store temp tables in memory (faster joins and sorts)
|
| 37 |
+
cursor.execute("PRAGMA temp_store=MEMORY")
|
| 38 |
+
# Memory-mapped I/O: 256 MB for faster large reads
|
| 39 |
+
cursor.execute("PRAGMA mmap_size=268435456")
|
| 40 |
+
cursor.close()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def create_db_and_tables():
|
| 44 |
+
"""Create all tables defined by SQLModel metadata. Runs once at startup."""
|
| 45 |
+
SQLModel.metadata.create_all(engine)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_session():
|
| 49 |
+
"""Yield a database session for FastAPI dependency injection."""
|
| 50 |
+
with Session(engine) as session:
|
| 51 |
+
yield session
|
app/main.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/main.py
|
| 2 |
+
# NexLab LIS — FastAPI Application Entry Point
|
| 3 |
+
# Slim entry point: registers routers, lifecycle, middleware, error handling.
|
| 4 |
+
|
| 5 |
+
from fastapi import FastAPI, Request
|
| 6 |
+
from fastapi.staticfiles import StaticFiles
|
| 7 |
+
from fastapi.responses import JSONResponse, HTMLResponse
|
| 8 |
+
from sqlmodel import Session, select
|
| 9 |
+
from contextlib import asynccontextmanager
|
| 10 |
+
import os
|
| 11 |
+
import logging
|
| 12 |
+
|
| 13 |
+
from app.config import SECRET_KEY, pwd_context
|
| 14 |
+
from app.database import create_db_and_tables, engine
|
| 15 |
+
from app.models import User
|
| 16 |
+
from app.middleware import auth_middleware
|
| 17 |
+
|
| 18 |
+
# Import routers (from original routes/ directory — they still work via bridges)
|
| 19 |
+
from routes.auth import router as auth_router
|
| 20 |
+
from routes.departments import router as departments_router
|
| 21 |
+
from routes.tests import router as tests_router
|
| 22 |
+
from routes.geography import router as geography_router
|
| 23 |
+
from routes.patients import router as patients_router
|
| 24 |
+
from routes.printing import router as printing_router
|
| 25 |
+
from routes.api import router as api_router
|
| 26 |
+
from routes.results import router as results_router
|
| 27 |
+
from routes.double_auth import router as double_auth_router
|
| 28 |
+
from routes.call_centre import router as call_centre_router
|
| 29 |
+
from routes.history import router as history_router
|
| 30 |
+
from routes.patient_status import router as patient_status_router
|
| 31 |
+
from routes.users import router as users_router
|
| 32 |
+
from routes.attachments import router as attachments_router
|
| 33 |
+
from routes.expenses import router as expenses_router
|
| 34 |
+
from routes.reports import router as reports_router
|
| 35 |
+
from routes.messages import router as messages_router
|
| 36 |
+
from routes.websockets import router as websockets_router
|
| 37 |
+
from routes.supplies import router as supplies_router
|
| 38 |
+
from routes.inventory import router as inventory_router
|
| 39 |
+
from routes.cal_control import router as cal_control_router
|
| 40 |
+
from routes.hr import router as hr_router
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ===========================
|
| 44 |
+
# APP LIFESPAN (Startup/Shutdown)
|
| 45 |
+
# ===========================
|
| 46 |
+
@asynccontextmanager
|
| 47 |
+
async def lifespan(app: FastAPI):
|
| 48 |
+
# Startup: create tables
|
| 49 |
+
create_db_and_tables()
|
| 50 |
+
|
| 51 |
+
# Ensure required directories exist
|
| 52 |
+
for d in ["tmp", "uploads", "uploads/attachments", "uploads/chat_media"]:
|
| 53 |
+
os.makedirs(d, exist_ok=True)
|
| 54 |
+
|
| 55 |
+
# Seed admin user if none exists
|
| 56 |
+
with Session(engine) as session:
|
| 57 |
+
existing = session.exec(select(User).where(User.username == "admin")).first()
|
| 58 |
+
if not existing:
|
| 59 |
+
admin = User(
|
| 60 |
+
username="admin",
|
| 61 |
+
full_name="Administrator",
|
| 62 |
+
role="admin",
|
| 63 |
+
hashed_password=pwd_context.hash("admin123"),
|
| 64 |
+
is_active=True
|
| 65 |
+
)
|
| 66 |
+
session.add(admin)
|
| 67 |
+
session.commit()
|
| 68 |
+
print("WARNING: Default admin user created with password 'admin123'. Change this immediately in production!")
|
| 69 |
+
else:
|
| 70 |
+
print("[OK] Admin user already exists")
|
| 71 |
+
|
| 72 |
+
yield
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
app = FastAPI(title="NexLab LIS", lifespan=lifespan)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# ===========================
|
| 79 |
+
# GLOBAL ERROR HANDLERS — Crash-proof
|
| 80 |
+
# ===========================
|
| 81 |
+
@app.exception_handler(Exception)
|
| 82 |
+
async def global_exception_handler(request: Request, exc: Exception):
|
| 83 |
+
"""Catch all unhandled exceptions so the server NEVER crashes."""
|
| 84 |
+
logging.error(f"Unhandled error on {request.url.path}: {exc}", exc_info=True)
|
| 85 |
+
if request.url.path.startswith("/api/"):
|
| 86 |
+
return JSONResponse(
|
| 87 |
+
status_code=500,
|
| 88 |
+
content={"error": "Internal server error", "detail": str(exc)}
|
| 89 |
+
)
|
| 90 |
+
return HTMLResponse(
|
| 91 |
+
content=f"<h2>System Error</h2><p>An internal error occurred. The system is still running.</p><p><a href='/dashboard'>Return to Dashboard</a></p>",
|
| 92 |
+
status_code=500
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@app.exception_handler(404)
|
| 97 |
+
async def not_found_handler(request: Request, exc):
|
| 98 |
+
if request.url.path.startswith("/api/"):
|
| 99 |
+
return JSONResponse(status_code=404, content={"error": "Not found"})
|
| 100 |
+
return HTMLResponse(
|
| 101 |
+
content=f"<h2>Page Not Found</h2><p>The page you requested does not exist.</p><p><a href='/dashboard'>Return to Dashboard</a></p>",
|
| 102 |
+
status_code=404
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# ===========================
|
| 107 |
+
# AUTH MIDDLEWARE
|
| 108 |
+
# ===========================
|
| 109 |
+
@app.middleware("http")
|
| 110 |
+
async def _auth_middleware(request, call_next):
|
| 111 |
+
return await auth_middleware(request, call_next)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ===========================
|
| 115 |
+
# STATIC FILES
|
| 116 |
+
# ===========================
|
| 117 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 118 |
+
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
|
| 119 |
+
app.mount("/tmp", StaticFiles(directory="tmp"), name="tmp")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# ===========================
|
| 123 |
+
# INCLUDE ROUTERS
|
| 124 |
+
# ===========================
|
| 125 |
+
app.include_router(auth_router)
|
| 126 |
+
app.include_router(departments_router)
|
| 127 |
+
app.include_router(tests_router)
|
| 128 |
+
app.include_router(geography_router)
|
| 129 |
+
app.include_router(patients_router)
|
| 130 |
+
app.include_router(printing_router)
|
| 131 |
+
app.include_router(api_router)
|
| 132 |
+
app.include_router(results_router)
|
| 133 |
+
app.include_router(double_auth_router)
|
| 134 |
+
app.include_router(call_centre_router)
|
| 135 |
+
app.include_router(history_router)
|
| 136 |
+
app.include_router(patient_status_router)
|
| 137 |
+
app.include_router(users_router)
|
| 138 |
+
app.include_router(attachments_router)
|
| 139 |
+
app.include_router(expenses_router)
|
| 140 |
+
app.include_router(reports_router)
|
| 141 |
+
app.include_router(messages_router)
|
| 142 |
+
app.include_router(websockets_router)
|
| 143 |
+
app.include_router(supplies_router)
|
| 144 |
+
app.include_router(inventory_router)
|
| 145 |
+
app.include_router(cal_control_router)
|
| 146 |
+
app.include_router(hr_router)
|
app/middleware.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/middleware.py
|
| 2 |
+
# Auth middleware — protects all routes, extracted from main.py for clean SoC.
|
| 3 |
+
|
| 4 |
+
import hashlib
|
| 5 |
+
from starlette.responses import RedirectResponse as StarletteRedirect
|
| 6 |
+
|
| 7 |
+
from app.config import SECRET_KEY
|
| 8 |
+
from sqlmodel import Session
|
| 9 |
+
from app.database import engine
|
| 10 |
+
from app.services.auth_service import get_current_user
|
| 11 |
+
|
| 12 |
+
# Pre-compute the print token once at import time (not per-request)
|
| 13 |
+
PRINT_TOKEN = hashlib.sha256(SECRET_KEY.encode()).hexdigest()[:16]
|
| 14 |
+
|
| 15 |
+
# Paths that don't require authentication
|
| 16 |
+
PUBLIC_PATHS = ["/login", "/static/", "/tmp/", "/favicon.ico"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
async def auth_middleware(request, call_next):
|
| 20 |
+
"""HTTP middleware that enforces authentication on all non-public routes."""
|
| 21 |
+
path = request.url.path
|
| 22 |
+
is_public = any(path.startswith(p) for p in PUBLIC_PATHS)
|
| 23 |
+
|
| 24 |
+
# Allow local Headless Chrome to load assets for PDF generation
|
| 25 |
+
user_agent = request.headers.get("user-agent", "")
|
| 26 |
+
if "HeadlessChrome" in user_agent and request.client.host == "127.0.0.1":
|
| 27 |
+
is_public = True
|
| 28 |
+
|
| 29 |
+
# NexPrint token bypass for barcode/receipt printing
|
| 30 |
+
if path.startswith("/print-barcode/") or path.startswith("/print-receipt/") or path.startswith("/api/print-barcode-pdf/") or path.startswith("/api/print-barcode-image/"):
|
| 31 |
+
token = request.query_params.get("print_token", "")
|
| 32 |
+
if token == PRINT_TOKEN:
|
| 33 |
+
is_public = True
|
| 34 |
+
|
| 35 |
+
if not is_public:
|
| 36 |
+
with Session(engine) as session:
|
| 37 |
+
user = get_current_user(request, session)
|
| 38 |
+
if not user:
|
| 39 |
+
response = StarletteRedirect(url="/login", status_code=303)
|
| 40 |
+
response.delete_cookie("nexlab_session")
|
| 41 |
+
return response
|
| 42 |
+
request.state.user_id = user.id
|
| 43 |
+
|
| 44 |
+
response = await call_next(request)
|
| 45 |
+
return response
|
app/models/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/__init__.py
|
| 2 |
+
# Central re-export of all models.
|
| 3 |
+
# Usage: from app.models import Patient, Order, User, ...
|
| 4 |
+
|
| 5 |
+
from app.models.user import User, UserPermission
|
| 6 |
+
from app.models.audit import AuditLog, ActivityLog, DeletedRecord
|
| 7 |
+
from app.models.department import Parameter, Department, Device, SampleType, ReportNote
|
| 8 |
+
from app.models.geography import Province, Region
|
| 9 |
+
from app.models.test import TestDefinition, TestDevice, TestParameter, TestRange, TestResultType
|
| 10 |
+
from app.models.patient import Patient, PatientVisit, Attachment
|
| 11 |
+
from app.models.order import Order, Result, ResultDetail
|
| 12 |
+
from app.models.formula import Formula, FormulaItem
|
| 13 |
+
from app.models.package import Partner, Package, PackageTest
|
| 14 |
+
from app.models.lab import LabInfo, PrintTemplate
|
| 15 |
+
from app.models.finance import Payment, ExpenseType, Expense
|
| 16 |
+
from app.models.messaging import Chat, ChatMember, Message, MessageReceipt
|
| 17 |
+
from app.models.inventory import Supply, Inventory, CalControl
|
| 18 |
+
from app.models.hr import Employee, EmployeeAttachment
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
"User", "UserPermission",
|
| 22 |
+
"AuditLog", "ActivityLog", "DeletedRecord",
|
| 23 |
+
"Parameter", "Department", "Device", "SampleType", "ReportNote",
|
| 24 |
+
"Province", "Region",
|
| 25 |
+
"TestDefinition", "TestDevice", "TestParameter", "TestRange", "TestResultType",
|
| 26 |
+
"Patient", "PatientVisit", "Attachment",
|
| 27 |
+
"Order", "Result", "ResultDetail",
|
| 28 |
+
"Formula", "FormulaItem",
|
| 29 |
+
"Partner", "Package", "PackageTest",
|
| 30 |
+
"LabInfo", "PrintTemplate",
|
| 31 |
+
"Payment", "ExpenseType", "Expense",
|
| 32 |
+
"Chat", "ChatMember", "Message", "MessageReceipt",
|
| 33 |
+
"Supply", "Inventory", "CalControl",
|
| 34 |
+
"Employee", "EmployeeAttachment",
|
| 35 |
+
]
|
app/models/audit.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/audit.py
|
| 2 |
+
# Audit logging, activity tracking, and archival models.
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class AuditLog(SQLModel, table=True):
|
| 10 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 11 |
+
table_name: str
|
| 12 |
+
record_id: int
|
| 13 |
+
action: str
|
| 14 |
+
user_id: int = Field(foreign_key="user.id")
|
| 15 |
+
username: str
|
| 16 |
+
old_values: Optional[str] = None
|
| 17 |
+
new_values: Optional[str] = None
|
| 18 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ActivityLog(SQLModel, table=True):
|
| 22 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 23 |
+
action_type: str = Field(index=True)
|
| 24 |
+
description: str
|
| 25 |
+
target_type: Optional[str] = None
|
| 26 |
+
target_id: Optional[int] = None
|
| 27 |
+
user_id: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 28 |
+
username: Optional[str] = None
|
| 29 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class DeletedRecord(SQLModel, table=True):
|
| 33 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 34 |
+
source_table: str = Field(index=True)
|
| 35 |
+
record_id: int
|
| 36 |
+
record_data: str # Full JSON snapshot
|
| 37 |
+
deleted_reason: Optional[str] = None
|
| 38 |
+
deleted_by: int = Field(foreign_key="user.id")
|
| 39 |
+
deleted_at: datetime = Field(default_factory=datetime.now)
|
app/models/department.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/department.py
|
| 2 |
+
# Department, SampleType, Device, Parameter, and ReportNote models.
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Parameter(SQLModel, table=True):
|
| 10 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 11 |
+
parameter_name: str = Field(unique=True, index=True)
|
| 12 |
+
parameter_short_name: str
|
| 13 |
+
is_header: bool = Field(default=False)
|
| 14 |
+
|
| 15 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 16 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 17 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 18 |
+
edited_at: Optional[datetime] = None
|
| 19 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 20 |
+
deleted_at: Optional[datetime] = None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Department(SQLModel, table=True):
|
| 24 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 25 |
+
department_name: str = Field(unique=True, index=True)
|
| 26 |
+
department_note: Optional[str] = None
|
| 27 |
+
is_active: bool = Field(default=True)
|
| 28 |
+
|
| 29 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 30 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 31 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 32 |
+
edited_at: Optional[datetime] = None
|
| 33 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 34 |
+
deleted_at: Optional[datetime] = None
|
| 35 |
+
activated_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 36 |
+
activated_at: Optional[datetime] = None
|
| 37 |
+
deactivated_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 38 |
+
deactivated_at: Optional[datetime] = None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Device(SQLModel, table=True):
|
| 42 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 43 |
+
device_name: str = Field(unique=True, index=True)
|
| 44 |
+
serial_number: str
|
| 45 |
+
install_date: datetime
|
| 46 |
+
installer_name: str
|
| 47 |
+
installer_phone: str
|
| 48 |
+
note: Optional[str] = None
|
| 49 |
+
is_active: bool = Field(default=True)
|
| 50 |
+
|
| 51 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 52 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 53 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 54 |
+
edited_at: Optional[datetime] = None
|
| 55 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 56 |
+
deleted_at: Optional[datetime] = None
|
| 57 |
+
activated_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 58 |
+
activated_at: Optional[datetime] = None
|
| 59 |
+
deactivated_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 60 |
+
deactivated_at: Optional[datetime] = None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class SampleType(SQLModel, table=True):
|
| 64 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 65 |
+
sample_name: str = Field(unique=True, index=True)
|
| 66 |
+
sample_note: Optional[str] = None
|
| 67 |
+
is_active: bool = Field(default=True)
|
| 68 |
+
|
| 69 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 70 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 71 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 72 |
+
edited_at: Optional[datetime] = None
|
| 73 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 74 |
+
deleted_at: Optional[datetime] = None
|
| 75 |
+
activated_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 76 |
+
activated_at: Optional[datetime] = None
|
| 77 |
+
deactivated_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 78 |
+
deactivated_at: Optional[datetime] = None
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class ReportNote(SQLModel, table=True):
|
| 82 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 83 |
+
note_name: str = Field(unique=True, index=True)
|
| 84 |
+
note_content: str
|
| 85 |
+
is_active: bool = Field(default=True)
|
| 86 |
+
|
| 87 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 88 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 89 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 90 |
+
edited_at: Optional[datetime] = None
|
| 91 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 92 |
+
deleted_at: Optional[datetime] = None
|
app/models/finance.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/finance.py
|
| 2 |
+
# Payment, Expense, and ExpenseType models.
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field, Relationship
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Payment(SQLModel, table=True):
|
| 10 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 11 |
+
visit_id: int = Field(foreign_key="patientvisit.id", index=True)
|
| 12 |
+
patient_id: int = Field(foreign_key="patient.id", index=True)
|
| 13 |
+
amount: float
|
| 14 |
+
payment_method: str = Field(default="cash")
|
| 15 |
+
payment_date: datetime = Field(default_factory=datetime.now)
|
| 16 |
+
note: Optional[str] = None
|
| 17 |
+
recorded_by: int = Field(foreign_key="user.id")
|
| 18 |
+
is_refund: bool = Field(default=False)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ExpenseType(SQLModel, table=True):
|
| 22 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 23 |
+
type_name: str = Field(unique=True, index=True)
|
| 24 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 25 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 26 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 27 |
+
edited_at: Optional[datetime] = None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Expense(SQLModel, table=True):
|
| 31 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 32 |
+
type_id: int = Field(foreign_key="expensetype.id", index=True)
|
| 33 |
+
expense_date: datetime = Field(default_factory=datetime.now)
|
| 34 |
+
amount: float = Field(default=0.0)
|
| 35 |
+
note: Optional[str] = None
|
| 36 |
+
file_path: Optional[str] = None
|
| 37 |
+
file_name: Optional[str] = None
|
| 38 |
+
created_by: int = Field(foreign_key="user.id")
|
| 39 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 40 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 41 |
+
edited_at: Optional[datetime] = None
|
| 42 |
+
expense_type: "ExpenseType" = Relationship()
|
app/models/formula.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/formula.py
|
| 2 |
+
# Formula and FormulaItem models.
|
| 3 |
+
|
| 4 |
+
from typing import Optional, List
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field, Relationship
|
| 7 |
+
|
| 8 |
+
from app.models.department import Parameter
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Formula(SQLModel, table=True):
|
| 12 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 13 |
+
formula_name: str
|
| 14 |
+
main_test_id: int = Field(foreign_key="testdefinition.id")
|
| 15 |
+
main_parameter_id: Optional[int] = Field(default=None, foreign_key="parameter.id")
|
| 16 |
+
gender_type: str = Field(default="both")
|
| 17 |
+
formula_expression: str = Field(default="")
|
| 18 |
+
formula_description: Optional[str] = None
|
| 19 |
+
is_active: bool = Field(default=True)
|
| 20 |
+
|
| 21 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 22 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 23 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 24 |
+
edited_at: Optional[datetime] = None
|
| 25 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 26 |
+
deleted_at: Optional[datetime] = None
|
| 27 |
+
|
| 28 |
+
main_test: "TestDefinition" = Relationship()
|
| 29 |
+
main_parameter: Optional[Parameter] = Relationship()
|
| 30 |
+
items: List["FormulaItem"] = Relationship(back_populates="formula")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class FormulaItem(SQLModel, table=True):
|
| 34 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 35 |
+
formula_id: int = Field(foreign_key="formula.id")
|
| 36 |
+
operation: str = Field(default="+")
|
| 37 |
+
source_type: str = Field(default="parameter")
|
| 38 |
+
source_test_id: Optional[int] = Field(default=None, foreign_key="testdefinition.id")
|
| 39 |
+
source_parameter_id: Optional[int] = Field(default=None, foreign_key="parameter.id")
|
| 40 |
+
weight_value: float = Field(default=1.0)
|
| 41 |
+
order_index: int = Field(default=0)
|
| 42 |
+
|
| 43 |
+
formula: Formula = Relationship(back_populates="items")
|
app/models/geography.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/geography.py
|
| 2 |
+
# Province and Region models.
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field, Relationship
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Province(SQLModel, table=True):
|
| 10 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 11 |
+
province_name: str = Field(unique=True, index=True)
|
| 12 |
+
is_active: bool = Field(default=True)
|
| 13 |
+
|
| 14 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 15 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 16 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 17 |
+
edited_at: Optional[datetime] = None
|
| 18 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 19 |
+
deleted_at: Optional[datetime] = None
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Region(SQLModel, table=True):
|
| 23 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 24 |
+
region_name: str = Field(unique=True, index=True)
|
| 25 |
+
province_id: int = Field(foreign_key="province.id")
|
| 26 |
+
is_active: bool = Field(default=True)
|
| 27 |
+
|
| 28 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 29 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 30 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 31 |
+
edited_at: Optional[datetime] = None
|
| 32 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 33 |
+
deleted_at: Optional[datetime] = None
|
| 34 |
+
|
| 35 |
+
province: Province = Relationship()
|
app/models/hr.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/hr.py
|
| 2 |
+
# Employee and EmployeeAttachment models for HR management.
|
| 3 |
+
|
| 4 |
+
from typing import Optional, List
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field, Relationship
|
| 7 |
+
|
| 8 |
+
class Employee(SQLModel, table=True):
|
| 9 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 10 |
+
full_name: str = Field(index=True)
|
| 11 |
+
age: Optional[int] = None
|
| 12 |
+
phone: Optional[str] = None
|
| 13 |
+
address: Optional[str] = None
|
| 14 |
+
photo_path: Optional[str] = None
|
| 15 |
+
start_date: datetime = Field(default_factory=datetime.now)
|
| 16 |
+
|
| 17 |
+
# Store working days as a comma-separated string or JSON string (e.g. "Monday, Tuesday, Wednesday")
|
| 18 |
+
working_days: Optional[str] = None
|
| 19 |
+
|
| 20 |
+
# Store hours as "09:00" and "17:00" for simplicity
|
| 21 |
+
working_hours_start: Optional[str] = None
|
| 22 |
+
working_hours_end: Optional[str] = None
|
| 23 |
+
|
| 24 |
+
salary: Optional[float] = None
|
| 25 |
+
username: Optional[str] = None
|
| 26 |
+
is_active: bool = Field(default=True)
|
| 27 |
+
|
| 28 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 29 |
+
|
| 30 |
+
attachments: List["EmployeeAttachment"] = Relationship(back_populates="employee", cascade_delete=True)
|
| 31 |
+
|
| 32 |
+
@property
|
| 33 |
+
def working_life_months(self) -> int:
|
| 34 |
+
if not self.start_date:
|
| 35 |
+
return 0
|
| 36 |
+
now = datetime.now()
|
| 37 |
+
delta = now.year * 12 + now.month - (self.start_date.year * 12 + self.start_date.month)
|
| 38 |
+
return delta if delta > 0 else 0
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class EmployeeAttachment(SQLModel, table=True):
|
| 42 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 43 |
+
employee_id: int = Field(foreign_key="employee.id", index=True)
|
| 44 |
+
file_name: str
|
| 45 |
+
file_path: str
|
| 46 |
+
uploaded_at: datetime = Field(default_factory=datetime.now)
|
| 47 |
+
|
| 48 |
+
employee: Optional["Employee"] = Relationship(back_populates="attachments")
|
app/models/inventory.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/inventory.py
|
| 2 |
+
# Supply, Inventory, and CalControl models.
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field, Relationship
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Supply(SQLModel, table=True):
|
| 10 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 11 |
+
name: str = Field(index=True)
|
| 12 |
+
note: Optional[str] = None
|
| 13 |
+
is_active: bool = Field(default=True)
|
| 14 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 15 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 16 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 17 |
+
edited_at: Optional[datetime] = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Inventory(SQLModel, table=True):
|
| 21 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 22 |
+
material_type: str = Field(index=True)
|
| 23 |
+
test_id: Optional[int] = Field(default=None, foreign_key="testdefinition.id")
|
| 24 |
+
supply_id: Optional[int] = Field(default=None, foreign_key="supply.id")
|
| 25 |
+
test: Optional["TestDefinition"] = Relationship()
|
| 26 |
+
supply: Optional["Supply"] = Relationship()
|
| 27 |
+
quantity: float = Field(default=0.0)
|
| 28 |
+
unit: str = Field(default="Test")
|
| 29 |
+
expiration_date: datetime
|
| 30 |
+
note: Optional[str] = None
|
| 31 |
+
is_active: bool = Field(default=True)
|
| 32 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 33 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 34 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 35 |
+
edited_at: Optional[datetime] = None
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class CalControl(SQLModel, table=True):
|
| 39 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 40 |
+
test_id: int = Field(foreign_key="testdefinition.id", index=True)
|
| 41 |
+
device_id: int = Field(foreign_key="device.id", index=True)
|
| 42 |
+
process_type: str = Field(index=True)
|
| 43 |
+
quantity: float
|
| 44 |
+
note: Optional[str] = None
|
| 45 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 46 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 47 |
+
test: "TestDefinition" = Relationship()
|
| 48 |
+
device: "Device" = Relationship()
|
app/models/lab.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/lab.py
|
| 2 |
+
# LabInfo and PrintTemplate models.
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class LabInfo(SQLModel, table=True):
|
| 10 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 11 |
+
lab_name: str = Field(default="")
|
| 12 |
+
lab_title: Optional[str] = Field(default=None)
|
| 13 |
+
first_doctor_name: Optional[str] = Field(default=None)
|
| 14 |
+
second_doctor_name: Optional[str] = Field(default=None)
|
| 15 |
+
lab_address: Optional[str] = Field(default=None)
|
| 16 |
+
lab_phone_1: str = Field(default="")
|
| 17 |
+
lab_phone_2: Optional[str] = Field(default=None)
|
| 18 |
+
whatsapp_api: Optional[str] = Field(default=None)
|
| 19 |
+
whatsapp_token: Optional[str] = Field(default=None)
|
| 20 |
+
telegram_api: Optional[str] = Field(default=None)
|
| 21 |
+
telegram_token: Optional[str] = Field(default=None)
|
| 22 |
+
lab_qr_1: Optional[str] = Field(default=None)
|
| 23 |
+
lab_qr_2: Optional[str] = Field(default=None)
|
| 24 |
+
lab_stamp_1: Optional[str] = Field(default=None)
|
| 25 |
+
lab_stamp_2: Optional[str] = Field(default=None)
|
| 26 |
+
lab_logo: Optional[str] = Field(default=None)
|
| 27 |
+
lab_signature_1: Optional[str] = Field(default=None)
|
| 28 |
+
lab_signature_2: Optional[str] = Field(default=None)
|
| 29 |
+
lab_image_1: Optional[str] = Field(default=None)
|
| 30 |
+
lab_image_2: Optional[str] = Field(default=None)
|
| 31 |
+
lab_email: Optional[str] = Field(default=None)
|
| 32 |
+
lab_note_1: Optional[str] = Field(default=None)
|
| 33 |
+
lab_note_2: Optional[str] = Field(default=None)
|
| 34 |
+
lab_website: Optional[str] = Field(default=None)
|
| 35 |
+
welcome_message: Optional[str] = Field(default=None)
|
| 36 |
+
welcome_template_name: Optional[str] = Field(default=None)
|
| 37 |
+
province_id: Optional[int] = Field(default=None, foreign_key="province.id")
|
| 38 |
+
lab_currency: str = Field(default="$")
|
| 39 |
+
tax_percentage: float = Field(default=0.0)
|
| 40 |
+
phone_country_code: str = Field(default="964")
|
| 41 |
+
|
| 42 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 43 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 44 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 45 |
+
edited_at: Optional[datetime] = None
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class PrintTemplate(SQLModel, table=True):
|
| 49 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 50 |
+
template_name: str = Field(unique=True, index=True)
|
| 51 |
+
template_type: str = Field(default="receipt")
|
| 52 |
+
paper_width: str = Field(default="80mm")
|
| 53 |
+
paper_height: str = Field(default="auto")
|
| 54 |
+
margin: str = Field(default="0")
|
| 55 |
+
elements: str = Field(default="")
|
| 56 |
+
is_active: bool = Field(default=True)
|
| 57 |
+
|
| 58 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 59 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 60 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 61 |
+
edited_at: Optional[datetime] = None
|
app/models/messaging.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/messaging.py
|
| 2 |
+
# Chat, ChatMember, Message, MessageReceipt models.
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Chat(SQLModel, table=True):
|
| 10 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 11 |
+
is_group: bool = Field(default=False)
|
| 12 |
+
name: Optional[str] = None
|
| 13 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 14 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 15 |
+
edited_at: Optional[datetime] = None
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ChatMember(SQLModel, table=True):
|
| 19 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 20 |
+
chat_id: int = Field(foreign_key="chat.id", index=True)
|
| 21 |
+
user_id: int = Field(foreign_key="user.id", index=True)
|
| 22 |
+
joined_at: datetime = Field(default_factory=datetime.now)
|
| 23 |
+
is_admin: bool = Field(default=False)
|
| 24 |
+
last_read_message_id: Optional[int] = None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class Message(SQLModel, table=True):
|
| 28 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 29 |
+
chat_id: int = Field(foreign_key="chat.id", index=True)
|
| 30 |
+
sender_id: Optional[int] = Field(default=None, foreign_key="user.id", index=True)
|
| 31 |
+
text: Optional[str] = None
|
| 32 |
+
attachment_path: Optional[str] = None
|
| 33 |
+
attachment_name: Optional[str] = None
|
| 34 |
+
attachment_type: Optional[str] = None
|
| 35 |
+
voice_note_path: Optional[str] = None
|
| 36 |
+
voice_note_duration: Optional[int] = None
|
| 37 |
+
reply_to_id: Optional[int] = Field(default=None, foreign_key="message.id")
|
| 38 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 39 |
+
is_deleted: bool = Field(default=False)
|
| 40 |
+
is_call: bool = Field(default=False)
|
| 41 |
+
call_type: Optional[str] = None
|
| 42 |
+
call_status: Optional[str] = None
|
| 43 |
+
call_duration: Optional[int] = None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class MessageReceipt(SQLModel, table=True):
|
| 47 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 48 |
+
message_id: int = Field(foreign_key="message.id", index=True)
|
| 49 |
+
user_id: int = Field(foreign_key="user.id", index=True)
|
| 50 |
+
chat_id: int = Field(foreign_key="chat.id", index=True)
|
| 51 |
+
status: str = Field(default="delivered")
|
| 52 |
+
updated_at: datetime = Field(default_factory=datetime.now)
|
app/models/order.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/order.py
|
| 2 |
+
# Order, Result, and ResultDetail models.
|
| 3 |
+
|
| 4 |
+
from typing import Optional, List
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field, Relationship
|
| 7 |
+
|
| 8 |
+
from app.models.department import Parameter
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Order(SQLModel, table=True):
|
| 12 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 13 |
+
order_number: str = Field(unique=True, index=True)
|
| 14 |
+
patient_id: int = Field(foreign_key="patient.id")
|
| 15 |
+
test_id: int = Field(foreign_key="testdefinition.id")
|
| 16 |
+
status: str = Field(default="ordered")
|
| 17 |
+
ordered_by: int = Field(foreign_key="user.id")
|
| 18 |
+
collected_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 19 |
+
verified_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 20 |
+
order_date: datetime = Field(default_factory=datetime.now)
|
| 21 |
+
collection_date: Optional[datetime] = None
|
| 22 |
+
verified_date: Optional[datetime] = None
|
| 23 |
+
visit_id: Optional[int] = Field(default=None, foreign_key="patientvisit.id")
|
| 24 |
+
package_name: Optional[str] = Field(default=None)
|
| 25 |
+
# Price snapshot at order time
|
| 26 |
+
unit_price: float = Field(default=0.0)
|
| 27 |
+
discount_amount: float = Field(default=0.0)
|
| 28 |
+
final_price: float = Field(default=0.0)
|
| 29 |
+
no_sample_reason: Optional[str] = Field(default=None)
|
| 30 |
+
|
| 31 |
+
# Relationships — use string references for cross-module models
|
| 32 |
+
patient: "Patient" = Relationship(back_populates="orders")
|
| 33 |
+
test: "TestDefinition" = Relationship()
|
| 34 |
+
result: Optional["Result"] = Relationship(back_populates="order")
|
| 35 |
+
visit: Optional["PatientVisit"] = Relationship(back_populates="orders")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class Result(SQLModel, table=True):
|
| 39 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 40 |
+
order_id: int = Field(foreign_key="order.id", unique=True)
|
| 41 |
+
result_value: Optional[str] = Field(default=None)
|
| 42 |
+
rerun_result: Optional[str] = Field(default=None)
|
| 43 |
+
flag: Optional[str] = None
|
| 44 |
+
note: Optional[str] = None
|
| 45 |
+
device_id: Optional[int] = Field(default=None, foreign_key="device.id")
|
| 46 |
+
entered_by: int = Field(foreign_key="user.id")
|
| 47 |
+
entered_at: datetime = Field(default_factory=datetime.now)
|
| 48 |
+
authorized: bool = Field(default=False)
|
| 49 |
+
authorized_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 50 |
+
authorized_at: Optional[datetime] = None
|
| 51 |
+
double_authorized: bool = Field(default=False)
|
| 52 |
+
double_authorized_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 53 |
+
double_authorized_at: Optional[datetime] = None
|
| 54 |
+
unauth_reason: Optional[str] = Field(default=None)
|
| 55 |
+
|
| 56 |
+
order: Order = Relationship(back_populates="result")
|
| 57 |
+
details: List["ResultDetail"] = Relationship(back_populates="result")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class ResultDetail(SQLModel, table=True):
|
| 61 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 62 |
+
result_id: int = Field(foreign_key="result.id")
|
| 63 |
+
parameter_id: int = Field(foreign_key="parameter.id")
|
| 64 |
+
result_value: Optional[str] = Field(default=None)
|
| 65 |
+
rerun_result: Optional[str] = Field(default=None)
|
| 66 |
+
flag: Optional[str] = None
|
| 67 |
+
device_id: Optional[int] = Field(default=None, foreign_key="device.id")
|
| 68 |
+
remark: Optional[str] = Field(default=None)
|
| 69 |
+
|
| 70 |
+
result: Result = Relationship(back_populates="details")
|
| 71 |
+
parameter: Parameter = Relationship()
|
app/models/package.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/package.py
|
| 2 |
+
# Package, PackageTest, and Partner models.
|
| 3 |
+
|
| 4 |
+
from typing import Optional, List
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field, Relationship
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Partner(SQLModel, table=True):
|
| 10 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 11 |
+
partner_name: str = Field(unique=True, index=True)
|
| 12 |
+
partner_note: Optional[str] = None
|
| 13 |
+
partner_contact: Optional[str] = None
|
| 14 |
+
partner_weight: Optional[float] = Field(default=None)
|
| 15 |
+
is_active: bool = Field(default=True)
|
| 16 |
+
|
| 17 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 18 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 19 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 20 |
+
edited_at: Optional[datetime] = None
|
| 21 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 22 |
+
deleted_at: Optional[datetime] = None
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Package(SQLModel, table=True):
|
| 26 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 27 |
+
package_name: str = Field(unique=True, index=True)
|
| 28 |
+
package_short_name: str
|
| 29 |
+
price: float
|
| 30 |
+
package_note: Optional[str] = None
|
| 31 |
+
is_active: bool = Field(default=True)
|
| 32 |
+
|
| 33 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 34 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 35 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 36 |
+
edited_at: Optional[datetime] = None
|
| 37 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 38 |
+
deleted_at: Optional[datetime] = None
|
| 39 |
+
|
| 40 |
+
package_tests: List["PackageTest"] = Relationship(back_populates="package")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class PackageTest(SQLModel, table=True):
|
| 44 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 45 |
+
package_id: int = Field(foreign_key="package.id")
|
| 46 |
+
test_id: int = Field(foreign_key="testdefinition.id")
|
| 47 |
+
|
| 48 |
+
package: Package = Relationship(back_populates="package_tests")
|
| 49 |
+
test: "TestDefinition" = Relationship()
|
app/models/patient.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/patient.py
|
| 2 |
+
# Patient, PatientVisit, and Attachment models.
|
| 3 |
+
|
| 4 |
+
from typing import Optional, List
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field, Relationship
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Patient(SQLModel, table=True):
|
| 10 |
+
__tablename__ = "patient"
|
| 11 |
+
|
| 12 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 13 |
+
patient_id: str = Field(unique=True, index=True)
|
| 14 |
+
full_name: str = Field()
|
| 15 |
+
gender: str = Field()
|
| 16 |
+
age: Optional[int] = Field(default=None)
|
| 17 |
+
age_unit: Optional[str] = Field(default="year")
|
| 18 |
+
date_of_birth: Optional[datetime] = None
|
| 19 |
+
phone_key: str = Field()
|
| 20 |
+
phone_number: str = Field()
|
| 21 |
+
weight: Optional[float] = Field(default=None)
|
| 22 |
+
height: Optional[float] = Field(default=None)
|
| 23 |
+
province_id: Optional[int] = Field(default=None, foreign_key="province.id")
|
| 24 |
+
region_id: Optional[int] = Field(default=None, foreign_key="region.id")
|
| 25 |
+
fasting_time: Optional[int] = Field(default=None)
|
| 26 |
+
note: Optional[str] = Field(default=None)
|
| 27 |
+
email: Optional[str] = Field(default=None)
|
| 28 |
+
diagnosis: Optional[str] = Field(default=None)
|
| 29 |
+
symptoms: Optional[str] = Field(default=None)
|
| 30 |
+
therapy: Optional[str] = Field(default=None)
|
| 31 |
+
partner_id: Optional[int] = Field(default=None, foreign_key="partner.id")
|
| 32 |
+
doctor: Optional[str] = Field(default=None)
|
| 33 |
+
skin_colour: Optional[str] = Field(default=None)
|
| 34 |
+
agent_name: Optional[str] = Field(default=None)
|
| 35 |
+
is_outlab: bool = Field(default=False)
|
| 36 |
+
is_active: bool = Field(default=True)
|
| 37 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 38 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 39 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 40 |
+
edited_at: Optional[datetime] = None
|
| 41 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 42 |
+
deleted_at: Optional[datetime] = None
|
| 43 |
+
deleted_reason: Optional[str] = Field(default=None)
|
| 44 |
+
|
| 45 |
+
# Relationships
|
| 46 |
+
visits: List["PatientVisit"] = Relationship(back_populates="patient", cascade_delete=True)
|
| 47 |
+
orders: List["Order"] = Relationship(back_populates="patient")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class PatientVisit(SQLModel, table=True):
|
| 51 |
+
__tablename__ = "patientvisit"
|
| 52 |
+
|
| 53 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 54 |
+
visit_id: str = Field(index=True)
|
| 55 |
+
patient_id: int = Field(foreign_key="patient.id")
|
| 56 |
+
visit_date: datetime = Field(default_factory=datetime.now)
|
| 57 |
+
is_active: bool = Field(default=True)
|
| 58 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 59 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 60 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 61 |
+
edited_at: Optional[datetime] = None
|
| 62 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 63 |
+
deleted_at: Optional[datetime] = None
|
| 64 |
+
|
| 65 |
+
# Payment fields
|
| 66 |
+
received_amount: float = Field(default=0.0)
|
| 67 |
+
discount_amount: float = Field(default=0.0)
|
| 68 |
+
discount_percentage: float = Field(default=0.0)
|
| 69 |
+
discount_note: Optional[str] = Field(default=None)
|
| 70 |
+
tax_applied: bool = Field(default=True)
|
| 71 |
+
tax_amount: float = Field(default=0.0)
|
| 72 |
+
remaining_amount: float = Field(default=0.0)
|
| 73 |
+
|
| 74 |
+
# Call Centre fields
|
| 75 |
+
is_called: bool = Field(default=False)
|
| 76 |
+
is_whatsapp_sent: bool = Field(default=False)
|
| 77 |
+
is_printed: bool = Field(default=False)
|
| 78 |
+
|
| 79 |
+
# Relationships
|
| 80 |
+
patient: Optional["Patient"] = Relationship(back_populates="visits")
|
| 81 |
+
orders: List["Order"] = Relationship(back_populates="visit")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class Attachment(SQLModel, table=True):
|
| 85 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 86 |
+
patient_id: int = Field(foreign_key="patient.id", index=True)
|
| 87 |
+
visit_id: Optional[int] = Field(default=None, foreign_key="patientvisit.id", index=True)
|
| 88 |
+
file_name: str
|
| 89 |
+
file_path: str
|
| 90 |
+
file_type: str
|
| 91 |
+
description: Optional[str] = None
|
| 92 |
+
uploaded_by: int = Field(foreign_key="user.id")
|
| 93 |
+
uploaded_at: datetime = Field(default_factory=datetime.now)
|
app/models/test.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/test.py
|
| 2 |
+
# Test definition, test-device/parameter links, ranges, and result types.
|
| 3 |
+
|
| 4 |
+
from typing import Optional, List
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field, Relationship
|
| 7 |
+
|
| 8 |
+
from app.models.department import Department, SampleType, ReportNote, Device, Parameter
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TestDefinition(SQLModel, table=True):
|
| 12 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 13 |
+
test_name: str = Field(unique=True, index=True)
|
| 14 |
+
test_short_name: str
|
| 15 |
+
department_id: int = Field(foreign_key="department.id")
|
| 16 |
+
sample_type_id: int = Field(foreign_key="sampletype.id")
|
| 17 |
+
report_note_id: Optional[int] = Field(default=None, foreign_key="reportnote.id")
|
| 18 |
+
price: float
|
| 19 |
+
test_note: Optional[str] = None
|
| 20 |
+
test_condition: Optional[str] = None
|
| 21 |
+
is_available: bool = Field(default=True)
|
| 22 |
+
print_separately: bool = Field(default=False)
|
| 23 |
+
|
| 24 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 25 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 26 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 27 |
+
edited_at: Optional[datetime] = None
|
| 28 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 29 |
+
deleted_at: Optional[datetime] = None
|
| 30 |
+
|
| 31 |
+
# Relationships
|
| 32 |
+
department: Department = Relationship()
|
| 33 |
+
sample_type: SampleType = Relationship()
|
| 34 |
+
report_note: Optional[ReportNote] = Relationship()
|
| 35 |
+
test_devices: List["TestDevice"] = Relationship(back_populates="test")
|
| 36 |
+
test_parameters: List["TestParameter"] = Relationship(back_populates="test")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class TestDevice(SQLModel, table=True):
|
| 40 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 41 |
+
test_id: int = Field(foreign_key="testdefinition.id")
|
| 42 |
+
device_id: int = Field(foreign_key="device.id")
|
| 43 |
+
|
| 44 |
+
test: TestDefinition = Relationship(back_populates="test_devices")
|
| 45 |
+
device: Device = Relationship()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class TestParameter(SQLModel, table=True):
|
| 49 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 50 |
+
test_id: int = Field(foreign_key="testdefinition.id")
|
| 51 |
+
parameter_id: int = Field(foreign_key="parameter.id")
|
| 52 |
+
|
| 53 |
+
test: TestDefinition = Relationship(back_populates="test_parameters")
|
| 54 |
+
parameter: Parameter = Relationship()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class TestRange(SQLModel, table=True):
|
| 58 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 59 |
+
test_id: int = Field(foreign_key="testdefinition.id")
|
| 60 |
+
parameter_id: Optional[int] = Field(default=None, foreign_key="parameter.id")
|
| 61 |
+
device_id: Optional[int] = Field(default=None, foreign_key="device.id")
|
| 62 |
+
unit: str = Field(default="")
|
| 63 |
+
gender_type: str = Field(default="both")
|
| 64 |
+
age_from: int = Field(default=0)
|
| 65 |
+
age_from_unit: str = Field(default="year")
|
| 66 |
+
age_to: int = Field(default=999)
|
| 67 |
+
age_to_unit: str = Field(default="year")
|
| 68 |
+
age_unit: str = Field(default="year")
|
| 69 |
+
fasting_required: bool = Field(default=False)
|
| 70 |
+
range_type: str = Field(default="number")
|
| 71 |
+
|
| 72 |
+
normal_from: Optional[float] = Field(default=None)
|
| 73 |
+
normal_to: Optional[float] = Field(default=None)
|
| 74 |
+
vlow_from: Optional[float] = Field(default=None)
|
| 75 |
+
vlow_to: Optional[float] = Field(default=None)
|
| 76 |
+
low_from: Optional[float] = Field(default=None)
|
| 77 |
+
low_to: Optional[float] = Field(default=None)
|
| 78 |
+
midlow_from: Optional[float] = Field(default=None)
|
| 79 |
+
midlow_to: Optional[float] = Field(default=None)
|
| 80 |
+
midhigh_from: Optional[float] = Field(default=None)
|
| 81 |
+
midhigh_to: Optional[float] = Field(default=None)
|
| 82 |
+
high_from: Optional[float] = Field(default=None)
|
| 83 |
+
high_to: Optional[float] = Field(default=None)
|
| 84 |
+
vhigh_from: Optional[float] = Field(default=None)
|
| 85 |
+
vhigh_to: Optional[float] = Field(default=None)
|
| 86 |
+
panic_less_than: Optional[float] = Field(default=None)
|
| 87 |
+
panic_more_than: Optional[float] = Field(default=None)
|
| 88 |
+
|
| 89 |
+
text_range: Optional[str] = Field(default=None)
|
| 90 |
+
is_active: bool = Field(default=True)
|
| 91 |
+
|
| 92 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 93 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 94 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 95 |
+
edited_at: Optional[datetime] = None
|
| 96 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 97 |
+
deleted_at: Optional[datetime] = None
|
| 98 |
+
|
| 99 |
+
test: TestDefinition = Relationship()
|
| 100 |
+
parameter: Optional[Parameter] = Relationship()
|
| 101 |
+
device: Optional[Device] = Relationship()
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class TestResultType(SQLModel, table=True):
|
| 105 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 106 |
+
test_id: int = Field(foreign_key="testdefinition.id")
|
| 107 |
+
parameter_id: Optional[int] = Field(default=None, foreign_key="parameter.id")
|
| 108 |
+
result_type: str = Field(default="number")
|
| 109 |
+
selection_options: Optional[str] = Field(default=None)
|
| 110 |
+
is_active: bool = Field(default=True)
|
| 111 |
+
|
| 112 |
+
created_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 113 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 114 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 115 |
+
edited_at: Optional[datetime] = None
|
| 116 |
+
deleted_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 117 |
+
deleted_at: Optional[datetime] = None
|
| 118 |
+
|
| 119 |
+
test: TestDefinition = Relationship()
|
| 120 |
+
parameter: Optional[Parameter] = Relationship()
|
app/models/user.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/models/user.py
|
| 2 |
+
# User authentication and permission models.
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from sqlmodel import SQLModel, Field
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class User(SQLModel, table=True):
|
| 10 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 11 |
+
username: str = Field(unique=True, index=True)
|
| 12 |
+
full_name: str
|
| 13 |
+
role: str = Field(default="receptionist")
|
| 14 |
+
hashed_password: str
|
| 15 |
+
is_active: bool = Field(default=True)
|
| 16 |
+
created_at: datetime = Field(default_factory=datetime.now)
|
| 17 |
+
last_seen: Optional[datetime] = None
|
| 18 |
+
is_online: bool = Field(default=False)
|
| 19 |
+
|
| 20 |
+
# Security & Session Fields
|
| 21 |
+
failed_login_attempts: int = Field(default=0)
|
| 22 |
+
locked_until: Optional[datetime] = None
|
| 23 |
+
session_token: Optional[str] = None
|
| 24 |
+
|
| 25 |
+
# Profile Fields
|
| 26 |
+
date_of_birth: Optional[datetime] = None
|
| 27 |
+
phone_number: Optional[str] = None
|
| 28 |
+
address: Optional[str] = None
|
| 29 |
+
|
| 30 |
+
# Audit Fields
|
| 31 |
+
edited_by: Optional[int] = Field(default=None, foreign_key="user.id")
|
| 32 |
+
edited_at: Optional[datetime] = None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class UserPermission(SQLModel, table=True):
|
| 36 |
+
id: Optional[int] = Field(default=None, primary_key=True)
|
| 37 |
+
user_id: int = Field(foreign_key="user.id", index=True)
|
| 38 |
+
page_key: str = Field(index=True)
|
| 39 |
+
allowed_buttons: Optional[str] = Field(default=None) # JSON array of button keys
|
app/routes/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/routes/__init__.py
|
| 2 |
+
# Presentation layer routes package.
|
app/routes/template_helpers.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/routes/template_helpers.py
|
| 2 |
+
# Template system with auto-injection of user context and permissions.
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import json
|
| 6 |
+
from fastapi.templating import Jinja2Templates
|
| 7 |
+
from sqlmodel import Session, select
|
| 8 |
+
|
| 9 |
+
from app.config import TEMPLATE_DIR
|
| 10 |
+
from app.database import engine
|
| 11 |
+
from app.models import UserPermission, LabInfo
|
| 12 |
+
from app.services.auth_service import get_current_user
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
_base_templates = Jinja2Templates(directory=TEMPLATE_DIR)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class AutoUserTemplates:
|
| 19 |
+
"""Wrapper that auto-injects current_user, has_page(), has_button() into every template."""
|
| 20 |
+
|
| 21 |
+
def __init__(self, base):
|
| 22 |
+
self.base = base
|
| 23 |
+
self.env = base.env
|
| 24 |
+
|
| 25 |
+
def TemplateResponse(self, name, context, **kwargs):
|
| 26 |
+
request = context.get("request")
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
with Session(engine) as sess:
|
| 30 |
+
# Resolve current_user
|
| 31 |
+
if "current_user" not in context and request:
|
| 32 |
+
user = get_current_user(request, sess)
|
| 33 |
+
if user:
|
| 34 |
+
sess.expunge(user)
|
| 35 |
+
context["current_user"] = user
|
| 36 |
+
else:
|
| 37 |
+
context["current_user"] = None
|
| 38 |
+
|
| 39 |
+
if "current_user" not in context:
|
| 40 |
+
context["current_user"] = None
|
| 41 |
+
|
| 42 |
+
# Load permissions
|
| 43 |
+
current_user = context.get("current_user")
|
| 44 |
+
is_admin = current_user and (current_user.role == "admin" or current_user.username == "admin")
|
| 45 |
+
|
| 46 |
+
user_perms = {}
|
| 47 |
+
if current_user and not is_admin:
|
| 48 |
+
perms = sess.exec(
|
| 49 |
+
select(UserPermission).where(UserPermission.user_id == current_user.id)
|
| 50 |
+
).all()
|
| 51 |
+
for p in perms:
|
| 52 |
+
buttons = []
|
| 53 |
+
if p.allowed_buttons:
|
| 54 |
+
try:
|
| 55 |
+
buttons = json.loads(p.allowed_buttons)
|
| 56 |
+
except Exception:
|
| 57 |
+
buttons = []
|
| 58 |
+
user_perms[p.page_key] = buttons
|
| 59 |
+
|
| 60 |
+
# Inject global lab_name
|
| 61 |
+
if "global_lab_name" not in context:
|
| 62 |
+
lab_info_obj = sess.exec(select(LabInfo).limit(1)).first()
|
| 63 |
+
context["global_lab_name"] = lab_info_obj.lab_name if lab_info_obj and lab_info_obj.lab_name else ""
|
| 64 |
+
except Exception:
|
| 65 |
+
if "current_user" not in context:
|
| 66 |
+
context["current_user"] = None
|
| 67 |
+
current_user = context.get("current_user")
|
| 68 |
+
is_admin = current_user and (current_user.role == "admin" or current_user.username == "admin")
|
| 69 |
+
user_perms = {}
|
| 70 |
+
if "global_lab_name" not in context:
|
| 71 |
+
context["global_lab_name"] = ""
|
| 72 |
+
|
| 73 |
+
# Permission helpers for Jinja templates
|
| 74 |
+
def has_page(page_key):
|
| 75 |
+
if is_admin:
|
| 76 |
+
return True
|
| 77 |
+
return page_key in user_perms
|
| 78 |
+
|
| 79 |
+
def has_button(page_key, button_key):
|
| 80 |
+
if is_admin:
|
| 81 |
+
return True
|
| 82 |
+
if page_key not in user_perms:
|
| 83 |
+
return False
|
| 84 |
+
return button_key in user_perms[page_key]
|
| 85 |
+
|
| 86 |
+
context["has_page"] = has_page
|
| 87 |
+
context["has_button"] = has_button
|
| 88 |
+
context["is_admin"] = is_admin
|
| 89 |
+
context["user_perms"] = user_perms
|
| 90 |
+
|
| 91 |
+
return self.base.TemplateResponse(name, context, **kwargs)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
templates = AutoUserTemplates(_base_templates)
|
app/services/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/services/__init__.py
|
| 2 |
+
# Business logic services package.
|
app/services/audit_service.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/services/audit_service.py
|
| 2 |
+
# Audit logging, activity logging, and archival services.
|
| 3 |
+
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
import json
|
| 6 |
+
from sqlmodel import Session
|
| 7 |
+
|
| 8 |
+
from app.models import AuditLog, DeletedRecord, ActivityLog
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def log_audit_action(session: Session, table_name: str, record_id: int, action: str,
|
| 12 |
+
current_user, old_values: dict = None, new_values: dict = None):
|
| 13 |
+
"""Universal Audit Logger. Safely wraps in try/except to never crash the caller."""
|
| 14 |
+
try:
|
| 15 |
+
username = "System"
|
| 16 |
+
user_id = None
|
| 17 |
+
if current_user:
|
| 18 |
+
user_id = current_user.id
|
| 19 |
+
username = getattr(current_user, 'full_name', current_user.username)
|
| 20 |
+
|
| 21 |
+
log_entry = AuditLog(
|
| 22 |
+
table_name=table_name.lower(),
|
| 23 |
+
record_id=record_id,
|
| 24 |
+
action=action.upper(),
|
| 25 |
+
user_id=user_id,
|
| 26 |
+
username=username,
|
| 27 |
+
old_values=json.dumps(old_values) if old_values else None,
|
| 28 |
+
new_values=json.dumps(new_values) if new_values else None,
|
| 29 |
+
created_at=datetime.now()
|
| 30 |
+
)
|
| 31 |
+
session.add(log_entry)
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"Warning: Audit Log Failure: {str(e)}")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# Backwards-compatible alias
|
| 37 |
+
create_audit_log = log_audit_action
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def archive_deleted_record(session: Session, source_table: str, record_id: int,
|
| 41 |
+
record_data: dict, current_user, deleted_reason: str = None):
|
| 42 |
+
"""Saves a JSON snapshot of a record before soft or hard deletion."""
|
| 43 |
+
try:
|
| 44 |
+
user_id = current_user.id if hasattr(current_user, 'id') else 0
|
| 45 |
+
archive = DeletedRecord(
|
| 46 |
+
source_table=source_table,
|
| 47 |
+
record_id=record_id,
|
| 48 |
+
record_data=json.dumps(record_data),
|
| 49 |
+
deleted_by=user_id,
|
| 50 |
+
deleted_reason=deleted_reason
|
| 51 |
+
)
|
| 52 |
+
session.add(archive)
|
| 53 |
+
except Exception as e:
|
| 54 |
+
print(f"Warning: Failed to archive deleted record: {str(e)}")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def log_activity_action(session: Session, action_type: str, description: str,
|
| 58 |
+
current_user, target_type: str = None, target_id: int = None):
|
| 59 |
+
"""Logs non-data operational events (logins, printing, etc.)."""
|
| 60 |
+
try:
|
| 61 |
+
user_id = current_user.id if hasattr(current_user, 'id') else None
|
| 62 |
+
username = getattr(current_user, 'full_name', getattr(current_user, 'username', "System"))
|
| 63 |
+
|
| 64 |
+
activity = ActivityLog(
|
| 65 |
+
action_type=action_type.upper(),
|
| 66 |
+
description=description,
|
| 67 |
+
user_id=user_id,
|
| 68 |
+
username=username,
|
| 69 |
+
target_type=target_type,
|
| 70 |
+
target_id=target_id
|
| 71 |
+
)
|
| 72 |
+
session.add(activity)
|
| 73 |
+
except Exception as e:
|
| 74 |
+
print(f"Warning: Activity Log Failure: {str(e)}")
|
app/services/auth_service.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/services/auth_service.py
|
| 2 |
+
# Authentication helpers: session validation, user lookup, inactivity timeout.
|
| 3 |
+
|
| 4 |
+
import logging
|
| 5 |
+
from fastapi import Request
|
| 6 |
+
from sqlmodel import Session
|
| 7 |
+
from datetime import datetime, timedelta
|
| 8 |
+
from typing import Optional
|
| 9 |
+
from itsdangerous import URLSafeSerializer
|
| 10 |
+
|
| 11 |
+
from app.config import SECRET_KEY
|
| 12 |
+
from app.models import User
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def get_current_user(request: Request, session: Session) -> Optional[User]:
|
| 16 |
+
"""Get current logged-in user from session cookie."""
|
| 17 |
+
try:
|
| 18 |
+
s = URLSafeSerializer(SECRET_KEY)
|
| 19 |
+
cookie = request.cookies.get("nexlab_session")
|
| 20 |
+
if not cookie:
|
| 21 |
+
return None
|
| 22 |
+
data = s.loads(cookie)
|
| 23 |
+
user_id = data.get("user_id")
|
| 24 |
+
session_token = data.get("session_token")
|
| 25 |
+
|
| 26 |
+
if user_id and session_token:
|
| 27 |
+
user = session.get(User, user_id)
|
| 28 |
+
if user and user.session_token == session_token:
|
| 29 |
+
# Check inactivity timeout (2 hours)
|
| 30 |
+
if user.last_seen and (datetime.now() - user.last_seen) > timedelta(hours=2):
|
| 31 |
+
user.session_token = None
|
| 32 |
+
session.commit()
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
# Update last_seen if > 5 mins to avoid spamming DB
|
| 36 |
+
if not user.last_seen or (datetime.now() - user.last_seen) > timedelta(minutes=5):
|
| 37 |
+
user.last_seen = datetime.now()
|
| 38 |
+
session.commit()
|
| 39 |
+
|
| 40 |
+
return user
|
| 41 |
+
except Exception as e:
|
| 42 |
+
logging.error(f"Auth error in get_current_user: {e}")
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def login_required(request: Request, session: Session) -> Optional[User]:
|
| 47 |
+
"""Check if user is logged in, return user or None."""
|
| 48 |
+
return get_current_user(request, session)
|
app/services/barcode_image_service.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/services/barcode_image_service.py
|
| 2 |
+
# Generates barcode label as a high-DPI PNG image (Pillow + python-barcode).
|
| 3 |
+
# Same approach as NaseemPrint (ZXing + System.Drawing) —
|
| 4 |
+
# renders directly as a bitmap at thermal printer DPI.
|
| 5 |
+
|
| 6 |
+
import io
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 11 |
+
import barcode
|
| 12 |
+
from barcode.writer import ImageWriter
|
| 13 |
+
|
| 14 |
+
import arabic_reshaper
|
| 15 |
+
from bidi.algorithm import get_display
|
| 16 |
+
from app.config import STATIC_DIR
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
PRINTER_DPI = 203 # Standard thermal label printer DPI
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def parse_css_to_inches(dim_str):
|
| 23 |
+
"""Convert CSS dimension string to inches."""
|
| 24 |
+
if not dim_str:
|
| 25 |
+
return 0
|
| 26 |
+
dim_str = str(dim_str).strip().lower()
|
| 27 |
+
match = re.match(r'^([\d\.]+)\s*([a-z]*)$', dim_str)
|
| 28 |
+
if not match:
|
| 29 |
+
return 0
|
| 30 |
+
val, unit = float(match.group(1)), match.group(2)
|
| 31 |
+
if unit == 'mm':
|
| 32 |
+
return val / 25.4
|
| 33 |
+
elif unit == 'cm':
|
| 34 |
+
return val / 2.54
|
| 35 |
+
elif unit == 'in':
|
| 36 |
+
return val
|
| 37 |
+
elif unit == 'px':
|
| 38 |
+
return val / 96.0
|
| 39 |
+
return val / 96.0 # assume px
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def generate_barcode_label_image(patient, tests_by_sample_type, template, visit_id='', visit_date='', dpi=PRINTER_DPI):
|
| 43 |
+
"""
|
| 44 |
+
Generate barcode label as a high-DPI PNG image.
|
| 45 |
+
Returns: list of BytesIO objects (one PNG per sample type/page).
|
| 46 |
+
"""
|
| 47 |
+
# Label dimensions in pixels at target DPI
|
| 48 |
+
width_in = parse_css_to_inches(template.paper_width) or 4.0
|
| 49 |
+
height_in = parse_css_to_inches(template.paper_height) or 2.0
|
| 50 |
+
img_w = int(width_in * dpi)
|
| 51 |
+
img_h = int(height_in * dpi)
|
| 52 |
+
|
| 53 |
+
# Scale factor: template coordinates are in CSS pixels (96 DPI)
|
| 54 |
+
scale = dpi / 96.0
|
| 55 |
+
|
| 56 |
+
elements = json.loads(template.elements) if template.elements else []
|
| 57 |
+
|
| 58 |
+
# Load font
|
| 59 |
+
font_path = os.path.join(STATIC_DIR, 'vendor', 'fonts', 'Cairo-600.ttf')
|
| 60 |
+
if not os.path.exists(font_path):
|
| 61 |
+
font_path = None
|
| 62 |
+
|
| 63 |
+
# Arabic reshaper
|
| 64 |
+
try:
|
| 65 |
+
reshaper_config = arabic_reshaper.config_for_true_type_font(font_path) if font_path else None
|
| 66 |
+
except Exception:
|
| 67 |
+
reshaper_config = None
|
| 68 |
+
reshaper = arabic_reshaper.ArabicReshaper(configuration=reshaper_config) if reshaper_config else arabic_reshaper.ArabicReshaper()
|
| 69 |
+
|
| 70 |
+
sample_types = list(tests_by_sample_type.keys()) or ['Unknown']
|
| 71 |
+
pages = []
|
| 72 |
+
|
| 73 |
+
for sample_type in sample_types:
|
| 74 |
+
test_names = tests_by_sample_type.get(sample_type, [])
|
| 75 |
+
tests_str = ", ".join(test_names) if test_names else ''
|
| 76 |
+
|
| 77 |
+
# Create blank white label
|
| 78 |
+
img = Image.new('1', (img_w, img_h), 1) # mode='1' = 1-bit B&W, 1=white
|
| 79 |
+
draw = ImageDraw.Draw(img)
|
| 80 |
+
|
| 81 |
+
for el in elements:
|
| 82 |
+
el_type = el.get('type', '')
|
| 83 |
+
x = int(el.get('x', 0) * scale)
|
| 84 |
+
y = int(el.get('y', 0) * scale)
|
| 85 |
+
w = int(el.get('width', 100) * scale)
|
| 86 |
+
h = int(el.get('height', 20) * scale)
|
| 87 |
+
font_size = max(6, int(el.get('fontSize', 11) * scale))
|
| 88 |
+
|
| 89 |
+
if el_type == 'barcode_image':
|
| 90 |
+
# Generate Code128 barcode — bars only, text drawn separately for full control
|
| 91 |
+
try:
|
| 92 |
+
show_text = el.get('showBarcodeText', True)
|
| 93 |
+
code128 = barcode.get('code128', str(patient.patient_id), writer=ImageWriter())
|
| 94 |
+
bc_buffer = io.BytesIO()
|
| 95 |
+
code128.write(bc_buffer, options={
|
| 96 |
+
'module_width': 0.5, # thick bars
|
| 97 |
+
'module_height': 20, # tall bars in mm
|
| 98 |
+
'write_text': False,
|
| 99 |
+
'quiet_zone': 1,
|
| 100 |
+
'dpi': dpi,
|
| 101 |
+
})
|
| 102 |
+
bc_buffer.seek(0)
|
| 103 |
+
bc_img = Image.open(bc_buffer).convert('1')
|
| 104 |
+
|
| 105 |
+
# Crop white padding so bars fill the element properly
|
| 106 |
+
crop_box = bc_img.getbbox()
|
| 107 |
+
if crop_box:
|
| 108 |
+
bc_img = bc_img.crop(crop_box)
|
| 109 |
+
|
| 110 |
+
# Scale to fill element box
|
| 111 |
+
bc_ratio = min(w / bc_img.width, h / bc_img.height)
|
| 112 |
+
new_w = int(bc_img.width * bc_ratio)
|
| 113 |
+
new_h = int(bc_img.height * bc_ratio)
|
| 114 |
+
bc_img = bc_img.resize((new_w, new_h), Image.NEAREST)
|
| 115 |
+
|
| 116 |
+
# Paste bars centered in element box
|
| 117 |
+
paste_x = x + (w - new_w) // 2
|
| 118 |
+
paste_y = y
|
| 119 |
+
img.paste(bc_img, (paste_x, paste_y))
|
| 120 |
+
|
| 121 |
+
# Draw patient ID text BELOW the element box
|
| 122 |
+
if show_text:
|
| 123 |
+
try:
|
| 124 |
+
id_font = ImageFont.truetype(font_path, max(8, int(7 * scale))) if font_path else ImageFont.load_default()
|
| 125 |
+
except Exception:
|
| 126 |
+
id_font = ImageFont.load_default()
|
| 127 |
+
id_text = str(patient.patient_id)
|
| 128 |
+
bbox = draw.textbbox((0, 0), id_text, font=id_font)
|
| 129 |
+
tw = bbox[2] - bbox[0]
|
| 130 |
+
text_x = x + (w - tw) // 2 # centered under bars
|
| 131 |
+
text_y = y + h + 0.5 # minimal gap below bars
|
| 132 |
+
draw.text((text_x, text_y), id_text, fill=0, font=id_font)
|
| 133 |
+
except Exception as e:
|
| 134 |
+
# Fallback: draw placeholder
|
| 135 |
+
draw.rectangle([x, y, x + w, y + h], outline=0)
|
| 136 |
+
draw.text((x + 5, y + 5), f"BC:{patient.patient_id}", fill=0)
|
| 137 |
+
continue
|
| 138 |
+
|
| 139 |
+
# Text elements
|
| 140 |
+
txt = ''
|
| 141 |
+
if el_type == 'patient_name':
|
| 142 |
+
txt = str(patient.full_name or '')
|
| 143 |
+
elif el_type == 'patient_id':
|
| 144 |
+
txt = str(patient.patient_id or '')
|
| 145 |
+
elif el_type == 'patient_gender':
|
| 146 |
+
txt = str(patient.gender or '')
|
| 147 |
+
elif el_type == 'patient_age':
|
| 148 |
+
txt = f"{patient.age or 0} {patient.age_unit or 'year'}"
|
| 149 |
+
elif el_type == 'patient_phone':
|
| 150 |
+
txt = f"{patient.phone_key or ''} {patient.phone_number or ''}".strip()
|
| 151 |
+
elif el_type == 'sample_type':
|
| 152 |
+
txt = sample_type
|
| 153 |
+
elif el_type == 'test_list':
|
| 154 |
+
txt = tests_str
|
| 155 |
+
elif el_type == 'test_name':
|
| 156 |
+
txt = test_names[0] if test_names else ''
|
| 157 |
+
elif el_type == 'visit_id':
|
| 158 |
+
txt = str(visit_id or '')
|
| 159 |
+
elif el_type == 'visit_date':
|
| 160 |
+
txt = str(visit_date or '')
|
| 161 |
+
elif el_type == 'lab_name':
|
| 162 |
+
txt = el.get('label', '')
|
| 163 |
+
elif el_type == 'custom_text':
|
| 164 |
+
txt = el.get('customText', el.get('label', ''))
|
| 165 |
+
else:
|
| 166 |
+
txt = el.get('label', '')
|
| 167 |
+
|
| 168 |
+
if not txt:
|
| 169 |
+
continue
|
| 170 |
+
|
| 171 |
+
# Arabic text reshaping
|
| 172 |
+
try:
|
| 173 |
+
reshaped = reshaper.reshape(txt)
|
| 174 |
+
display_txt = get_display(reshaped)
|
| 175 |
+
except Exception:
|
| 176 |
+
display_txt = txt
|
| 177 |
+
|
| 178 |
+
# Load font at the correct size
|
| 179 |
+
try:
|
| 180 |
+
pil_font = ImageFont.truetype(font_path, font_size) if font_path else ImageFont.load_default()
|
| 181 |
+
except Exception:
|
| 182 |
+
pil_font = ImageFont.load_default()
|
| 183 |
+
|
| 184 |
+
# Calculate text position based on alignment
|
| 185 |
+
align = el.get('align', 'left')
|
| 186 |
+
bbox = draw.textbbox((0, 0), display_txt, font=pil_font)
|
| 187 |
+
text_w = bbox[2] - bbox[0]
|
| 188 |
+
text_h = bbox[3] - bbox[1]
|
| 189 |
+
text_y = y + (h - text_h) // 2
|
| 190 |
+
|
| 191 |
+
if align == 'center':
|
| 192 |
+
text_x = x + (w - text_w) // 2
|
| 193 |
+
elif align == 'right':
|
| 194 |
+
text_x = x + w - text_w
|
| 195 |
+
else:
|
| 196 |
+
text_x = x + 5 # small padding
|
| 197 |
+
|
| 198 |
+
draw.text((text_x, text_y), display_txt, fill=0, font=pil_font)
|
| 199 |
+
|
| 200 |
+
# Convert to PNG bytes
|
| 201 |
+
buf = io.BytesIO()
|
| 202 |
+
img.save(buf, format='PNG', dpi=(dpi, dpi))
|
| 203 |
+
buf.seek(0)
|
| 204 |
+
pages.append(buf)
|
| 205 |
+
|
| 206 |
+
return pages
|
app/services/barcode_service.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/services/barcode_service.py
|
| 2 |
+
# Barcode generation utilities.
|
| 3 |
+
|
| 4 |
+
import io
|
| 5 |
+
import base64
|
| 6 |
+
|
| 7 |
+
import barcode
|
| 8 |
+
from barcode.writer import ImageWriter
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def generate_barcode_base64(patient_id: str) -> str:
|
| 12 |
+
"""Generate a Code128 barcode as a base64-encoded PNG string."""
|
| 13 |
+
try:
|
| 14 |
+
code128 = barcode.get_barcode_class('code128')
|
| 15 |
+
rv = io.BytesIO()
|
| 16 |
+
code128(str(patient_id), writer=ImageWriter()).write(rv)
|
| 17 |
+
rv.seek(0)
|
| 18 |
+
return base64.b64encode(rv.read()).decode('utf-8')
|
| 19 |
+
except Exception:
|
| 20 |
+
return ""
|
app/services/patient_service.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/services/patient_service.py
|
| 2 |
+
# Patient-related business logic: query builders, data helpers.
|
| 3 |
+
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from sqlmodel import Session, select
|
| 6 |
+
from sqlalchemy.orm import selectinload
|
| 7 |
+
|
| 8 |
+
from app.models import Patient, PatientVisit, Order, TestDefinition
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def calculate_age(dob: datetime) -> int:
|
| 12 |
+
"""Calculate age from date of birth."""
|
| 13 |
+
if dob is None:
|
| 14 |
+
return 0
|
| 15 |
+
today = datetime.today()
|
| 16 |
+
return today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def age_to_days(age, unit: str) -> int:
|
| 20 |
+
"""Convert age and unit to days for consistent comparison."""
|
| 21 |
+
if age is None or age == "":
|
| 22 |
+
return 0
|
| 23 |
+
age = int(age)
|
| 24 |
+
u = (unit or "year").lower()
|
| 25 |
+
if "year" in u:
|
| 26 |
+
return age * 365
|
| 27 |
+
elif "month" in u:
|
| 28 |
+
return age * 30
|
| 29 |
+
elif "day" in u:
|
| 30 |
+
return age
|
| 31 |
+
return age * 365
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def model_to_dict(model):
|
| 35 |
+
"""Convert SQLModel object to dict."""
|
| 36 |
+
if model is None:
|
| 37 |
+
return None
|
| 38 |
+
data = {}
|
| 39 |
+
for column in model.__table__.columns.keys():
|
| 40 |
+
value = getattr(model, column)
|
| 41 |
+
if isinstance(value, datetime):
|
| 42 |
+
data[column] = value.isoformat()
|
| 43 |
+
else:
|
| 44 |
+
data[column] = value
|
| 45 |
+
return data
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def build_patient_visit_data(session, request, status_filter=None, defaults_today=True):
|
| 49 |
+
"""
|
| 50 |
+
Shared helper to build patient_data list for patient list pages.
|
| 51 |
+
Eliminates N+1 queries by fetching visits directly with eager-loaded orders.
|
| 52 |
+
Supports pagination via ?page= query param.
|
| 53 |
+
|
| 54 |
+
Returns: (patient_data, filters, page, total_pages, total_count)
|
| 55 |
+
"""
|
| 56 |
+
PAGE_SIZE = 50
|
| 57 |
+
|
| 58 |
+
today_str = datetime.today().strftime("%Y-%m-%d") if defaults_today else ""
|
| 59 |
+
start_date = request.query_params.get("start_date", today_str)
|
| 60 |
+
end_date = request.query_params.get("end_date", today_str)
|
| 61 |
+
name = request.query_params.get("name", "")
|
| 62 |
+
patient_id_q = request.query_params.get("patient_id", "")
|
| 63 |
+
test_q = request.query_params.get("test", "")
|
| 64 |
+
status_q = status_filter or request.query_params.get("status", "all")
|
| 65 |
+
|
| 66 |
+
# Pagination
|
| 67 |
+
try:
|
| 68 |
+
page = max(1, int(request.query_params.get("page", 1)))
|
| 69 |
+
except (ValueError, TypeError):
|
| 70 |
+
page = 1
|
| 71 |
+
|
| 72 |
+
# Single query: fetch visits with eager-loaded patient and orders
|
| 73 |
+
visit_query = (
|
| 74 |
+
select(PatientVisit)
|
| 75 |
+
.options(
|
| 76 |
+
selectinload(PatientVisit.patient),
|
| 77 |
+
selectinload(PatientVisit.orders).selectinload(Order.test)
|
| 78 |
+
)
|
| 79 |
+
.join(Patient, PatientVisit.patient_id == Patient.id)
|
| 80 |
+
.where(Patient.is_active == True)
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
if start_date:
|
| 84 |
+
visit_query = visit_query.where(PatientVisit.visit_date >= datetime.strptime(f"{start_date} 00:00:00", "%Y-%m-%d %H:%M:%S"))
|
| 85 |
+
if end_date:
|
| 86 |
+
visit_query = visit_query.where(PatientVisit.visit_date <= datetime.strptime(f"{end_date} 23:59:59", "%Y-%m-%d %H:%M:%S"))
|
| 87 |
+
if name:
|
| 88 |
+
visit_query = visit_query.where(Patient.full_name.ilike(f"%{name}%"))
|
| 89 |
+
if patient_id_q:
|
| 90 |
+
visit_query = visit_query.where(Patient.patient_id.ilike(f"%{patient_id_q}%"))
|
| 91 |
+
|
| 92 |
+
if test_q:
|
| 93 |
+
visit_query = visit_query.join(Order, Order.visit_id == PatientVisit.id).join(
|
| 94 |
+
TestDefinition, Order.test_id == TestDefinition.id
|
| 95 |
+
).where(
|
| 96 |
+
(TestDefinition.test_name.ilike(f"%{test_q}%")) |
|
| 97 |
+
(TestDefinition.test_short_name.ilike(f"%{test_q}%"))
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if status_q != "all":
|
| 101 |
+
if not test_q:
|
| 102 |
+
visit_query = visit_query.join(Order, Order.visit_id == PatientVisit.id)
|
| 103 |
+
if status_q == "pending":
|
| 104 |
+
visit_query = visit_query.where(Order.status == "ordered")
|
| 105 |
+
elif status_q in ("received", "resulted"):
|
| 106 |
+
visit_query = visit_query.where(Order.status == "resulted")
|
| 107 |
+
elif status_q in ("authorize", "authorized"):
|
| 108 |
+
visit_query = visit_query.where(Order.status == "authorized")
|
| 109 |
+
elif status_q == "double_authorized":
|
| 110 |
+
visit_query = visit_query.where(Order.status == "double_authorized")
|
| 111 |
+
elif status_q == "AD":
|
| 112 |
+
visit_query = visit_query.where(Order.status.in_(["authorized", "double_authorized"]))
|
| 113 |
+
|
| 114 |
+
visits = session.exec(
|
| 115 |
+
visit_query.distinct().order_by(PatientVisit.visit_date.desc())
|
| 116 |
+
).all()
|
| 117 |
+
|
| 118 |
+
# Build one row per visit (no deduplication — each visit is shown separately)
|
| 119 |
+
all_patient_data = []
|
| 120 |
+
|
| 121 |
+
for visit in visits:
|
| 122 |
+
patient = visit.patient
|
| 123 |
+
if not patient:
|
| 124 |
+
continue
|
| 125 |
+
|
| 126 |
+
# Build tests data from orders
|
| 127 |
+
packages = {}
|
| 128 |
+
standalones = []
|
| 129 |
+
|
| 130 |
+
for order in visit.orders:
|
| 131 |
+
if not order.test or order.status == "no_sample":
|
| 132 |
+
continue
|
| 133 |
+
|
| 134 |
+
status_color = "red"
|
| 135 |
+
if order.status == "resulted":
|
| 136 |
+
status_color = "blue"
|
| 137 |
+
elif order.status == "authorized":
|
| 138 |
+
status_color = "green"
|
| 139 |
+
elif order.status == "double_authorized":
|
| 140 |
+
status_color = "purple"
|
| 141 |
+
|
| 142 |
+
test_info = {"name": order.test.test_name, "color": status_color}
|
| 143 |
+
|
| 144 |
+
if order.package_name:
|
| 145 |
+
if order.package_name not in packages:
|
| 146 |
+
packages[order.package_name] = []
|
| 147 |
+
packages[order.package_name].append(test_info)
|
| 148 |
+
else:
|
| 149 |
+
standalones.append(test_info)
|
| 150 |
+
|
| 151 |
+
tests_data = []
|
| 152 |
+
for pkg_name, pkg_tests in packages.items():
|
| 153 |
+
tests_data.append({"is_package": True, "package_name": pkg_name, "tests": pkg_tests})
|
| 154 |
+
for t in standalones:
|
| 155 |
+
tests_data.append({"is_package": False, "test": t})
|
| 156 |
+
|
| 157 |
+
all_patient_data.append({
|
| 158 |
+
"patient": patient,
|
| 159 |
+
"visit": visit,
|
| 160 |
+
"registration_date": visit.visit_date,
|
| 161 |
+
"tests": tests_data
|
| 162 |
+
})
|
| 163 |
+
|
| 164 |
+
# Pagination
|
| 165 |
+
total_count = len(all_patient_data)
|
| 166 |
+
total_pages = max(1, (total_count + PAGE_SIZE - 1) // PAGE_SIZE)
|
| 167 |
+
page = min(page, total_pages)
|
| 168 |
+
offset = (page - 1) * PAGE_SIZE
|
| 169 |
+
patient_data = all_patient_data[offset:offset + PAGE_SIZE]
|
| 170 |
+
|
| 171 |
+
filters = {
|
| 172 |
+
"start_date": start_date,
|
| 173 |
+
"end_date": end_date,
|
| 174 |
+
"name": name,
|
| 175 |
+
"patient_id": patient_id_q,
|
| 176 |
+
"test": test_q,
|
| 177 |
+
"status": status_q,
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
return patient_data, filters, page, total_pages, total_count
|
app/services/pdf_service.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/services/pdf_service.py
|
| 2 |
+
# Native PDF generation for barcode labels using ReportLab.
|
| 3 |
+
|
| 4 |
+
import io
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
from reportlab.pdfgen import canvas
|
| 8 |
+
from reportlab.lib.units import inch, mm
|
| 9 |
+
from reportlab.graphics.barcode import code128
|
| 10 |
+
from reportlab.pdfbase import pdfmetrics
|
| 11 |
+
from reportlab.pdfbase.ttfonts import TTFont
|
| 12 |
+
import arabic_reshaper
|
| 13 |
+
from bidi.algorithm import get_display
|
| 14 |
+
|
| 15 |
+
from app.config import STATIC_DIR
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def parse_pt(dim_str):
|
| 19 |
+
"""Convert CSS dimension to PDF points."""
|
| 20 |
+
if not dim_str:
|
| 21 |
+
return 0
|
| 22 |
+
dim_str = str(dim_str).strip().lower()
|
| 23 |
+
import re
|
| 24 |
+
match = re.match(r'^([\d\.]+)\s*([a-z]*)$', dim_str)
|
| 25 |
+
if not match:
|
| 26 |
+
return 0
|
| 27 |
+
val, unit = float(match.group(1)), match.group(2)
|
| 28 |
+
if unit == 'mm':
|
| 29 |
+
return val * 2.83465
|
| 30 |
+
elif unit == 'cm':
|
| 31 |
+
return val * 28.3465
|
| 32 |
+
elif unit == 'in':
|
| 33 |
+
return val * 72.0
|
| 34 |
+
elif unit == 'px':
|
| 35 |
+
return val * 0.75
|
| 36 |
+
return val
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def generate_native_barcode_pdf(patient, tests_by_sample_type, template, visit_id='', visit_date=''):
|
| 40 |
+
"""
|
| 41 |
+
Generate a pure vector PDF using ReportLab natively.
|
| 42 |
+
Coordinates are converted from CSS screen pixels (96dpi) to PDF points (72dpi).
|
| 43 |
+
Returns: BytesIO object containing the PDF.
|
| 44 |
+
"""
|
| 45 |
+
buffer = io.BytesIO()
|
| 46 |
+
|
| 47 |
+
width_pt = parse_pt(template.paper_width) or (2.0 * 72.0)
|
| 48 |
+
height_pt = parse_pt(template.paper_height) or (1.0 * 72.0)
|
| 49 |
+
margin_pt = parse_pt(template.margin) if template.margin else 0
|
| 50 |
+
|
| 51 |
+
c = canvas.Canvas(buffer, pagesize=(width_pt, height_pt))
|
| 52 |
+
|
| 53 |
+
# Font registry
|
| 54 |
+
font_path = os.path.join(STATIC_DIR, 'vendor', 'fonts', 'Cairo-600.ttf')
|
| 55 |
+
if os.path.exists(font_path):
|
| 56 |
+
try:
|
| 57 |
+
pdfmetrics.registerFont(TTFont('ArabicFont', font_path))
|
| 58 |
+
font_name = 'ArabicFont'
|
| 59 |
+
except Exception:
|
| 60 |
+
font_name = 'Helvetica'
|
| 61 |
+
else:
|
| 62 |
+
font_name = 'Helvetica'
|
| 63 |
+
|
| 64 |
+
elements = json.loads(template.elements) if template.elements else []
|
| 65 |
+
|
| 66 |
+
# Arabic reshaper
|
| 67 |
+
try:
|
| 68 |
+
reshaper_config = arabic_reshaper.config_for_true_type_font(font_path) if os.path.exists(font_path) else None
|
| 69 |
+
except Exception:
|
| 70 |
+
reshaper_config = None
|
| 71 |
+
reshaper = arabic_reshaper.ArabicReshaper(configuration=reshaper_config) if reshaper_config else arabic_reshaper.ArabicReshaper()
|
| 72 |
+
|
| 73 |
+
PX_TO_PT = 72.0 / 96.0
|
| 74 |
+
|
| 75 |
+
sample_types = list(tests_by_sample_type.keys()) or ['Unknown']
|
| 76 |
+
|
| 77 |
+
for sample_type in sample_types:
|
| 78 |
+
test_names = tests_by_sample_type.get(sample_type, [])
|
| 79 |
+
tests_str = ", ".join(test_names) if test_names else ''
|
| 80 |
+
|
| 81 |
+
for el in elements:
|
| 82 |
+
el_type = el.get('type', '')
|
| 83 |
+
|
| 84 |
+
x_pt = el.get('x', 0) * PX_TO_PT + margin_pt
|
| 85 |
+
y_top_pt = el.get('y', 0) * PX_TO_PT + margin_pt
|
| 86 |
+
el_w_pt = el.get('width', 100) * PX_TO_PT
|
| 87 |
+
el_h_pt = el.get('height', 20) * PX_TO_PT
|
| 88 |
+
font_size_pt = el.get('fontSize', 11) * PX_TO_PT
|
| 89 |
+
align = el.get('align', 'left')
|
| 90 |
+
color_hex = el.get('color', '#000000').lstrip('#')
|
| 91 |
+
|
| 92 |
+
try:
|
| 93 |
+
r = int(color_hex[0:2], 16) / 255.0
|
| 94 |
+
g = int(color_hex[2:4], 16) / 255.0
|
| 95 |
+
b = int(color_hex[4:6], 16) / 255.0
|
| 96 |
+
c.setFillColorRGB(r, g, b)
|
| 97 |
+
except Exception:
|
| 98 |
+
c.setFillColorRGB(0, 0, 0)
|
| 99 |
+
|
| 100 |
+
pdf_y = height_pt - y_top_pt - el_h_pt
|
| 101 |
+
|
| 102 |
+
if el_type == 'barcode_image':
|
| 103 |
+
bc_height = el_h_pt * 0.85
|
| 104 |
+
show_text = el.get('showBarcodeText', True)
|
| 105 |
+
bc = code128.Code128(
|
| 106 |
+
str(patient.patient_id),
|
| 107 |
+
barHeight=bc_height,
|
| 108 |
+
barWidth=max(0.5, el.get('barcodeScale', 3) * 0.2),
|
| 109 |
+
humanReadable=bool(show_text)
|
| 110 |
+
)
|
| 111 |
+
bc_width = bc.width
|
| 112 |
+
if align == 'center':
|
| 113 |
+
draw_x = x_pt + (el_w_pt - bc_width) / 2
|
| 114 |
+
elif align == 'right':
|
| 115 |
+
draw_x = x_pt + el_w_pt - bc_width
|
| 116 |
+
else:
|
| 117 |
+
draw_x = x_pt
|
| 118 |
+
bc.drawOn(c, draw_x, height_pt - y_top_pt - bc_height)
|
| 119 |
+
continue
|
| 120 |
+
|
| 121 |
+
txt = ''
|
| 122 |
+
if el_type == 'patient_name':
|
| 123 |
+
txt = str(patient.full_name or '')
|
| 124 |
+
elif el_type == 'patient_id':
|
| 125 |
+
txt = str(patient.patient_id or '')
|
| 126 |
+
elif el_type == 'patient_gender':
|
| 127 |
+
txt = str(patient.gender or '')
|
| 128 |
+
elif el_type == 'patient_age':
|
| 129 |
+
txt = f"{patient.age or 0} {patient.age_unit or 'year'}"
|
| 130 |
+
elif el_type == 'patient_phone':
|
| 131 |
+
txt = f"{patient.phone_key or ''} {patient.phone_number or ''}".strip()
|
| 132 |
+
elif el_type == 'sample_type':
|
| 133 |
+
txt = sample_type
|
| 134 |
+
elif el_type == 'test_list':
|
| 135 |
+
txt = tests_str
|
| 136 |
+
elif el_type == 'test_name':
|
| 137 |
+
txt = test_names[0] if test_names else ''
|
| 138 |
+
elif el_type == 'visit_id':
|
| 139 |
+
txt = str(visit_id or '')
|
| 140 |
+
elif el_type == 'visit_date':
|
| 141 |
+
txt = str(visit_date or '')
|
| 142 |
+
elif el_type == 'lab_name':
|
| 143 |
+
txt = el.get('label', '')
|
| 144 |
+
elif el_type == 'custom_text':
|
| 145 |
+
txt = el.get('customText', el.get('label', ''))
|
| 146 |
+
else:
|
| 147 |
+
txt = el.get('label', '')
|
| 148 |
+
|
| 149 |
+
if not txt:
|
| 150 |
+
continue
|
| 151 |
+
|
| 152 |
+
try:
|
| 153 |
+
reshaped = reshaper.reshape(txt)
|
| 154 |
+
display_txt = get_display(reshaped)
|
| 155 |
+
except Exception:
|
| 156 |
+
display_txt = txt
|
| 157 |
+
|
| 158 |
+
c.setFont(font_name, max(4, font_size_pt))
|
| 159 |
+
text_y = pdf_y + (el_h_pt - font_size_pt) / 2
|
| 160 |
+
|
| 161 |
+
if align == 'center':
|
| 162 |
+
c.drawCentredString(x_pt + el_w_pt / 2, text_y, display_txt)
|
| 163 |
+
elif align == 'right':
|
| 164 |
+
c.drawRightString(x_pt + el_w_pt, text_y, display_txt)
|
| 165 |
+
else:
|
| 166 |
+
c.drawString(x_pt, text_y, display_txt)
|
| 167 |
+
|
| 168 |
+
c.showPage()
|
| 169 |
+
|
| 170 |
+
c.save()
|
| 171 |
+
buffer.seek(0)
|
| 172 |
+
return buffer
|
app/services/permission_service.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app/services/permission_service.py
|
| 2 |
+
# Permission checking for page/button access control.
|
| 3 |
+
|
| 4 |
+
from fastapi import Request
|
| 5 |
+
from sqlmodel import Session, select
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
from app.services.auth_service import get_current_user
|
| 9 |
+
from app.models import UserPermission
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def require_permission(request: Request, session: Session, page_key: str, button_key: str = None) -> bool:
|
| 13 |
+
"""Verifies if the current user has the specified page/button permission."""
|
| 14 |
+
user = get_current_user(request, session)
|
| 15 |
+
if not user:
|
| 16 |
+
return False
|
| 17 |
+
|
| 18 |
+
# Admins always have all permissions
|
| 19 |
+
if user.role == 'admin' or user.username == 'admin':
|
| 20 |
+
return True
|
| 21 |
+
|
| 22 |
+
# Check page permission
|
| 23 |
+
perms = session.exec(
|
| 24 |
+
select(UserPermission).where(
|
| 25 |
+
UserPermission.user_id == user.id,
|
| 26 |
+
UserPermission.page_key == page_key
|
| 27 |
+
)
|
| 28 |
+
).first()
|
| 29 |
+
|
| 30 |
+
if not perms:
|
| 31 |
+
return False
|
| 32 |
+
|
| 33 |
+
# Check specific button permission if requested
|
| 34 |
+
if button_key:
|
| 35 |
+
if not perms.allowed_buttons:
|
| 36 |
+
return False
|
| 37 |
+
try:
|
| 38 |
+
buttons = json.loads(perms.allowed_buttons)
|
| 39 |
+
if button_key not in buttons:
|
| 40 |
+
return False
|
| 41 |
+
except Exception:
|
| 42 |
+
return False
|
| 43 |
+
|
| 44 |
+
return True
|
backup_db.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sqlite3
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
|
| 5 |
+
def backup_database():
|
| 6 |
+
"""
|
| 7 |
+
Safe database backup using SQLite's built-in backup API.
|
| 8 |
+
Unlike shutil.copy2, this handles active connections and WAL mode correctly,
|
| 9 |
+
producing a consistent, non-corrupted backup every time.
|
| 10 |
+
"""
|
| 11 |
+
project_root = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
+
db_file = os.path.join(project_root, "lab_database.db")
|
| 13 |
+
backup_dir = os.path.join(project_root, "backups")
|
| 14 |
+
|
| 15 |
+
if not os.path.exists(db_file):
|
| 16 |
+
print(f"❌ Error: Database file '{db_file}' not found.")
|
| 17 |
+
return False
|
| 18 |
+
|
| 19 |
+
if not os.path.exists(backup_dir):
|
| 20 |
+
os.makedirs(backup_dir)
|
| 21 |
+
print(f"📁 Created backup directory: {backup_dir}")
|
| 22 |
+
|
| 23 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 24 |
+
backup_file = os.path.join(backup_dir, f"lab_database_{timestamp}.db")
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
# Connect to the live database
|
| 28 |
+
source = sqlite3.connect(db_file)
|
| 29 |
+
# Connect to the backup destination
|
| 30 |
+
dest = sqlite3.connect(backup_file)
|
| 31 |
+
|
| 32 |
+
# Use SQLite's built-in backup API — safe even during active writes
|
| 33 |
+
source.backup(dest)
|
| 34 |
+
|
| 35 |
+
dest.close()
|
| 36 |
+
source.close()
|
| 37 |
+
|
| 38 |
+
size_mb = os.path.getsize(backup_file) / (1024 * 1024)
|
| 39 |
+
print(f"✅ Success: Database backed up to {backup_file} ({size_mb:.2f} MB)")
|
| 40 |
+
|
| 41 |
+
# Cleanup: keep only last 30 backups
|
| 42 |
+
cleanup_old_backups(backup_dir, keep=30)
|
| 43 |
+
|
| 44 |
+
return True
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f"❌ Error during backup: {e}")
|
| 47 |
+
return False
|
| 48 |
+
|
| 49 |
+
def cleanup_old_backups(backup_dir, keep=30):
|
| 50 |
+
"""Remove old backups, keeping only the most recent 'keep' files."""
|
| 51 |
+
try:
|
| 52 |
+
backups = sorted(
|
| 53 |
+
[f for f in os.listdir(backup_dir) if f.startswith("lab_database_") and f.endswith(".db")],
|
| 54 |
+
reverse=True
|
| 55 |
+
)
|
| 56 |
+
for old_backup in backups[keep:]:
|
| 57 |
+
os.remove(os.path.join(backup_dir, old_backup))
|
| 58 |
+
print(f"🗑️ Removed old backup: {old_backup}")
|
| 59 |
+
except Exception as e:
|
| 60 |
+
print(f"⚠️ Cleanup warning: {e}")
|
| 61 |
+
|
| 62 |
+
if __name__ == "__main__":
|
| 63 |
+
backup_database()
|
database.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# database.py
|
| 2 |
+
# ===================================================================
|
| 3 |
+
# BACKWARD-COMPATIBLE BRIDGE — re-exports from app/database.py.
|
| 4 |
+
# Existing code can continue to use: from database import get_session, engine
|
| 5 |
+
# ===================================================================
|
| 6 |
+
|
| 7 |
+
from app.database import engine, get_session, create_db_and_tables
|
deployment_guide.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NexLab LIS Deployment Guide (Server PC)
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
## Step 1: Copying the System
|
| 6 |
+
1. Locate the `NexLab_Published` folder created by the packager.
|
| 7 |
+
2. Copy this entire folder to your target PC (e.g., using a USB Drive).
|
| 8 |
+
3. Place it in a safe location (e.g., `C:\NexLab_LIS`).
|
| 9 |
+
|
| 10 |
+
## Step 2: One-Time Set Up (Target PC)
|
| 11 |
+
1. Open the `NexLab_Published` folder on the new PC.
|
| 12 |
+
2. Double-click `install_requirements.bat`. This will:
|
| 13 |
+
- Create the virtual environment.
|
| 14 |
+
- Install all Python libraries.
|
| 15 |
+
- Download the PDF generation components (Playwright Chrome).
|
| 16 |
+
- *Note: This requires internet access the first time.*
|
| 17 |
+
|
| 18 |
+
## Step 3: Running the System
|
| 19 |
+
1. Double-click `start_nexlab.bat`.
|
| 20 |
+
2. A window will open showing that the server is running.
|
| 21 |
+
3. You can access the system on this PC at: `http://localhost:8000` (or your chosen port).
|
| 22 |
+
|
| 23 |
+
## Extra: How to Change the Port
|
| 24 |
+
If you need to change the port (e.g. to 5000 or 80):
|
| 25 |
+
1. Open `start_nexlab.bat` in Notepad.
|
| 26 |
+
2. Change the line `set "PORT=8000"` to your preferred number.
|
| 27 |
+
3. Save the file and restart the system.
|
| 28 |
+
|
| 29 |
+
## Step 4: Connecting from Other PCs
|
| 30 |
+
1. find the **IP Address** of the Server PC:
|
| 31 |
+
- Open Command Prompt and type `ipconfig`.
|
| 32 |
+
- Look for "IPv4 Address" (e.g., `192.168.1.50`).
|
| 33 |
+
2. On any other PC in the lab, open a browser and go to: `http://192.168.1.50:8000`.
|
| 34 |
+
|
| 35 |
+
## Step 5: (Optional) Automatic Start
|
| 36 |
+
1. To make the server start automatically when you log into Windows:
|
| 37 |
+
2. Double-click `add_to_startup.bat` once.
|
| 38 |
+
|
| 39 |
+
---
|
| 40 |
+
### Requirements for the Server PC:
|
| 41 |
+
- Windows 10/11.
|
| 42 |
+
- Python 3.10 or higher installed (one-time requirement for the environment setup).
|
| 43 |
+
- Port 8000 allowed in Windows Firewall (if connecting from other PCs).
|
device_interfacing/CBC/failed/alh.txt
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PID=1010008
|
| 2 |
+
8=4.33
|
| 3 |
+
10=52.9
|
| 4 |
+
12=44.6
|
| 5 |
+
16=1.5
|
| 6 |
+
14=0.7
|
| 7 |
+
18=0.3
|
| 8 |
+
9=2.29
|
| 9 |
+
11=1.93
|
| 10 |
+
15=0.06
|
| 11 |
+
13=0.03
|
| 12 |
+
17=0.02
|
| 13 |
+
2=4.28
|
| 14 |
+
1=12.3
|
| 15 |
+
6=31.2
|
| 16 |
+
5=28.8
|
| 17 |
+
4=92.3
|
| 18 |
+
7=12.6
|
| 19 |
+
3=39.5
|
| 20 |
+
19=223
|
| 21 |
+
20=9.8
|
| 22 |
+
|
| 23 |
+
|
device_interfacing/CBC/processed/20260426_204913_alh.txt
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PID=1010008
|
| 2 |
+
8=4.33
|
| 3 |
+
10=52.9
|
| 4 |
+
12=44.6
|
| 5 |
+
16=1.5
|
| 6 |
+
14=0.7
|
| 7 |
+
18=0.3
|
| 8 |
+
9=2.29
|
| 9 |
+
11=1.93
|
| 10 |
+
15=0.06
|
| 11 |
+
13=0.03
|
| 12 |
+
17=0.02
|
| 13 |
+
2=4.28
|
| 14 |
+
1=12.3
|
| 15 |
+
6=31.2
|
| 16 |
+
5=28.8
|
| 17 |
+
4=92.3
|
| 18 |
+
7=12.6
|
| 19 |
+
3=39.5
|
| 20 |
+
19=223
|
| 21 |
+
20=9.8
|
| 22 |
+
|
| 23 |
+
|
device_interfacing/device_watcher.py
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# device_interfacing/device_watcher.py
|
| 2 |
+
# =====================================================
|
| 3 |
+
# NexLab Device Link — CBC Folder Watcher
|
| 4 |
+
# =====================================================
|
| 5 |
+
# Standalone service that watches a folder for CBC device
|
| 6 |
+
# result files and writes them directly to the database.
|
| 7 |
+
#
|
| 8 |
+
# Usage:
|
| 9 |
+
# python device_interfacing/device_watcher.py
|
| 10 |
+
#
|
| 11 |
+
# File format expected:
|
| 12 |
+
# PID = 110003
|
| 13 |
+
# 1=4.5
|
| 14 |
+
# 2=23.3
|
| 15 |
+
#
|
| 16 |
+
# Where PID is the patient_id and 1,2,... are parameter IDs.
|
| 17 |
+
# =====================================================
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
import sys
|
| 21 |
+
import subprocess
|
| 22 |
+
|
| 23 |
+
# Resolve the project root (parent of device_interfacing/)
|
| 24 |
+
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 25 |
+
|
| 26 |
+
# =====================================================
|
| 27 |
+
# AUTO-DETECT VENV: If running with system Python,
|
| 28 |
+
# re-launch with the project's venv Python automatically.
|
| 29 |
+
# =====================================================
|
| 30 |
+
VENV_PYTHON = os.path.join(PROJECT_ROOT, "venv", "Scripts", "python.exe")
|
| 31 |
+
|
| 32 |
+
if os.path.exists(VENV_PYTHON) and sys.executable.lower() != VENV_PYTHON.lower():
|
| 33 |
+
# We're NOT running inside the venv — re-launch with venv Python
|
| 34 |
+
print(f"Re-launching with venv Python: {VENV_PYTHON}")
|
| 35 |
+
result = subprocess.call([VENV_PYTHON, os.path.abspath(__file__)])
|
| 36 |
+
sys.exit(result)
|
| 37 |
+
|
| 38 |
+
# =====================================================
|
| 39 |
+
# From here on, we're guaranteed to be in the venv
|
| 40 |
+
# =====================================================
|
| 41 |
+
import time
|
| 42 |
+
import shutil
|
| 43 |
+
import logging
|
| 44 |
+
from datetime import datetime
|
| 45 |
+
from pathlib import Path
|
| 46 |
+
|
| 47 |
+
# CRITICAL: Change working directory to project root BEFORE importing database.
|
| 48 |
+
# database.py uses a relative SQLite path (sqlite:///./lab_database.db),
|
| 49 |
+
# so CWD must be the project root for the DB to be found.
|
| 50 |
+
os.chdir(PROJECT_ROOT)
|
| 51 |
+
sys.path.insert(0, PROJECT_ROOT)
|
| 52 |
+
|
| 53 |
+
from sqlmodel import Session, select
|
| 54 |
+
from database import engine
|
| 55 |
+
from models import (
|
| 56 |
+
Patient, PatientVisit, Order, TestDefinition, TestParameter,
|
| 57 |
+
Result, ResultDetail, AuditLog, ActivityLog
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
# =====================================================
|
| 61 |
+
# CONFIGURATION — Edit these to match your environment
|
| 62 |
+
# =====================================================
|
| 63 |
+
# Watch folder: where the CBC device drops .txt files
|
| 64 |
+
WATCH_FOLDER = r"C:\Users\aliss\Desktop\lab_system\device_interfacing\CBC"
|
| 65 |
+
|
| 66 |
+
# How often to check for new files (seconds) — used in polling mode
|
| 67 |
+
POLL_INTERVAL = 3
|
| 68 |
+
|
| 69 |
+
# System user ID for audit trail (admin = 1)
|
| 70 |
+
SYSTEM_USER_ID = 1
|
| 71 |
+
SYSTEM_USERNAME = "CBC_Device"
|
| 72 |
+
|
| 73 |
+
# Log file
|
| 74 |
+
LOG_FILE = os.path.join(
|
| 75 |
+
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
| 76 |
+
"device_interfacing.log"
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# =====================================================
|
| 80 |
+
# LOGGING SETUP
|
| 81 |
+
# =====================================================
|
| 82 |
+
logger = logging.getLogger("NexLabDeviceLink")
|
| 83 |
+
logger.setLevel(logging.INFO)
|
| 84 |
+
|
| 85 |
+
# File handler
|
| 86 |
+
file_handler = logging.FileHandler(LOG_FILE, encoding="utf-8")
|
| 87 |
+
file_handler.setFormatter(logging.Formatter(
|
| 88 |
+
"%(asctime)s [%(levelname)s] %(message)s",
|
| 89 |
+
datefmt="%Y-%m-%d %H:%M:%S"
|
| 90 |
+
))
|
| 91 |
+
logger.addHandler(file_handler)
|
| 92 |
+
|
| 93 |
+
# Console handler
|
| 94 |
+
console_handler = logging.StreamHandler()
|
| 95 |
+
console_handler.setFormatter(logging.Formatter(
|
| 96 |
+
"%(asctime)s [%(levelname)s] %(message)s",
|
| 97 |
+
datefmt="%H:%M:%S"
|
| 98 |
+
))
|
| 99 |
+
logger.addHandler(console_handler)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# =====================================================
|
| 103 |
+
# FILE PARSER
|
| 104 |
+
# =====================================================
|
| 105 |
+
def parse_result_file(filepath: str) -> dict:
|
| 106 |
+
"""
|
| 107 |
+
Parse a CBC result text file.
|
| 108 |
+
|
| 109 |
+
Expected format:
|
| 110 |
+
PID = 110003
|
| 111 |
+
1=4.5
|
| 112 |
+
2=23.3
|
| 113 |
+
|
| 114 |
+
Returns:
|
| 115 |
+
{
|
| 116 |
+
"patient_id": "110003",
|
| 117 |
+
"results": {1: "4.5", 2: "23.3"}
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
Raises ValueError if format is invalid.
|
| 121 |
+
"""
|
| 122 |
+
patient_id = None
|
| 123 |
+
results = {}
|
| 124 |
+
|
| 125 |
+
with open(filepath, "r", encoding="utf-8-sig") as f:
|
| 126 |
+
for line_num, raw_line in enumerate(f, start=1):
|
| 127 |
+
line = raw_line.strip()
|
| 128 |
+
if not line:
|
| 129 |
+
continue
|
| 130 |
+
|
| 131 |
+
# Parse PID line
|
| 132 |
+
if line.upper().startswith("PID"):
|
| 133 |
+
parts = line.split("=", 1)
|
| 134 |
+
if len(parts) == 2:
|
| 135 |
+
patient_id = parts[1].strip()
|
| 136 |
+
else:
|
| 137 |
+
raise ValueError(f"Line {line_num}: Invalid PID format: '{line}'")
|
| 138 |
+
continue
|
| 139 |
+
|
| 140 |
+
# Parse parameter=value line
|
| 141 |
+
if "=" in line:
|
| 142 |
+
parts = line.split("=", 1)
|
| 143 |
+
try:
|
| 144 |
+
param_id = int(parts[0].strip())
|
| 145 |
+
value = parts[1].strip()
|
| 146 |
+
results[param_id] = value
|
| 147 |
+
except ValueError:
|
| 148 |
+
raise ValueError(f"Line {line_num}: Invalid parameter format: '{line}'")
|
| 149 |
+
else:
|
| 150 |
+
raise ValueError(f"Line {line_num}: Unrecognized line: '{line}'")
|
| 151 |
+
|
| 152 |
+
if patient_id is None:
|
| 153 |
+
raise ValueError("No PID line found in file")
|
| 154 |
+
|
| 155 |
+
if not results:
|
| 156 |
+
raise ValueError("No parameter results found in file")
|
| 157 |
+
|
| 158 |
+
return {"patient_id": patient_id, "results": results}
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# =====================================================
|
| 162 |
+
# DATABASE WRITER
|
| 163 |
+
# =====================================================
|
| 164 |
+
def write_results_to_db(patient_id: str, results: dict) -> dict:
|
| 165 |
+
"""
|
| 166 |
+
Write parsed results to the NexLab database.
|
| 167 |
+
|
| 168 |
+
Logic:
|
| 169 |
+
1. Find the patient by patient_id
|
| 170 |
+
2. Find their latest visit
|
| 171 |
+
3. Find all orders for that visit
|
| 172 |
+
4. Match parameter IDs to orders via TestParameter
|
| 173 |
+
5. Upsert Result + ResultDetail rows
|
| 174 |
+
6. Set order status to "resulted"
|
| 175 |
+
7. Create audit log entries
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
patient_id: The patient's ID string (e.g., "110003")
|
| 179 |
+
results: Dict of {parameter_id: value} (e.g., {1: "4.5", 2: "23.3"})
|
| 180 |
+
|
| 181 |
+
Returns:
|
| 182 |
+
Summary dict with counts of what was updated.
|
| 183 |
+
"""
|
| 184 |
+
now = datetime.now()
|
| 185 |
+
summary = {
|
| 186 |
+
"patient_id": patient_id,
|
| 187 |
+
"parameters_matched": 0,
|
| 188 |
+
"orders_updated": 0,
|
| 189 |
+
"parameters_skipped": [],
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
with Session(engine) as session:
|
| 193 |
+
# Step 1: Find patient
|
| 194 |
+
patient = session.exec(
|
| 195 |
+
select(Patient).where(Patient.patient_id == patient_id)
|
| 196 |
+
).first()
|
| 197 |
+
|
| 198 |
+
if not patient:
|
| 199 |
+
raise ValueError(f"Patient not found: {patient_id}")
|
| 200 |
+
|
| 201 |
+
# Step 2: Find latest visit
|
| 202 |
+
visit = session.exec(
|
| 203 |
+
select(PatientVisit)
|
| 204 |
+
.where(PatientVisit.patient_id == patient.id)
|
| 205 |
+
.order_by(PatientVisit.id.desc())
|
| 206 |
+
).first()
|
| 207 |
+
|
| 208 |
+
if not visit:
|
| 209 |
+
raise ValueError(f"No visit found for patient: {patient_id}")
|
| 210 |
+
|
| 211 |
+
# Step 3: Find all orders for this visit (excluding no_sample)
|
| 212 |
+
orders = session.exec(
|
| 213 |
+
select(Order)
|
| 214 |
+
.where(Order.visit_id == visit.id, Order.status != "no_sample")
|
| 215 |
+
).all()
|
| 216 |
+
|
| 217 |
+
if not orders:
|
| 218 |
+
raise ValueError(f"No orders found for patient {patient_id}, visit {visit.visit_id}")
|
| 219 |
+
|
| 220 |
+
# Step 4: Build a map of parameter_id → order
|
| 221 |
+
# This tells us which order each parameter belongs to
|
| 222 |
+
param_to_order = {}
|
| 223 |
+
for order in orders:
|
| 224 |
+
# Skip already finalized orders
|
| 225 |
+
if order.status == "double_authorized":
|
| 226 |
+
continue
|
| 227 |
+
|
| 228 |
+
test_params = session.exec(
|
| 229 |
+
select(TestParameter).where(TestParameter.test_id == order.test_id)
|
| 230 |
+
).all()
|
| 231 |
+
|
| 232 |
+
for tp in test_params:
|
| 233 |
+
param_to_order[tp.parameter_id] = order
|
| 234 |
+
|
| 235 |
+
# Step 5: Group results by order
|
| 236 |
+
order_results = {} # order_id -> list of (param_id, value)
|
| 237 |
+
unmatched_params = []
|
| 238 |
+
|
| 239 |
+
for param_id, value in results.items():
|
| 240 |
+
if param_id in param_to_order:
|
| 241 |
+
order = param_to_order[param_id]
|
| 242 |
+
if order.id not in order_results:
|
| 243 |
+
order_results[order.id] = []
|
| 244 |
+
order_results[order.id].append((param_id, value))
|
| 245 |
+
else:
|
| 246 |
+
unmatched_params.append(param_id)
|
| 247 |
+
|
| 248 |
+
if unmatched_params:
|
| 249 |
+
summary["parameters_skipped"] = unmatched_params
|
| 250 |
+
logger.warning(
|
| 251 |
+
f" Parameters not matching any order: {unmatched_params}"
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
if not order_results:
|
| 255 |
+
raise ValueError(
|
| 256 |
+
f"None of the parameters ({list(results.keys())}) "
|
| 257 |
+
f"match any order for patient {patient_id}"
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
# Step 6: Write results to database
|
| 261 |
+
for order_id, param_values in order_results.items():
|
| 262 |
+
order = session.get(Order, order_id)
|
| 263 |
+
if not order:
|
| 264 |
+
continue
|
| 265 |
+
|
| 266 |
+
# Upsert parent Result
|
| 267 |
+
result = session.exec(
|
| 268 |
+
select(Result).where(Result.order_id == order_id)
|
| 269 |
+
).first()
|
| 270 |
+
|
| 271 |
+
if not result:
|
| 272 |
+
result = Result(
|
| 273 |
+
order_id=order_id,
|
| 274 |
+
result_value="",
|
| 275 |
+
rerun_result="",
|
| 276 |
+
flag="",
|
| 277 |
+
note="",
|
| 278 |
+
entered_by=SYSTEM_USER_ID,
|
| 279 |
+
entered_at=now,
|
| 280 |
+
)
|
| 281 |
+
session.add(result)
|
| 282 |
+
session.flush() # Need result.id for details
|
| 283 |
+
|
| 284 |
+
# Upsert each ResultDetail
|
| 285 |
+
for param_id, value in param_values:
|
| 286 |
+
detail = session.exec(
|
| 287 |
+
select(ResultDetail).where(
|
| 288 |
+
ResultDetail.result_id == result.id,
|
| 289 |
+
ResultDetail.parameter_id == param_id,
|
| 290 |
+
)
|
| 291 |
+
).first()
|
| 292 |
+
|
| 293 |
+
if not detail:
|
| 294 |
+
detail = ResultDetail(
|
| 295 |
+
result_id=result.id,
|
| 296 |
+
parameter_id=param_id,
|
| 297 |
+
)
|
| 298 |
+
session.add(detail)
|
| 299 |
+
|
| 300 |
+
detail.result_value = value
|
| 301 |
+
session.add(detail)
|
| 302 |
+
summary["parameters_matched"] += 1
|
| 303 |
+
|
| 304 |
+
# Update order status to "resulted" (not authorized — needs human review)
|
| 305 |
+
if order.status in ("ordered", "resulted"):
|
| 306 |
+
order.status = "resulted"
|
| 307 |
+
session.add(order)
|
| 308 |
+
summary["orders_updated"] += 1
|
| 309 |
+
|
| 310 |
+
# Step 7: Audit log
|
| 311 |
+
try:
|
| 312 |
+
import json
|
| 313 |
+
audit_entry = AuditLog(
|
| 314 |
+
table_name="result",
|
| 315 |
+
record_id=visit.id,
|
| 316 |
+
action="DEVICE_IMPORT",
|
| 317 |
+
user_id=SYSTEM_USER_ID,
|
| 318 |
+
username=SYSTEM_USERNAME,
|
| 319 |
+
old_values=None,
|
| 320 |
+
new_values=json.dumps({
|
| 321 |
+
"source": "CBC_Device",
|
| 322 |
+
"patient_id": patient_id,
|
| 323 |
+
"parameters_updated": summary["parameters_matched"],
|
| 324 |
+
"orders_updated": summary["orders_updated"],
|
| 325 |
+
}),
|
| 326 |
+
created_at=now,
|
| 327 |
+
)
|
| 328 |
+
session.add(audit_entry)
|
| 329 |
+
|
| 330 |
+
activity = ActivityLog(
|
| 331 |
+
action_type="DEVICE_IMPORT",
|
| 332 |
+
description=(
|
| 333 |
+
f"CBC device imported {summary['parameters_matched']} result(s) "
|
| 334 |
+
f"for patient {patient_id}"
|
| 335 |
+
),
|
| 336 |
+
user_id=SYSTEM_USER_ID,
|
| 337 |
+
username=SYSTEM_USERNAME,
|
| 338 |
+
target_type="patient",
|
| 339 |
+
target_id=patient.id,
|
| 340 |
+
)
|
| 341 |
+
session.add(activity)
|
| 342 |
+
except Exception as e:
|
| 343 |
+
logger.warning(f" Audit log failed (non-critical): {e}")
|
| 344 |
+
|
| 345 |
+
session.commit()
|
| 346 |
+
|
| 347 |
+
return summary
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
# =====================================================
|
| 351 |
+
# FILE PROCESSOR
|
| 352 |
+
# =====================================================
|
| 353 |
+
def process_file(filepath: str) -> bool:
|
| 354 |
+
"""
|
| 355 |
+
Process a single result file: parse → write to DB → move to processed/failed.
|
| 356 |
+
Returns True on success, False on failure.
|
| 357 |
+
"""
|
| 358 |
+
filename = os.path.basename(filepath)
|
| 359 |
+
logger.info(f"Found new file: {filename}")
|
| 360 |
+
|
| 361 |
+
watch_dir = os.path.dirname(filepath)
|
| 362 |
+
processed_dir = os.path.join(watch_dir, "processed")
|
| 363 |
+
failed_dir = os.path.join(watch_dir, "failed")
|
| 364 |
+
os.makedirs(processed_dir, exist_ok=True)
|
| 365 |
+
os.makedirs(failed_dir, exist_ok=True)
|
| 366 |
+
|
| 367 |
+
try:
|
| 368 |
+
# Parse the file
|
| 369 |
+
data = parse_result_file(filepath)
|
| 370 |
+
logger.info(
|
| 371 |
+
f"Processing results for Patient ID: {data['patient_id']} "
|
| 372 |
+
f"({len(data['results'])} parameters)"
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
# Write to database
|
| 376 |
+
summary = write_results_to_db(data["patient_id"], data["results"])
|
| 377 |
+
logger.info(
|
| 378 |
+
f"✅ Successfully updated results for Patient {data['patient_id']} — "
|
| 379 |
+
f"{summary['parameters_matched']} params, "
|
| 380 |
+
f"{summary['orders_updated']} orders updated"
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
# Move to processed folder (add timestamp to avoid name collisions)
|
| 384 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 385 |
+
dest_name = f"{timestamp}_{filename}"
|
| 386 |
+
dest_path = os.path.join(processed_dir, dest_name)
|
| 387 |
+
shutil.move(filepath, dest_path)
|
| 388 |
+
logger.info(f"Moved {filename} → processed/{dest_name}")
|
| 389 |
+
|
| 390 |
+
return True
|
| 391 |
+
|
| 392 |
+
except ValueError as e:
|
| 393 |
+
# Known error (bad format, missing patient, etc.)
|
| 394 |
+
logger.error(f"❌ Failed to process {filename}: {e}")
|
| 395 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 396 |
+
dest_name = f"{timestamp}_{filename}"
|
| 397 |
+
dest_path = os.path.join(failed_dir, dest_name)
|
| 398 |
+
shutil.move(filepath, dest_path)
|
| 399 |
+
logger.info(f"Moved {filename} → failed/{dest_name}")
|
| 400 |
+
return False
|
| 401 |
+
|
| 402 |
+
except Exception as e:
|
| 403 |
+
# Unexpected error
|
| 404 |
+
logger.error(f"❌ Unexpected error processing {filename}: {e}")
|
| 405 |
+
import traceback
|
| 406 |
+
logger.error(traceback.format_exc())
|
| 407 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 408 |
+
dest_name = f"{timestamp}_{filename}"
|
| 409 |
+
dest_path = os.path.join(failed_dir, dest_name)
|
| 410 |
+
try:
|
| 411 |
+
shutil.move(filepath, dest_path)
|
| 412 |
+
logger.info(f"Moved {filename} → failed/{dest_name}")
|
| 413 |
+
except Exception:
|
| 414 |
+
pass
|
| 415 |
+
return False
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
# =====================================================
|
| 419 |
+
# STARTUP — Process any existing files first
|
| 420 |
+
# =====================================================
|
| 421 |
+
def process_existing_files(watch_folder: str):
|
| 422 |
+
"""Process any .txt files already in the watch folder on startup."""
|
| 423 |
+
existing = sorted(Path(watch_folder).glob("*.txt"))
|
| 424 |
+
if existing:
|
| 425 |
+
logger.info(f"Found {len(existing)} existing file(s) to process")
|
| 426 |
+
for fp in existing:
|
| 427 |
+
process_file(str(fp))
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
# =====================================================
|
| 431 |
+
# WATCHER — Two modes: watchdog (preferred) or polling
|
| 432 |
+
# =====================================================
|
| 433 |
+
def start_watchdog_watcher(watch_folder: str):
|
| 434 |
+
"""Use the watchdog library for efficient file system monitoring."""
|
| 435 |
+
from watchdog.observers import Observer
|
| 436 |
+
from watchdog.events import FileSystemEventHandler
|
| 437 |
+
|
| 438 |
+
class CBCFileHandler(FileSystemEventHandler):
|
| 439 |
+
def on_created(self, event):
|
| 440 |
+
if event.is_directory:
|
| 441 |
+
return
|
| 442 |
+
if event.src_path.lower().endswith(".txt"):
|
| 443 |
+
# Small delay to ensure the file is fully written
|
| 444 |
+
time.sleep(0.5)
|
| 445 |
+
process_file(event.src_path)
|
| 446 |
+
|
| 447 |
+
observer = Observer()
|
| 448 |
+
observer.schedule(CBCFileHandler(), watch_folder, recursive=False)
|
| 449 |
+
observer.start()
|
| 450 |
+
logger.info("Watching with watchdog (real-time file detection)")
|
| 451 |
+
|
| 452 |
+
try:
|
| 453 |
+
while True:
|
| 454 |
+
time.sleep(1)
|
| 455 |
+
except KeyboardInterrupt:
|
| 456 |
+
observer.stop()
|
| 457 |
+
logger.info("Service stopped by user")
|
| 458 |
+
observer.join()
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def start_polling_watcher(watch_folder: str):
|
| 462 |
+
"""Fallback: poll the folder every POLL_INTERVAL seconds."""
|
| 463 |
+
logger.warning(
|
| 464 |
+
"Watchdog library not found. Falling back to polling mode "
|
| 465 |
+
f"(every {POLL_INTERVAL} seconds)."
|
| 466 |
+
)
|
| 467 |
+
logger.info("Tip: Run 'pip install watchdog' for better performance.")
|
| 468 |
+
|
| 469 |
+
known_files = set()
|
| 470 |
+
# Initialize with current files (already processed at startup)
|
| 471 |
+
for fp in Path(watch_folder).glob("*.txt"):
|
| 472 |
+
known_files.add(str(fp))
|
| 473 |
+
|
| 474 |
+
try:
|
| 475 |
+
while True:
|
| 476 |
+
time.sleep(POLL_INTERVAL)
|
| 477 |
+
current_files = set(str(fp) for fp in Path(watch_folder).glob("*.txt"))
|
| 478 |
+
new_files = current_files - known_files
|
| 479 |
+
|
| 480 |
+
for filepath in sorted(new_files):
|
| 481 |
+
# Small delay to ensure the file is fully written
|
| 482 |
+
time.sleep(0.3)
|
| 483 |
+
process_file(filepath)
|
| 484 |
+
|
| 485 |
+
known_files = current_files
|
| 486 |
+
except KeyboardInterrupt:
|
| 487 |
+
logger.info("Service stopped by user")
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
# =====================================================
|
| 491 |
+
# MAIN ENTRY POINT
|
| 492 |
+
# =====================================================
|
| 493 |
+
def main():
|
| 494 |
+
print()
|
| 495 |
+
print("=" * 55)
|
| 496 |
+
print(" NexLab Device Link — CBC Folder Watcher")
|
| 497 |
+
print("=" * 55)
|
| 498 |
+
print()
|
| 499 |
+
|
| 500 |
+
# Ensure watch folder exists
|
| 501 |
+
os.makedirs(WATCH_FOLDER, exist_ok=True)
|
| 502 |
+
|
| 503 |
+
logger.info("NexLab Device Link Service Started")
|
| 504 |
+
logger.info(f"Watching folder: {WATCH_FOLDER}")
|
| 505 |
+
|
| 506 |
+
# Process any files already waiting
|
| 507 |
+
process_existing_files(WATCH_FOLDER)
|
| 508 |
+
|
| 509 |
+
# Start watching for new files
|
| 510 |
+
try:
|
| 511 |
+
start_watchdog_watcher(WATCH_FOLDER)
|
| 512 |
+
except ImportError:
|
| 513 |
+
start_polling_watcher(WATCH_FOLDER)
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
if __name__ == "__main__":
|
| 517 |
+
main()
|
excel_files/Departments.xlsx
ADDED
|
Binary file (10.4 kB). View file
|
|
|
excel_files/Devices.xlsx
ADDED
|
Binary file (10.7 kB). View file
|
|
|
excel_files/Ranges.xlsx
ADDED
|
Binary file (65.2 kB). View file
|
|
|
excel_files/ReportNote.xlsx
ADDED
|
Binary file (14.9 kB). View file
|
|
|
excel_files/SampleType.xlsx
ADDED
|
Binary file (11.3 kB). View file
|
|
|
excel_files/Tests.xlsx
ADDED
|
Binary file (28.2 kB). View file
|
|
|
excel_files/parmeters.xlsx
ADDED
|
Binary file (22.2 kB). View file
|
|
|
main.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# main.py
|
| 2 |
+
# ===================================================================
|
| 3 |
+
# BACKWARD-COMPATIBLE BRIDGE — re-exports from app/main.py.
|
| 4 |
+
# uvicorn main:app still works.
|
| 5 |
+
# ===================================================================
|
| 6 |
+
|
| 7 |
+
from app.main import app
|
migrations/migrate_calcontrol.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlmodel import SQLModel
|
| 2 |
+
from database import engine
|
| 3 |
+
from models import CalControl
|
| 4 |
+
|
| 5 |
+
def migrate():
|
| 6 |
+
print("Creating CalControl table if it doesn't exist...")
|
| 7 |
+
SQLModel.metadata.create_all(engine)
|
| 8 |
+
print("Migration successful.")
|
| 9 |
+
|
| 10 |
+
if __name__ == "__main__":
|
| 11 |
+
migrate()
|
migrations/migrate_double_auth.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sqlite3
|
| 2 |
+
|
| 3 |
+
def migrate():
|
| 4 |
+
# Connect to the main database
|
| 5 |
+
conn = sqlite3.connect('lab_database.db')
|
| 6 |
+
cursor = conn.cursor()
|
| 7 |
+
|
| 8 |
+
print("Starting database migration for Double Authorisation...")
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
cursor.execute("ALTER TABLE result ADD COLUMN double_authorized BOOLEAN DEFAULT 0")
|
| 12 |
+
print("Added double_authorized to result")
|
| 13 |
+
except sqlite3.OperationalError as e:
|
| 14 |
+
print(f"double_authorized column might already exist: {e}")
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
cursor.execute("ALTER TABLE result ADD COLUMN double_authorized_by INTEGER")
|
| 18 |
+
print("Added double_authorized_by to result")
|
| 19 |
+
except sqlite3.OperationalError as e:
|
| 20 |
+
print(f"double_authorized_by column might already exist: {e}")
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
cursor.execute("ALTER TABLE result ADD COLUMN double_authorized_at DATETIME")
|
| 24 |
+
print("Added double_authorized_at to result")
|
| 25 |
+
except sqlite3.OperationalError as e:
|
| 26 |
+
print(f"double_authorized_at column might already exist: {e}")
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
cursor.execute("ALTER TABLE result ADD COLUMN unauth_reason VARCHAR")
|
| 30 |
+
print("Added unauth_reason to result")
|
| 31 |
+
except sqlite3.OperationalError as e:
|
| 32 |
+
print(f"unauth_reason column might already exist: {e}")
|
| 33 |
+
|
| 34 |
+
conn.commit()
|
| 35 |
+
conn.close()
|
| 36 |
+
print("Migration completed successfully.")
|
| 37 |
+
|
| 38 |
+
if __name__ == "__main__":
|
| 39 |
+
migrate()
|