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
Files changed (50)
- .gitattributes+1
- .gitignore+7
- System_Update_Guide.md+66-24
- app/database.py+25-6
- app/main.py+45
- app/middleware.py+26-8
- app/models/__init__.py+6-4
- app/models/ai_agent.pyAdded+20
- app/models/finance.py+11
- app/models/lab.py+24
- app/models/order.py+1-1
- app/models/patient.py+3-1
- app/services/ai_data_queries.pyAdded+1239
- app/services/ai_setup_agent.pyAdded
- app/services/barcode_image_service.py+10-12
- app/services/gdrive_service.pyAdded+262
- app/services/patient_service.py+4-3
- app/services/pdf_service.py+5-7
- audit_base.pyAdded+12
- audit_permissions.pyAdded+256
- migrations/migrate_gdrive.pyAdded+59
- migrations/migrate_whatsapp.pyAdded+28
- package_app.py+4-2
- render.yamlAdded+33
- requirements.txt+6
- routes/ai_agent.pyAdded+195
- routes/api.py+1-1
- routes/auth.py+1
- routes/cal_control.py+3-3
- routes/call_centre.py+169-62
- routes/discount_rules.pyAdded+110
- routes/double_auth.py+22-3
- routes/expenses.py+4-4
- routes/geography.py+8-4
- routes/hr.py+16-14
- routes/messages.py+7-7
- routes/patient_status.py+4-3
- routes/patients.py+284-30
- routes/printing.py+356-21
- routes/reports.py+95-28
- routes/results.py+20-11
- routes/tests.py+20-3
- routes/users.py+67-2
- routes/whatsapp_notifier.pyAdded+266
- routes/whatsapp_utils.py+240-157
- safe_update.batAdded+166
- scripts/gdrive_auth.pyAdded+41
- seed_database.sqlite+2-2
- set_admin_perm.py+1-1
- static/vendor/fonts/Amiri-Bold.ttfAdded+3
44 unmodified lines45464744 unmodified linesuploads/attachments/14_e8137e8fb27f236b.pdf filter=lfs diff=lfs merge=lfs -textuploads/chat_media/1ff26a15-52ee-4896-b8a9-1b2fd8f87d86.png filter=lfs diff=lfs merge=lfs -textseed_database.sqlite filter=lfs diff=lfs merge=lfs -text44 unmodified lines4546474844 unmodified linesuploads/attachments/14_e8137e8fb27f236b.pdf filter=lfs diff=lfs merge=lfs -textuploads/chat_media/1ff26a15-52ee-4896-b8a9-1b2fd8f87d86.png filter=lfs diff=lfs merge=lfs -textseed_database.sqlite filter=lfs diff=lfs merge=lfs -textstatic/vendor/fonts/Amiri-Bold.ttf filter=lfs diff=lfs merge=lfs -text
38 unmodified lines39404142434438 unmodified lines.env.env.local# Logs*.log38 unmodified lines3940414243444546474849505138 unmodified lines.env.env.local# Google Drive service account & OAuth credentials*credentials*.json*service-account*.jsonhistorical-results-*.jsonclient_secret.jsontoken.json# Logs*.log
6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152536 unmodified lines- Ensure no one is currently using the system before starting.- Keep a backup of your `lab_database.db` file in a safe location.---## 🚀 The Automatic Way (Recommended)We have provided an automated tool to handle backups and database migrations for you.1. **Close the System**: Stop the server (close the window opened by `start_nexlab.bat`).2. **Run the Update Tool**: Double-click `update_system.bat`.3. **Follow the Prompts**:* The tool will automatically create a backup in the `backups/` folder.* It will ask you to confirm that you have replaced the system files with the new version.* It will automatically run all database migrations (`migrate_*.py`).4. **Restart**: Once completed, run `start_nexlab.bat` as usual.---## 🛠️ The Manual Way (Step-by-Step)If you prefer to perform the update manually, follow these steps exactly:### 1. Backup your Database- Go to your system folder (`lab_system`).- Locate the file `lab_database.db`.- Copy this file and paste it into a folder named `backups`. Rename it to something like `lab_database_backup_DATE.db`.### 2. Replace System Files- Delete the old files (except for `lab_database.db`, `backups/`, and `venv/`).- Copy the new files from the update package into the `lab_system` folder.### 3. Run Database Migrations- If the new system version includes new database columns or features, you must run the migration scripts.- Open a Command Prompt in the folder.- Type: `venv\Scripts\python.exe run_all_migrations.py`- Press Enter.### 4. Restart the Server- Double-click `start_nexlab.bat` to bring the system back online.---## 🆘 Troubleshooting- **Error: "Column already exists"**: This is normal if you have already run the migration before. The scripts are designed to skip columns that already exist.- **System Won't Start**: Check the `update_debug.log` if it exists, or restore your backup by renaming your latest backup file back to `lab_database.db`.> [!WARNING]> DO NOT delete or overwrite `lab_database.db` during an update. This file contains all your data.6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394956 unmodified lines- Ensure no one is currently using the system before starting.- Keep a backup of your `lab_database.db` file in a safe location.> [!CAUTION]> **NEVER delete the entire NexLab_Published folder during an update!**> The database uses WAL mode, which stores recent writes in `lab_database.db-wal`.> Deleting the folder destroys this file and causes **data loss** (patient results, status changes).---## 🚀 The Safe Way (Recommended — One Click)### Prerequisites1. Get the new `NexLab_Published` folder from the developer2. **Stop the NexLab server** (close the `start_nexlab.bat` window)### Steps1. Copy the new `NexLab_Published` folder **next to** your existing one on the server2. **Rename** the new folder to `NexLab_Update`3. Place it **inside** your existing `NexLab_Published` folder4. Double-click **`safe_update.bat`**5. Follow the prompts — it will:- ✅ Flush all pending database writes (WAL checkpoint)- ✅ Create a timestamped backup- ✅ Copy only code files (your database, config, uploads are protected)- ✅ Install any new dependencies- ✅ Run database migrations6. Once complete, run `start_nexlab.bat` to start the system7. Delete the `NexLab_Update` folder (no longer needed)### What is protected (NEVER overwritten):| File/Folder | Contains ||-------------|----------|| `lab_database.db` | All patient data, results, orders || `lab_database.db-wal` | Recent uncommitted writes || `lab_database.db-shm` | Database shared memory || `.env` | Server secrets and configuration || `venv/` | Python virtual environment || `backups/` | Database backups || `uploads/` | Patient attachments and files |---## 🛠️ The Manual Way (Step-by-Step)If you prefer to perform the update manually, follow these steps **exactly**:### 1. Stop the Server- Close the `start_nexlab.bat` window completely.### 2. Checkpoint the Database- Open a Command Prompt in the `NexLab_Published` folder.- Run: `venv\Scripts\python.exe tools\checkpoint_db.py`- This flushes all pending writes into the main database file.### 3. Backup your Database- Run: `venv\Scripts\python.exe tools\backup_db.py`- A backup will be saved in the `backups/` folder.### 4. Replace System Files- **DO NOT delete the folder!**- Delete the old files **EXCEPT** for:- `lab_database.db` (and `.db-wal`, `.db-shm`)- `.env`- `backups/` folder- `venv/` folder- `uploads/` folder- Copy the new files from the update package into the folder.### 5. Install Dependencies- Run: `install_requirements.bat`### 6. Run Database Migrations- Run: `venv\Scripts\python.exe migrations\run_all.py`### 7. Restart the Server- Double-click `start_nexlab.bat` to bring the system back online.---## 🆘 Troubleshooting- **Error: "Column already exists"**: This is normal if you have already run the migration before. The scripts are designed to skip columns that already exist.- **Error: "Database is locked"**: Make sure you completely closed the `start_nexlab.bat` window. Wait a few seconds and try again.- **System Won't Start**: Restore your backup by copying the latest file from `backups/` and renaming it to `lab_database.db`.- **Patient data is missing after update**: You may have lost WAL data. Restore from the backup in the `backups/` folder.> [!WARNING]> DO NOT delete or overwrite `lab_database.db` during an update. This file contains all your data.> Also protect `lab_database.db-wal` and `lab_database.db-shm` — they contain recent writes!
3 unmodified lines45678910111213141516171819202119 unmodified lines4142434445464748493 unmodified linesfrom sqlmodel import create_engine, SQLModel, Sessionfrom sqlalchemy import eventfrom sqlalchemy.pool import StaticPoolfrom app.config import DATABASE_URL# Create engine with StaticPool — optimal for SQLite with multi-threaded access.# StaticPool uses a single connection that is reused across all threads,# which is the safest strategy for SQLite + FastAPI (single worker).engine = create_engine(DATABASE_URL,echo=False,connect_args={"check_same_thread": False},poolclass=StaticPool,)19 unmodified linesdef create_db_and_tables():"""Create all tables defined by SQLModel metadata. Runs once at startup."""SQLModel.metadata.create_all(engine)def get_session():"""Yield a database session for FastAPI dependency injection."""3 unmodified lines4567891011121314151617181920212219 unmodified lines4243444546474849505152535455565758596061626364656667683 unmodified linesfrom sqlmodel import create_engine, SQLModel, Sessionfrom sqlalchemy import eventfrom sqlalchemy.pool import QueuePoolfrom app.config import DATABASE_URL# Create engine with QueuePool to allow concurrent readers with SQLite WAL mode.# This prevents the single-connection bottleneck of StaticPool.engine = create_engine(DATABASE_URL,echo=False,connect_args={"check_same_thread": False},poolclass=QueuePool,pool_size=10,max_overflow=20,)19 unmodified linesdef create_db_and_tables():"""Create all tables defined by SQLModel metadata and ensure schema columns exist."""SQLModel.metadata.create_all(engine)# Auto-add any columns added in recent migrations if missing from existing SQLite tablesfrom sqlalchemy import text_column_migrations = [("patient", "gdrive_folder_id", "TEXT DEFAULT NULL"),("patientvisit", "gdrive_file_id", "TEXT DEFAULT NULL"),("labinfo", "whatsapp_group_id", "VARCHAR DEFAULT NULL"),("labinfo", "whatsapp_notify_enabled", "BOOLEAN DEFAULT 0"),]with engine.begin() as conn:for table_name, col_name, col_def in _column_migrations:try:rows = conn.execute(text(f"PRAGMA table_info([{table_name}])")).fetchall()existing_cols = {r[1] for r in rows}if rows and col_name not in existing_cols:conn.execute(text(f"ALTER TABLE [{table_name}] ADD COLUMN {col_name} {col_def}"))except Exception:passdef get_session():"""Yield a database session for FastAPI dependency injection."""
8 unmodified lines9101112131423 unmodified lines38394041424325 unmodified lines697071727374757667 unmodified lines1441451468 unmodified linesfrom contextlib import asynccontextmanagerimport osimport loggingfrom app.config import SECRET_KEY, pwd_contextfrom app.database import create_db_and_tables, engine23 unmodified linesfrom routes.inventory import router as inventory_routerfrom routes.cal_control import router as cal_control_routerfrom routes.hr import router as hr_router# ===========================25 unmodified lineselse:print("[OK] Admin user already exists")yieldapp = FastAPI(title="NexLab LIS", lifespan=lifespan)67 unmodified linesapp.include_router(inventory_router)app.include_router(cal_control_router)app.include_router(hr_router)8 unmodified lines910111213141523 unmodified lines394041424344454625 unmodified lines7273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811967 unmodified lines1871881891901918 unmodified linesfrom contextlib import asynccontextmanagerimport osimport loggingimport asynciofrom app.config import SECRET_KEY, pwd_contextfrom app.database import create_db_and_tables, engine23 unmodified linesfrom routes.inventory import router as inventory_routerfrom routes.cal_control import router as cal_control_routerfrom routes.hr import router as hr_routerfrom routes.discount_rules import router as discount_rules_routerfrom routes.ai_agent import router as ai_agent_router# ===========================25 unmodified lineselse:print("[OK] Admin user already exists")# ── WhatsApp Group Notification Scheduler ──# Uses a simple asyncio background task (no external dependencies).# Runs check_and_notify() every 15 minutes in a separate thread.from routes.whatsapp_notifier import check_and_notify, process_whatsapp_queueasync def _whatsapp_notifier_loop():"""Background loop: waits 15 min, then checks for overdue patients in a separate thread."""while True:await asyncio.sleep(900) # 15 minutestry:# Offload synchronous network & DB I/O to a background threadawait asyncio.to_thread(check_and_notify)except asyncio.CancelledError:# Allow task cancellation to propagate cleanly during shutdownraiseexcept Exception as e:logging.error(f"[ERR] WhatsApp notifier background task failed: {e}", exc_info=True)async def _whatsapp_queue_loop():"""Background loop: checks queue every 10 seconds."""while True:await asyncio.sleep(10)try:await asyncio.to_thread(process_whatsapp_queue)except asyncio.CancelledError:raiseexcept Exception as e:logging.error(f"[ERR] WhatsApp queue background task failed: {e}", exc_info=True)notifier_task = asyncio.create_task(_whatsapp_notifier_loop())queue_task = asyncio.create_task(_whatsapp_queue_loop())print("[OK] WhatsApp group notification scheduler started (every 15 min)")print("[OK] WhatsApp queue processor started (every 10 sec)")yield# Cancel the background tasks cleanlynotifier_task.cancel()queue_task.cancel()print("[OK] WhatsApp background tasks stopped")app = FastAPI(title="NexLab LIS", lifespan=lifespan)67 unmodified linesapp.include_router(inventory_router)app.include_router(cal_control_router)app.include_router(hr_router)app.include_router(discount_rules_router)app.include_router(ai_agent_router)
123459 unmodified lines151617181920212223242526272829303132333435365 unmodified lines42434445# app/middleware.py# Auth middleware — protects all routes, extracted from main.py for clean SoC.import hashlibfrom starlette.responses import RedirectResponse as StarletteRedirect9 unmodified lines# Paths that don't require authenticationPUBLIC_PATHS = ["/login", "/static/", "/tmp/", "/favicon.ico"]async def auth_middleware(request, call_next):"""HTTP middleware that enforces authentication on all non-public routes."""path = request.url.pathis_public = any(path.startswith(p) for p in PUBLIC_PATHS)# Allow local Headless Chrome to load assets for PDF generationuser_agent = request.headers.get("user-agent", "")if "HeadlessChrome" in user_agent and request.client.host == "127.0.0.1":is_public = True# NexPrint token bypass for barcode/receipt printingif path.startswith("/print-barcode/") or path.startswith("/print-receipt/") or path.startswith("/api/print-barcode-pdf/") or path.startswith("/api/print-barcode-image/"):token = request.query_params.get("print_token", "")if token == PRINT_TOKEN:is_public = Trueif not is_public:with Session(engine) as session:5 unmodified linesrequest.state.user_id = user.idresponse = await call_next(request)return response12345679 unmodified lines171819202122232425262728293031323334353637383940414243444546475 unmodified lines5354555657585960616263# app/middleware.py# Auth middleware — protects all routes, extracted from main.py for clean SoC.# SEC-08: Uses print_token for headless PDF bypass (not User-Agent sniffing).# SEC-12: Adds security headers to all responses.import hashlibfrom starlette.responses import RedirectResponse as StarletteRedirect9 unmodified lines# Paths that don't require authenticationPUBLIC_PATHS = ["/login", "/static/", "/tmp/", "/favicon.ico"]# Paths that can bypass auth when a valid print_token is provided.# This covers both the NexPrint client AND local Headless Chrome PDF generation.PRINT_TOKEN_PATHS = ["/print-barcode/", "/print-receipt/","/api/print-barcode-pdf/", "/api/print-barcode-image/","/print-results/render/", "/api/lab-info",]async def auth_middleware(request, call_next):"""HTTP middleware that enforces authentication on all non-public routes."""path = request.url.pathis_public = any(path.startswith(p) for p in PUBLIC_PATHS)# SEC-08 FIX: Replaced insecure HeadlessChrome User-Agent sniffing with# print_token validation. Any path in PRINT_TOKEN_PATHS can bypass auth# if a valid print_token query param is provided (used by NexPrint client# and Headless Chrome PDF generation).if not is_public:token = request.query_params.get("print_token", "")if token == PRINT_TOKEN:for prefix in PRINT_TOKEN_PATHS:if path.startswith(prefix):is_public = Truebreakif not is_public:with Session(engine) as session:5 unmodified linesrequest.state.user_id = user.idresponse = await call_next(request)# SEC-12: Add security headers to all responsesresponse.headers["X-Content-Type-Options"] = "nosniff"response.headers["X-Frame-Options"] = "SAMEORIGIN"response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"response.headers["X-XSS-Protection"] = "1; mode=block"return response
10 unmodified lines11121314151617181920215 unmodified lines27282930313233343510 unmodified linesfrom app.models.order import Order, Result, ResultDetailfrom app.models.formula import Formula, FormulaItemfrom app.models.package import Partner, Package, PackageTestfrom app.models.lab import LabInfo, PrintTemplatefrom app.models.finance import Payment, ExpenseType, Expensefrom app.models.messaging import Chat, ChatMember, Message, MessageReceiptfrom app.models.inventory import Supply, Inventory, CalControlfrom app.models.hr import Employee, EmployeeAttachment__all__ = ["User", "UserPermission",5 unmodified lines"Order", "Result", "ResultDetail","Formula", "FormulaItem","Partner", "Package", "PackageTest","LabInfo", "PrintTemplate","Payment", "ExpenseType", "Expense","Chat", "ChatMember", "Message", "MessageReceipt","Supply", "Inventory", "CalControl","Employee", "EmployeeAttachment",]10 unmodified lines1112131415161718192021225 unmodified lines2829303132333435363710 unmodified linesfrom app.models.order import Order, Result, ResultDetailfrom app.models.formula import Formula, FormulaItemfrom app.models.package import Partner, Package, PackageTestfrom app.models.lab import LabInfo, PrintTemplate, WhatsAppNotificationLog, WhatsAppQueuefrom app.models.finance import Payment, ExpenseType, Expense, DiscountRulefrom app.models.messaging import Chat, ChatMember, Message, MessageReceiptfrom app.models.inventory import Supply, Inventory, CalControlfrom app.models.hr import Employee, EmployeeAttachmentfrom app.models.ai_agent import AIActionPlan__all__ = ["User", "UserPermission",5 unmodified lines"Order", "Result", "ResultDetail","Formula", "FormulaItem","Partner", "Package", "PackageTest","LabInfo", "PrintTemplate", "WhatsAppNotificationLog", "WhatsAppQueue","Payment", "ExpenseType", "Expense", "DiscountRule","Chat", "ChatMember", "Message", "MessageReceipt","Supply", "Inventory", "CalControl","Employee", "EmployeeAttachment","AIActionPlan",]
1234567891011121314151617181920# app/models/ai_agent.py# Stores proposed and executed AI Lab Setup Agent action plans for human-in-the-loop confirmation.
from typing import Optionalfrom datetime import datetimefrom sqlmodel import SQLModel, Field
class AIActionPlan(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) user_id: int = Field(foreign_key="user.id", index=True) user_prompt: str assistant_message: str interaction_id: Optional[str] = Field(default=None) actions_json: str = Field(default="[]") preview_json: str = Field(default="[]") status: str = Field(default="pending", index=True) # pending | confirmed | cancelled | failed execution_result_json: Optional[str] = Field(default=None) created_at: datetime = Field(default_factory=datetime.now) resolved_at: Optional[datetime] = Field(default=None)39 unmodified lines40414239 unmodified linesedited_by: Optional[int] = Field(default=None, foreign_key="user.id")edited_at: Optional[datetime] = Noneexpense_type: "ExpenseType" = Relationship()39 unmodified lines404142434445464748495051525339 unmodified linesedited_by: Optional[int] = Field(default=None, foreign_key="user.id")edited_at: Optional[datetime] = Noneexpense_type: "ExpenseType" = Relationship()class DiscountRule(SQLModel, table=True):id: Optional[int] = Field(default=None, primary_key=True)min_total: float = Field(default=0.0)max_total: float = Field(default=0.0)max_discount: float = Field(default=0.0)created_at: datetime = Field(default_factory=datetime.now)created_by: Optional[int] = Field(default=None, foreign_key="user.id")edited_by: Optional[int] = Field(default=None, foreign_key="user.id")edited_at: Optional[datetime] = None
16 unmodified lines17181920212236 unmodified lines59606116 unmodified lineslab_phone_2: Optional[str] = Field(default=None)whatsapp_api: Optional[str] = Field(default=None)whatsapp_token: Optional[str] = Field(default=None)telegram_api: Optional[str] = Field(default=None)telegram_token: Optional[str] = Field(default=None)lab_qr_1: Optional[str] = Field(default=None)36 unmodified linescreated_at: datetime = Field(default_factory=datetime.now)edited_by: Optional[int] = Field(default=None, foreign_key="user.id")edited_at: Optional[datetime] = None16 unmodified lines171819202122232436 unmodified lines6162636465666768697071727374757677787980818283848516 unmodified lineslab_phone_2: Optional[str] = Field(default=None)whatsapp_api: Optional[str] = Field(default=None)whatsapp_token: Optional[str] = Field(default=None)whatsapp_group_id: Optional[str] = Field(default=None)whatsapp_notify_enabled: bool = Field(default=False)telegram_api: Optional[str] = Field(default=None)telegram_token: Optional[str] = Field(default=None)lab_qr_1: Optional[str] = Field(default=None)36 unmodified linescreated_at: datetime = Field(default_factory=datetime.now)edited_by: Optional[int] = Field(default=None, foreign_key="user.id")edited_at: Optional[datetime] = Noneclass WhatsAppNotificationLog(SQLModel, table=True):"""Tracks WhatsApp group notifications sent to prevent duplicate messages."""__tablename__ = "whatsapp_notification_log"id: Optional[int] = Field(default=None, primary_key=True)visit_id: int = Field(foreign_key="patientvisit.id", index=True)notification_type: str = Field() # "pending_2h" or "authorize_5m"sent_at: datetime = Field(default_factory=datetime.now)class WhatsAppQueue(SQLModel, table=True):__tablename__ = "whatsapp_queue"id: Optional[int] = Field(default=None, primary_key=True)message_id: Optional[str] = Field(default=None, index=True)visit_id: Optional[str] = Field(default=None, index=True)payload: str = Field(default="{}") # JSON payloadstatus: str = Field(default="pending", index=True)retries: int = Field(default=0)created_at: datetime = Field(default_factory=datetime.now)updated_at: datetime = Field(default_factory=datetime.now)
53 unmodified lines5455565758596053 unmodified linesunauth_reason: Optional[str] = Field(default=None)order: Order = Relationship(back_populates="result")details: List["ResultDetail"] = Relationship(back_populates="result")class ResultDetail(SQLModel, table=True):53 unmodified lines5455565758596053 unmodified linesunauth_reason: Optional[str] = Field(default=None)order: Order = Relationship(back_populates="result")details: List["ResultDetail"] = Relationship(back_populates="result", cascade_delete=True)class ResultDetail(SQLModel, table=True):
40 unmodified lines41424344454628 unmodified lines7576777879808182838440 unmodified linesdeleted_by: Optional[int] = Field(default=None, foreign_key="user.id")deleted_at: Optional[datetime] = Nonedeleted_reason: Optional[str] = Field(default=None)# Relationshipsvisits: List["PatientVisit"] = Relationship(back_populates="patient", cascade_delete=True)28 unmodified linesis_called: bool = Field(default=False)is_whatsapp_sent: bool = Field(default=False)is_printed: bool = Field(default=False)# Relationshipspatient: Optional["Patient"] = Relationship(back_populates="visits")orders: List["Order"] = Relationship(back_populates="visit")class Attachment(SQLModel, table=True):40 unmodified lines4142434445464728 unmodified lines767778798081828384858640 unmodified linesdeleted_by: Optional[int] = Field(default=None, foreign_key="user.id")deleted_at: Optional[datetime] = Nonedeleted_reason: Optional[str] = Field(default=None)gdrive_folder_id: Optional[str] = Field(default=None)# Relationshipsvisits: List["PatientVisit"] = Relationship(back_populates="patient", cascade_delete=True)28 unmodified linesis_called: bool = Field(default=False)is_whatsapp_sent: bool = Field(default=False)is_printed: bool = Field(default=False)gdrive_file_id: Optional[str] = Field(default=None)# Relationshipspatient: Optional["Patient"] = Relationship(back_populates="visits")orders: List["Order"] = Relationship(back_populates="visit", cascade_delete=True)class Attachment(SQLModel, table=True):
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239# app/services/ai_data_queries.py# Comprehensive Iraqi Arabic System Data Query & Analytics Engine for NexLab (Raya System).# Answers natural-language questions across all 14 system modules (Patients, Visits, Results,# Finance/Income, Debts, Tests, Ranges, Packages, Devices, Departments, Sample Types,# Parameters, Inventory/Expiry, Supplies, Expenses, HR Employees, Users/Audit, Lab Info & Discount Rules).
from __future__ import annotations
import refrom datetime import datetime, timedeltafrom typing import Any, Dict, List, Optional, Tuple
from sqlalchemy import funcfrom sqlalchemy.orm import selectinloadfrom sqlmodel import Session, select
from app.models import ( ActivityLog, AuditLog, CalControl, Department, Device, DiscountRule, Employee, Expense, ExpenseType, Formula, Inventory, LabInfo, Order, Package, PackageTest, Parameter, Partner, Patient, PatientVisit, Payment, Province, Region, ReportNote, Result, ResultDetail, SampleType, Supply, TestDefinition, TestDevice, TestParameter, TestRange, TestResultType, User,)
def fmt_iqd(val: Optional[float]) -> str: if val is None: return "0 د.ع" v = float(val) if v.is_integer(): return f"{int(v):,} د.ع" return f"{v:,.2f} د.ع"
# ===================================================================# 1. ARABIC / ENGLISH DEPARTMENT & SAMPLE TYPE SYNONYM MAPS# ===================================================================
DEPT_SYNONYMS: Dict[str, List[str]] = { "hematology": ["امراض الدم", "أمراض الدم", "الدم", "دم", "هيماتولوجي", "hematology", "haematology"], "chemsitry": ["الكيمياء", "كيمياء", "بايوكيمستري", "كيمستري", "chemistry", "chemsitry", "biochemistry", "clinical chemistry"], "hormones": ["الهرمونات", "هرمونات", "هورمونات", "هرمون", "hormones", "hormone", "endocrinology"], "immunology": ["المناعة", "مناعة", "اميونولوجي", "immunology", "immune"], "tumar marker": ["الاورام", "الأورام", "دلالات الاورام", "دلالات الأورام", "اورام", "أورام", "tumor", "tumar", "tumor marker", "tumar marker"], "virology": ["الفيروسات", "فيروسات", "فايروسات", "فايروس", "virology", "virus"], "serology": ["السيرولوجي", "سيرولوجي", "المصول", "مصول", "serology"], "microbiology": ["الاحياء المجهرية", "الأحياء المجهرية", "مايكروبايولوجي", "ميكروبيولوجي", "بكتيريا", "microbiology", "micro"], "genetic": ["الوراثة", "وراثة", "الجينات", "جينات", "genetic", "genetics"], "histopathology": ["الانسجة", "الأنسجة", "انسجة", "أنسجة", "نسيج", "histopathology", "pathology"], "culture": ["الزرع", "زرع", "مزرعة", "مزارع", "culture", "cultures"],}
SAMPLE_SYNONYMS: Dict[str, List[str]] = { "serum c": ["سيرم", "سيروم", "مصل", "مصل الدم", "serum", "serum c"], "serum h": ["سيرم هرمون", "serum h"], "whole blood edta": ["دم كامل", "دم ايديتا", "ايديتا", "edta", "whole blood", "whole blood edta", "دم"], "plasma edta": ["بلازما", "بلازما ايديتا", "plasma", "plasma edta"], "plasma na citrate": ["سترات", "صوديوم سترات", "citrate", "na citrate", "plasma na citrate"], "urine": ["ادرار", "إدرار", "بول", "عينة ادرار", "عينة بول", "urine"], "urine 24hrs": ["ادرار 24 ساعة", "بول 24 ساعة", "urine 24hrs", "24h urine"], "stool": ["خروج", "براز", "غائط", "عينة خروج", "stool"], "semen": ["سائل منوي", "مني", "نطف", "semen"], "csf": ["سائل النخاع", "نخاع شوكي", "csf"], "sputum": ["قشع", "بلغم", "بصاق", "sputum"], "esr": ["ترسيب", "esr"],}
def resolve_department(session: Session, query: str) -> Optional[Department]: q = (query or "").strip().lower() if not q: return None for pfx in ("قسم ", "بقسم ", "للقسم ", "في قسم ", "ال"): if q.startswith(pfx) and len(q) > len(pfx) + 1: q = q[len(pfx):].strip()
depts = session.exec(select(Department)).all() # Direct match for d in depts: dn = (d.department_name or "").strip().lower() if q == dn or q in dn or dn in q: return d
# Synonym match for canonical, syns in DEPT_SYNONYMS.items(): if any(q == s or s in q or q in s for s in syns): for d in depts: if canonical in (d.department_name or "").strip().lower(): return d return None
def resolve_sample_type(session: Session, query: str) -> Optional[SampleType]: q = (query or "").strip().lower() if not q: return None for pfx in ("عينة ", "نوع العينة ", "نوع عينة ", "بعينة ", "ال"): if q.startswith(pfx) and len(q) > len(pfx) + 1: q = q[len(pfx):].strip()
samples = session.exec(select(SampleType)).all() for s in samples: sn = (s.sample_name or "").strip().lower() if q == sn: return s
for canonical, syns in SAMPLE_SYNONYMS.items(): if any(q == syn or syn in q for syn in syns): for s in samples: if canonical == (s.sample_name or "").strip().lower(): return s for s in samples: if canonical in (s.sample_name or "").strip().lower(): return s
for s in samples: sn = (s.sample_name or "").strip().lower() if q in sn or sn in q: return s return None
# ===================================================================# 2. DATE & PERIOD PARSER# ===================================================================
def parse_arabic_date_period(text: str) -> Dict[str, Any]: """Parses date/period expressions from Iraqi Arabic / MSA / English queries.""" now = datetime.now() today_start = now.replace(hour=0, minute=0, second=0, microsecond=0) today_end = now.replace(hour=23, minute=59, second=59, microsecond=999999) t = (text or "").lower()
# Check explicit YYYY-MM-DD dates dates = re.findall(r"\b(20\d{2}-\d{2}-\d{2})\b", t) if len(dates) >= 2: try: d1 = datetime.strptime(dates[0], "%Y-%m-%d").replace(hour=0, minute=0, second=0) d2 = datetime.strptime(dates[1], "%Y-%m-%d").replace(hour=23, minute=59, second=59) return {"mode": "custom", "start": d1, "end": d2, "label_ar": f"من {dates[0]} إلى {dates[1]}"} except ValueError: pass elif len(dates) == 1: try: d1 = datetime.strptime(dates[0], "%Y-%m-%d").replace(hour=0, minute=0, second=0) d2 = d1.replace(hour=23, minute=59, second=59) return {"mode": "custom", "start": d1, "end": d2, "label_ar": f"تاريخ {dates[0]}"} except ValueError: pass
if re.search(r"\b(?:امس|أمس|البارحة|البارحه|يوم امس|yesterday)\b", t): y_start = today_start - timedelta(days=1) y_end = today_end - timedelta(days=1) return {"mode": "yesterday", "start": y_start, "end": y_end, "label_ar": f"أمس ({y_start.strftime('%Y-%m-%d')})"}
if re.search(r"\b(?:اسبوع|أسبوع|الاسبوع|الأسبوع|اخر 7 ايام|week)\b", t): w_start = today_start - timedelta(days=7) return {"mode": "week", "start": w_start, "end": today_end, "label_ar": "آخر 7 أيام"}
if re.search(r"\b(?:شهر|الشهر|هذا الشهر|الشهر الحالي|شهري|month)\b", t): m_start = today_start.replace(day=1) return {"mode": "month", "start": m_start, "end": today_end, "label_ar": f"هذا الشهر ({m_start.strftime('%Y-%m')})"}
if re.search(r"\b(?:سنة|السنة|هذه السنة|سنوي|year)\b", t) and not re.search(r"\d+\s*سنة", t): yr_start = today_start.replace(month=1, day=1) return {"mode": "year", "start": yr_start, "end": today_end, "label_ar": f"سنة {yr_start.year}"}
if re.search(r"\b(?:الكلي|الاجمالي|الإجمالي|كل الاوقات|كل الأوقات|العام|كامل|all|total)\b", t): return {"mode": "all", "start": None, "end": None, "label_ar": "الإجمالي الكلي (كل الأوقات)"}
if re.search(r"\b(?:اليوم|هاليوم|اليومي|today)\b", t): return {"mode": "today", "start": today_start, "end": today_end, "label_ar": f"اليوم ({today_start.strftime('%Y-%m-%d')})"}
return {"mode": "auto", "start": today_start, "end": today_end, "label_ar": f"اليوم ({today_start.strftime('%Y-%m-%d')})"}
# ===================================================================# 3. DOMAIN DATA QUERY FUNCTIONS# ===================================================================
def _calc_financials_for_range( session: Session, start_dt: Optional[datetime], end_dt: Optional[datetime],) -> Dict[str, Any]: v_stmt = ( select(PatientVisit) .options(selectinload(PatientVisit.patient)) .join(Patient, PatientVisit.patient_id == Patient.id) .where(Patient.is_active == True, PatientVisit.is_active == True) ) e_stmt = select(Expense) if start_dt is not None: v_stmt = v_stmt.where(PatientVisit.visit_date >= start_dt) e_stmt = e_stmt.where(Expense.expense_date >= start_dt) if end_dt is not None: v_stmt = v_stmt.where(PatientVisit.visit_date <= end_dt) e_stmt = e_stmt.where(Expense.expense_date <= end_dt)
visits = session.exec(v_stmt.order_by(PatientVisit.visit_date.desc())).all() expenses = session.exec(e_stmt.order_by(Expense.expense_date.desc())).all()
total_received = sum((v.received_amount or 0.0) for v in visits) total_discount = sum((v.discount_amount or 0.0) for v in visits) total_tax = sum((v.tax_amount or 0.0) for v in visits) total_remain = sum((v.remaining_amount or 0.0) for v in visits) gross_without_discount = total_received + total_remain + total_discount - total_tax total_expense = sum((e.amount or 0.0) for e in expenses) net_income = total_received - total_expense
return { "visits": visits, "expenses": expenses, "visits_count": len(visits), "expenses_count": len(expenses), "gross_without_discount": round(gross_without_discount, 2), "total_received": round(total_received, 2), "total_discount": round(total_discount, 2), "total_tax": round(total_tax, 2), "total_remain": round(total_remain, 2), "total_expense": round(total_expense, 2), "net_income": round(net_income, 2), }
def query_financial_report(session: Session, text: str) -> Dict[str, Any]: period = parse_arabic_date_period(text) fin = _calc_financials_for_range(session, period["start"], period["end"]) all_fin = None if period["mode"] in ("auto", "today") and fin["visits_count"] == 0 and fin["expenses_count"] == 0: all_fin = _calc_financials_for_range(session, None, None)
cards: List[Dict[str, Any]] = [ { "mode": "info", "badge_ar": f"التقرير المالي — {period['label_ar']}", "title": f"صافي الدخل: {fmt_iqd(fin['net_income'])}", "fields": [ {"label": "عدد الزيارات", "value": f"{fin['visits_count']} زيارة"}, {"label": "المبلغ الكلي (قبل الخصم)", "value": fmt_iqd(fin["gross_without_discount"])}, {"label": "المبلغ المستلم (الكاش)", "value": fmt_iqd(fin["total_received"])}, {"label": "مجموع الخصومات", "value": fmt_iqd(fin["total_discount"])}, {"label": "المبالغ المتبقية (الديون)", "value": fmt_iqd(fin["total_remain"])}, {"label": "مجموع المصاريف", "value": f"{fmt_iqd(fin['total_expense'])} ({fin['expenses_count']} صرفية)"}, {"label": "الصافي (المستلم - المصاريف)", "value": fmt_iqd(fin["net_income"])}, ], } ]
if all_fin and all_fin["visits_count"] > 0: cards.append( { "mode": "info", "badge_ar": "الإحصائية المالية الكلية للنظام", "title": f"إجمالي المستلم الكلي: {fmt_iqd(all_fin['total_received'])}", "fields": [ {"label": "إجمالي الزيارات بالنظام", "value": f"{all_fin['visits_count']} زيارة"}, {"label": "إجمالي المبالغ قبل الخصم", "value": fmt_iqd(all_fin["gross_without_discount"])}, {"label": "إجمالي المقبوضات", "value": fmt_iqd(all_fin["total_received"])}, {"label": "إجمالي الخصومات", "value": fmt_iqd(all_fin["total_discount"])}, {"label": "إجمالي الديون المتبقية", "value": fmt_iqd(all_fin["total_remain"])}, {"label": "إجمالي المصاريف", "value": fmt_iqd(all_fin["total_expense"])}, {"label": "الصافي الكلي", "value": fmt_iqd(all_fin["net_income"])}, ], } ) msg = ( f"بالنسبة لـ **{period['label_ar']}** لا توجد زيارات مسجلة بعد (0 د.ع).\n" f"عرضتلك أيضاً **الإحصائية المالية الكلية للنظام** ({all_fin['visits_count']} زيارة بإجمالي مقبوضات {fmt_iqd(all_fin['total_received'])} وصافي {fmt_iqd(all_fin['net_income'])}):" ) else: msg = ( f"تدلل! هذا التقرير المالي المفصل لـ **{period['label_ar']}**:\n" f"• عدد الزيارات: **{fin['visits_count']}** | المستلم: **{fmt_iqd(fin['total_received'])}** | المتبقي: **{fmt_iqd(fin['total_remain'])}** | الصافي: **{fmt_iqd(fin['net_income'])}**" )
return { "assistant_message_ar": msg, "preview_cards": cards, }
def query_remaining_debts(session: Session, text: str = "") -> Dict[str, Any]: stmt = ( select(PatientVisit) .options(selectinload(PatientVisit.patient), selectinload(PatientVisit.orders)) .join(Patient, PatientVisit.patient_id == Patient.id) .where( Patient.is_active == True, PatientVisit.is_active == True, PatientVisit.remaining_amount > 0, ) .order_by(PatientVisit.visit_date.desc()) ) all_debt_visits = [ v for v in session.exec(stmt).all() if round(float(v.remaining_amount or 0.0), 0) > 0 ]
users = session.exec(select(User)).all() user_dict = {u.id: u.full_name for u in users}
# Check if user asked about a specific patient's remaining balance t_clean = re.sub( r"\b(?:منو|من|المراجعين|المرضى|مراجع|مريض|للمريض|للمراجع|اللي|الذي|عليه|عليهم|عدهم|بذمته|بذمتهم|على|عن|حساب|باقي|الباقي|متبقي|المتبقي|ديون|الديون|فلوس|مطلوب|مطلوبين|ما|دافع|مسدد|شكد|كم|تقرير|اليوم|امس|أمس)\b", " ", text or "", flags=re.I, ).strip() t_clean = re.sub(r"\s+", " ", t_clean).strip(" ؟?!.")
filtered_visits = all_debt_visits if len(t_clean) >= 3: cand_Matches = [ v for v in all_debt_visits if v.patient and ( t_clean.lower() in (v.patient.full_name or "").lower() or t_clean.lower() in (v.patient.patient_id or "").lower() ) ] if cand_Matches: filtered_visits = cand_Matches
if not filtered_visits: return { "assistant_message_ar": "الحمد لله! لا يوجد أي مراجع عليه مبلغ متبقي (باقي) غير مسدد في النظام حالياً (الباقي الكلي: 0 د.ع).", "preview_cards": [], }
total_debt = sum(round(float(v.remaining_amount or 0.0), 0) for v in filtered_visits)
# Group by patient so the user sees both a per-patient summary AND per-visit details by_patient: Dict[int, Dict[str, Any]] = {} for v in filtered_visits: pid = v.patient_id p_name = v.patient.full_name if v.patient else f"مراجع #{pid}" p_code = v.patient.patient_id if v.patient else "—" p_phone = f"{v.patient.phone_key or ''}{v.patient.phone_number or ''}" if (v.patient and v.patient.phone_number) else "—" rem = round(float(v.remaining_amount or 0.0), 0) paid = round(float(v.received_amount or 0.0), 0) if pid not in by_patient: by_patient[pid] = { "patient_name": p_name, "patient_code": p_code, "phone": p_phone, "total_remain": 0.0, "total_paid": 0.0, "visits_count": 0, } by_patient[pid]["total_remain"] += rem by_patient[pid]["total_paid"] += paid by_patient[pid]["visits_count"] += 1
sorted_patients = sorted(by_patient.values(), key=lambda x: (-x["total_remain"], x["patient_name"]))
# Build direct, crystal-clear text summary listing the patients and their exact remaining amounts lines_ar = [ f"يوجد **{len(sorted_patients)} مراجعين** (في **{len(filtered_visits)} زيارة**) عليهم مبالغ متبقية (باقي) بإجمالي **{fmt_iqd(total_debt)}**:" ] for idx, p_info in enumerate(sorted_patients[:12], start=1): v_note = f"({p_info['visits_count']} زيارات)" if p_info["visits_count"] > 1 else "(زيارة واحدة)" lines_ar.append( f"{idx}. **{p_info['patient_name']}** — الباقي: **{fmt_iqd(p_info['total_remain'])}** | المدفوع: {fmt_iqd(p_info['total_paid'])} {v_note}" )
patient_summary_fields = [ {"label": "عدد المراجعين المطلوبين", "value": f"{len(sorted_patients)} مراجع ({len(filtered_visits)} زيارة)"}, {"label": "إجمالي المبالغ المتبقية (الباقي الكلي)", "value": fmt_iqd(total_debt)}, ] for p_info in sorted_patients[:15]: phone_tag = f" | 📞 {p_info['phone']}" if p_info["phone"] != "—" else "" patient_summary_fields.append({ "label": f"👤 {p_info['patient_name']} ({p_info['patient_code']})", "value": f"الباقي: {fmt_iqd(p_info['total_remain'])} | المدفوع: {fmt_iqd(p_info['total_paid'])} | الزيارات: {p_info['visits_count']}{phone_tag}", })
visit_detail_fields = [] for v in filtered_visits[:15]: p_name = v.patient.full_name if v.patient else f"#{v.patient_id}" rem = round(float(v.remaining_amount or 0.0), 0) paid = round(float(v.received_amount or 0.0), 0) disc = round(float(v.discount_amount or 0.0), 0) visit_total = sum((o.final_price or 0.0) for o in v.orders) if v.orders else (paid + rem) dt_str = v.visit_date.strftime("%Y-%m-%d %H:%M") if v.visit_date else "—" creator = user_dict.get(v.created_by, "—") disc_tag = f" | خصم: {fmt_iqd(disc)}" if disc > 0 else "" visit_detail_fields.append({ "label": f"{p_name} — تاريخ {dt_str}", "value": f"الباقي: {fmt_iqd(rem)} | المدفوع: {fmt_iqd(paid)} من أصل {fmt_iqd(visit_total)}{disc_tag} | الموظف: {creator}", })
return { "assistant_message_ar": "\n".join(lines_ar), "preview_cards": [ { "mode": "info", "badge_ar": "المراجعون الذين عليهم باقي", "title": f"إجمالي الباقي: {fmt_iqd(total_debt)}", "fields": patient_summary_fields, }, { "mode": "info", "badge_ar": "تفاصيل الزيارات المتبقية", "title": f"{len(filtered_visits)} زيارة غير مسددة بالكامل", "fields": visit_detail_fields, }, ], }
def query_discount_visits(session: Session) -> Dict[str, Any]: stmt = ( select(PatientVisit) .options(selectinload(PatientVisit.patient)) .join(Patient, PatientVisit.patient_id == Patient.id) .where( Patient.is_active == True, PatientVisit.is_active == True, PatientVisit.discount_amount > 0, ) .order_by(PatientVisit.visit_date.desc()) ) visits = [v for v in session.exec(stmt).all() if (v.discount_amount or 0) > 0] if not visits: return { "assistant_message_ar": "لا توجد زيارات مسجل عليها خصم في النظام حالياً.", "preview_cards": [], } total_disc = sum((v.discount_amount or 0.0) for v in visits) fields = [ {"label": "عدد الزيارات المشمولة بخصم", "value": f"{len(visits)} زيارة"}, {"label": "إجمالي الخصومات الممنوحة", "value": fmt_iqd(total_disc)}, ] lines = [f"يوجد **{len(visits)} زيارة** ممنوح لها خصم بإجمالي **{fmt_iqd(total_disc)}**:"] for idx, v in enumerate(visits[:12], start=1): p_name = v.patient.full_name if v.patient else f"#{v.patient_id}" dt_str = v.visit_date.strftime("%Y-%m-%d") if v.visit_date else "—" note_str = f" ({v.discount_note})" if v.discount_note else "" lines.append(f"{idx}. **{p_name}** — خصم: **{fmt_iqd(v.discount_amount)}** | التاريخ: {dt_str}{note_str}") fields.append({ "label": f"{p_name} ({dt_str})", "value": f"خصم: {fmt_iqd(v.discount_amount)} | المدفوع: {fmt_iqd(v.received_amount)}{note_str}", }) return { "assistant_message_ar": "\n".join(lines), "preview_cards": [ { "mode": "info", "badge_ar": "تقرير خصومات المراجعين", "title": f"إجمالي الخصومات: {fmt_iqd(total_disc)}", "fields": fields, } ], }
def query_patient_specific(session: Session, query_term: str) -> Optional[Dict[str, Any]]: q = (query_term or "").strip() if not q or len(q) < 2: return None
patients = session.exec( select(Patient) .where( Patient.is_active == True, (Patient.full_name.ilike(f"%{q}%")) | (Patient.patient_id.ilike(f"%{q}%")) | (Patient.phone_number.ilike(f"%{q}%")), ) .order_by(Patient.id.desc()) .limit(5) ).all()
if not patients: return None
cards: List[Dict[str, Any]] = [] for p in patients: visits = session.exec( select(PatientVisit) .where(PatientVisit.patient_id == p.id, PatientVisit.is_active == True) .order_by(PatientVisit.visit_date.desc()) ).all() orders = session.exec( select(Order) .options(selectinload(Order.test), selectinload(Order.result)) .where(Order.patient_id == p.id) .order_by(Order.id.desc()) ).all()
total_paid = sum((v.received_amount or 0.0) for v in visits) total_rem = sum((v.remaining_amount or 0.0) for v in visits)
fields = [ {"label": "كود المريض", "value": p.patient_id}, {"label": "العمر / الجنس", "value": f"{p.age or '—'} {p.age_unit or ''} | {p.gender}"}, {"label": "الهاتف", "value": f"{p.phone_key or ''}{p.phone_number or '—'}"}, {"label": "الطبيب المعالج", "value": p.doctor or "—"}, {"label": "عدد الزيارات", "value": f"{len(visits)} زيارة (مدفوع: {fmt_iqd(total_paid)} | متبقي: {fmt_iqd(total_rem)})"}, ] if orders: order_lines = [] for o in orders[:10]: t_name = o.test.test_name if o.test else f"Test #{o.test_id}" res_val = "قيد الانتظار" if o.result: auth_tag = "✓ مصادق" if o.result.authorized else "غير مصادق" res_val = f"{o.result.result_value or 'تفصيلي'} ({auth_tag})" order_lines.append(f"{t_name}: {res_val}") fields.append({"label": f"الفحوصات ({len(orders)})", "value": " ، ".join(order_lines)})
cards.append({ "mode": "info", "badge_ar": "بطاقة مريض", "title": f"{p.full_name} ({p.patient_id})", "fields": fields, })
return { "assistant_message_ar": f"تم العثور على **{len(patients)} مريض** مطابق لبحثك «{q}»:", "preview_cards": cards, }
def query_patients_overview(session: Session, text: str) -> Dict[str, Any]: # Check if searching for a specific patient name m_search = re.search( r"(?:ابحث\s+عن\s+مريض|ابحث\s+عن\s+مراجع|مريض\s+اسمه|مراجع\s+اسمه|معلومات\s+المريض|معلومات\s+المراجع|نتائج\s+المريض|نتائج\s+المراجع|فحوصات\s+المريض|تحاليل\s+المريض)\s+([A-Za-z0-9_\-\u0600-\u06FF\s]{2,40})", text, re.I, ) if m_search: cand = m_search.group(1).strip() for stop_w in ("اليوم", "امس", "أمس", "المسجلين", "اللي", "الذي", "كم", "شكد", "عدد", "عليه", "عليهم", "باقي", "متبقي", "خصم"): if cand == stop_w or cand.startswith(stop_w + " "): cand = "" break if cand: spec = query_patient_specific(session, cand) if spec: return spec return { "assistant_message_ar": f"لم أجد مريضاً في النظام باسم أو رقم «{cand}».", "preview_cards": [], }
period = parse_arabic_date_period(text) total_patients = session.exec(select(func.count()).select_from(Patient).where(Patient.is_active == True)).one() total_visits = session.exec(select(func.count()).select_from(PatientVisit).where(PatientVisit.is_active == True)).one()
v_stmt = ( select(PatientVisit) .options(selectinload(PatientVisit.patient)) .join(Patient, PatientVisit.patient_id == Patient.id) .where(Patient.is_active == True, PatientVisit.is_active == True) ) if period["start"]: v_stmt = v_stmt.where(PatientVisit.visit_date >= period["start"]) if period["end"]: v_stmt = v_stmt.where(PatientVisit.visit_date <= period["end"]) period_visits = session.exec(v_stmt.order_by(PatientVisit.visit_date.desc())).all()
recent_visits = session.exec( select(PatientVisit) .options(selectinload(PatientVisit.patient)) .join(Patient, PatientVisit.patient_id == Patient.id) .where(Patient.is_active == True, PatientVisit.is_active == True) .order_by(PatientVisit.visit_date.desc()) .limit(12) ).all()
fields = [ {"label": f"زيارات {period['label_ar']}", "value": f"{len(period_visits)} زيارة"}, {"label": "إجمالي المرضى المسجلين بالنظام", "value": f"{total_patients} مريض"}, {"label": "إجمالي الزيارات الكلي", "value": f"{total_visits} زيارة"}, ] display_list = period_visits[:12] if (period["mode"] != "auto" and period_visits) else recent_visits[:10] list_title = f"زيارات {period['label_ar']}" if (period["mode"] != "auto" and period_visits) else "أحدث الزيارات المسجلة بالنظام"
lines = [ f"إحصائيات المرضى والزيارات:\n" f"• **{period['label_ar']}**: **{len(period_visits)} زيارة**\n" f"• **إجمالي المرضى بالنظام**: **{total_patients} مريض** (**{total_visits} زيارة** إجمالية)" ]
for idx, v in enumerate(display_list, start=1): p = v.patient p_name = p.full_name if p else f"#{v.patient_id}" dt_str = v.visit_date.strftime("%Y-%m-%d %H:%M") if v.visit_date else "—" status_flags = [] if v.is_printed: status_flags.append("مطبوع") if v.is_whatsapp_sent: status_flags.append("واتساب ✓") if v.remaining_amount and round(float(v.remaining_amount), 0) > 0: status_flags.append(f"باقي {fmt_iqd(v.remaining_amount)}") flag_str = f" | {' | '.join(status_flags)}" if status_flags else "" fields.append({ "label": f"{idx}. {p_name} ({dt_str})", "value": f"المدفوع: {fmt_iqd(v.received_amount)}{flag_str}", })
return { "assistant_message_ar": "\n".join(lines), "preview_cards": [ { "mode": "info", "badge_ar": "سجل المرضى والزيارات", "title": list_title, "fields": fields, } ], }
def query_orders_and_results_status(session: Session) -> Dict[str, Any]: all_orders = session.exec( select(Order).options( selectinload(Order.test), selectinload(Order.patient), selectinload(Order.result), ).order_by(Order.id.desc()) ).all()
total_orders = len(all_orders) with_result = [o for o in all_orders if o.result is not None] pending_orders = [o for o in all_orders if o.result is None] authorized_results = [o for o in with_result if o.result.authorized] unauth_results = [o for o in with_result if not o.result.authorized] double_auth_results = [o for o in with_result if o.result.double_authorized]
visits = session.exec(select(PatientVisit).where(PatientVisit.is_active == True)).all() unprinted = [v for v in visits if not v.is_printed] unsent_wa = [v for v in visits if not v.is_whatsapp_sent]
fields = [ {"label": "إجمالي الفحوصات المطلوبة (Orders)", "value": f"{total_orders} فحص"}, {"label": "فحوصات بانتظار إدخال النتيجة", "value": f"{len(pending_orders)} فحص"}, {"label": "نتائج مدخلة بانتظار المصادقة", "value": f"{len(unauth_results)} نتيجة"}, {"label": "نتائج مصادقة (Authorized)", "value": f"{len(authorized_results)} نتيجة"}, {"label": "نتائج بتوثيق مزدوج (Double Auth)", "value": f"{len(double_auth_results)} نتيجة"}, {"label": "زيارات غير مطبوعة / لم يرسل لها واتساب", "value": f"غير مطبوعة: {len(unprinted)} | بدون واتساب: {len(unsent_wa)}"}, ]
for o in pending_orders[:6]: p_name = o.patient.full_name if o.patient else f"Patient #{o.patient_id}" t_name = o.test.test_name if o.test else f"Test #{o.test_id}" fields.append({ "label": f"⏳ معلق: {t_name}", "value": f"المريض: {p_name} | الطلب: {o.order_number}", })
return { "assistant_message_ar": ( f"ملخص حالة الفحوصات والنتائج في النظام:\n" f"• إجمالي الطلبات: **{total_orders}** (منها **{len(pending_orders)}** بانتظار النتيجة، و **{len(unauth_results)}** بانتظار المصادقة، و **{len(authorized_results)}** مصادق عليها)." ), "preview_cards": [ { "mode": "info", "badge_ar": "حالة الفحوصات والنتائج", "title": f"مكتمل: {len(with_result)} / {total_orders}", "fields": fields, } ], }
def query_test_or_catalog(session: Session, text: str, find_test_fn: Any) -> Dict[str, Any]: # 1. Check if asking for tests of a specific department m_dept = re.search(r"(?:تحاليل|فحوصات)\s+قسم\s+([A-Za-z0-9_\-\u0600-\u06FF\s]+)", text, re.I) if m_dept: dept = resolve_department(session, m_dept.group(1).strip()) if dept: d_tests = session.exec( select(TestDefinition).where(TestDefinition.department_id == dept.id).order_by(TestDefinition.id.asc()) ).all() fields = [ {"label": "القسم", "value": f"{dept.department_name} (#{dept.id})"}, {"label": "عدد التحاليل في القسم", "value": f"{len(d_tests)} تحليل"}, ] for t in d_tests[:20]: fields.append({ "label": f"{t.test_name} ({t.test_short_name})", "value": fmt_iqd(t.price), }) return { "assistant_message_ar": f"يوجد **{len(d_tests)} تحليل** في قسم **{dept.department_name}**:", "preview_cards": [ { "mode": "info", "badge_ar": f"تحاليل قسم {dept.department_name}", "title": f"{len(d_tests)} تحليل", "fields": fields, } ], }
# 2. Check if asking about a specific test m_spec = re.search( r"(?:سعر\s+تحليل|سعر\s+فحص|شكد\s+سعر|تفاصيل\s+تحليل|معلومات\s+تحليل|رينج\s+تحليل|الرينج\s+الطبيعي\s+لتحليل|نوع\s+نتيجة\s+تحليل|تحليل|فحص)\s+([A-Za-z0-9_\-\u0600-\u06FF\s]{2,35})", text, re.I, ) if m_spec: cand = m_spec.group(1).strip() cand = re.sub(r"\b(?:شكد|كم|شنو|ما\s+هو|بكم|سعره|بالنظام)\b", "", cand, flags=re.I).strip() if cand and cand not in ("الموجودة", "الكل", "جميع", "قسم"): t_obj = find_test_fn(session, cand) if t_obj: dept = session.get(Department, t_obj.department_id) st = session.get(SampleType, t_obj.sample_type_id) tds = session.exec(select(TestDevice).where(TestDevice.test_id == t_obj.id)).all() devs = [session.get(Device, td.device_id) for td in tds] dev_names = [d.device_name for d in devs if d] rts = session.exec(select(TestResultType).where(TestResultType.test_id == t_obj.id)).all() ranges = session.exec(select(TestRange).where(TestRange.test_id == t_obj.id)).all()
fields = [ {"label": "اسم التحليل", "value": f"{t_obj.test_name} (#{t_obj.id})"}, {"label": "المختصر", "value": t_obj.test_short_name or "N/A"}, {"label": "السعر", "value": fmt_iqd(t_obj.price)}, {"label": "القسم", "value": dept.department_name if dept else "N/A"}, {"label": "نوع العينة", "value": st.sample_name if st else "N/A"}, {"label": "الأجهزة المرتبطة", "value": "، ".join(dev_names) if dev_names else "غير محدد"}, {"label": "نوع النتيجة", "value": "، ".join(f"{r.result_type} ({r.selection_options or ''})" for r in rts) if rts else "رقمي افتراضي"}, ] for idx, rng in enumerate(ranges[:8], start=1): rng_val = rng.text_range if rng.range_type == "text" else f"{rng.normal_from} — {rng.normal_to} {rng.unit or ''}" fields.append({ "label": f"رينج #{idx} ({rng.gender_type} | {rng.age_from}-{rng.age_to} {rng.age_from_unit})", "value": rng_val, }) return { "assistant_message_ar": ( f"تفاصيل تحليل **{t_obj.test_name}** ({t_obj.test_short_name}):\n" f"• السعر: **{fmt_iqd(t_obj.price)}** | القسم: **{dept.department_name if dept else 'N/A'}** | العينة: **{st.sample_name if st else 'N/A'}** | عدد الرينجات: **{len(ranges)}**" ), "preview_cards": [ { "mode": "info", "badge_ar": "بطاقة تفاصيل تحليل", "title": f"{t_obj.test_name} ({t_obj.test_short_name})", "fields": fields, } ], }
# 3. General Tests Catalog Summary all_tests = session.exec(select(TestDefinition).order_by(TestDefinition.id.asc())).all() avail_count = sum(1 for t in all_tests if t.is_available) prices = [t.price for t in all_tests if t.price and t.price > 0] min_p = min(prices) if prices else 0 max_p = max(prices) if prices else 0 depts = session.exec(select(Department)).all()
fields = [ {"label": "إجمالي التحاليل في النظام", "value": f"{len(all_tests)} تحليل ({avail_count} متاح)"}, {"label": "نطاق الأسعار", "value": f"من {fmt_iqd(min_p)} إلى {fmt_iqd(max_p)}"}, ] for d in depts: cnt = sum(1 for t in all_tests if t.department_id == d.id) if cnt > 0: fields.append({"label": f"قسم {d.department_name}", "value": f"{cnt} تحليل"})
return { "assistant_message_ar": ( f"يوجد في النظام **{len(all_tests)} تحليل مختبري** موزعة على **{len(depts)} قسم**.\n" "يمكنك سؤالي عن أي تحليل محدد (مثلاً: `تفاصيل تحليل CBC` أو `تحاليل قسم الهرمونات`)." ), "preview_cards": [ { "mode": "info", "badge_ar": "دليل التحاليل والأقسام", "title": f"إجمالي التحاليل: {len(all_tests)}", "fields": fields, } ], }
def query_packages_info(session: Session) -> Dict[str, Any]: pkgs = session.exec( select(Package).options(selectinload(Package.package_tests)).order_by(Package.id.asc()) ).all() if not pkgs: return {"assistant_message_ar": "لا توجد باكجات مسجلة في النظام حالياً.", "preview_cards": []}
cards = [] for p in pkgs: tids = [pt.test_id for pt in p.package_tests] tests = session.exec(select(TestDefinition).where(TestDefinition.id.in_(tids))).all() if tids else [] sum_indiv = sum((t.price or 0.0) for t in tests) fields = [ {"label": "اسم الباكج", "value": f"{p.package_name} ({p.package_short_name})"}, {"label": "سعر الباكج", "value": fmt_iqd(p.price)}, {"label": "مجموع أسعار التحاليل منفردة", "value": fmt_iqd(sum_indiv)}, {"label": f"التحاليل المشمولة ({len(tests)})", "value": "، ".join(t.test_name for t in tests) if tests else "لا توجد تحاليل مربوطة"}, ] if p.package_note: fields.append({"label": "ملاحظة", "value": p.package_note}) cards.append({ "mode": "info", "badge_ar": f"باكج #{p.id}", "title": f"{p.package_name} — {fmt_iqd(p.price)}", "fields": fields, })
return { "assistant_message_ar": f"يوجد **{len(pkgs)} باكجات / عروض** في النظام:", "preview_cards": cards, }
def query_devices_info(session: Session) -> Dict[str, Any]: devices = session.exec(select(Device).order_by(Device.id.asc())).all() all_tds = session.exec(select(TestDevice)).all() counts_by_dev: Dict[int, int] = {} for td in all_tds: counts_by_dev[td.device_id] = counts_by_dev.get(td.device_id, 0) + 1
fields = [{"label": "إجمالي الأجهزة المختبرية", "value": f"{len(devices)} جهاز"}] for d in devices: cnt = counts_by_dev.get(d.id, 0) ser = f" | السيريال: {d.serial_number}" if d.serial_number and d.serial_number != "N/A" else "" fields.append({ "label": f"#{d.id} {d.device_name}", "value": f"{cnt} تحليل مربوط{ser}", })
return { "assistant_message_ar": f"يوجد **{len(devices)} جهاز مختبري** مسجل في النظام:", "preview_cards": [ { "mode": "info", "badge_ar": "أجهزة المختبر", "title": f"إجمالي الأجهزة: {len(devices)}", "fields": fields, } ], }
def query_departments_and_samples_info(session: Session) -> Dict[str, Any]: depts = session.exec(select(Department).order_by(Department.id.asc())).all() samples = session.exec(select(SampleType).order_by(SampleType.id.asc())).all() params_count = session.exec(select(func.count()).select_from(Parameter)).one() notes = session.exec(select(ReportNote).order_by(ReportNote.id.asc())).all()
dept_fields = [{"label": f"#{d.id} {d.department_name}", "value": d.department_note or "نشط"} for d in depts] sample_fields = [ {"label": "عدد أنواع العينات", "value": f"{len(samples)} نوع عينة"}, {"label": "العينات المسجلة", "value": "، ".join(s.sample_name for s in samples[:25]) + ("..." if len(samples) > 25 else "")}, {"label": "عدد البراميترات (Parameters)", "value": f"{params_count} براميتر"}, {"label": "عدد ملاحظات التقارير", "value": f"{len(notes)} ملاحظة"}, ]
return { "assistant_message_ar": ( f"إعدادات الأقسام والعينات في النظام:\n" f"• **{len(depts)} قسم** | **{len(samples)} نوع عينة** | **{params_count} براميتر** | **{len(notes)} ملاحظة تقارير**" ), "preview_cards": [ { "mode": "info", "badge_ar": "الأقسام المختبرية", "title": f"{len(depts)} قسم", "fields": dept_fields, }, { "mode": "info", "badge_ar": "العينات والبراميترات", "title": f"{len(samples)} نوع عينة", "fields": sample_fields, }, ], }
def query_inventory_and_supplies(session: Session) -> Dict[str, Any]: items = session.exec( select(Inventory) .options(selectinload(Inventory.test), selectinload(Inventory.supply)) .where(Inventory.is_active == True) .order_by(Inventory.expiration_date.asc()) ).all() supplies = session.exec(select(Supply).where(Supply.is_active == True)).all() cal_controls = session.exec( select(CalControl).options(selectinload(CalControl.test), selectinload(CalControl.device)).order_by(CalControl.id.desc()) ).all()
now = datetime.now() soon_cutoff = now + timedelta(days=30) expired_count = 0 soon_count = 0
inv_fields = [ {"label": "إجمالي مواد المخزن", "value": f"{len(items)} مادة"}, {"label": "إجمالي المستلزمات (Supplies)", "value": f"{len(supplies)} مستلزم ({'، '.join(s.name for s in supplies) or '—'})"}, {"label": "سجلات المعايرة والكونترول", "value": f"{len(cal_controls)} سجل"}, ]
for it in items: mat_name = (it.test.test_name if it.test else "Test") if it.material_type == "Test" else (it.supply.name if it.supply else "Supply") exp_str = it.expiration_date.strftime("%Y-%m-%d") if it.expiration_date else "—" status_tag = "صالح" if it.expiration_date: if it.expiration_date < now: status_tag = "⚠️ منتهي الصلاحية!" expired_count += 1 elif it.expiration_date <= soon_cutoff: status_tag = "⏰ قريب الانتهاء" soon_count += 1 inv_fields.append({ "label": f"{mat_name} ({it.material_type})", "value": f"الكمية: {it.quantity:g} {it.unit} | اكسباير: {exp_str} ({status_tag})", })
return { "assistant_message_ar": ( f"حالة المخزن والمستلزمات:\n" f"• عدد مواد المخزن: **{len(items)}** (منها **{expired_count}** منتهية الصلاحية و **{soon_count}** قريبة الانتهاء خلال 30 يوم)." ), "preview_cards": [ { "mode": "info", "badge_ar": "المخزن والمستلزمات (Inventory)", "title": f"{len(items)} مادة في المخزن", "fields": inv_fields, } ], }
def query_expenses_info(session: Session, text: str) -> Dict[str, Any]: types = session.exec(select(ExpenseType).order_by(ExpenseType.id.asc())).all() expenses = session.exec( select(Expense).options(selectinload(Expense.expense_type)).order_by(Expense.expense_date.desc()) ).all() total_exp = sum((e.amount or 0.0) for e in expenses)
fields = [ {"label": "إجمالي المصاريف المسجلة", "value": f"{fmt_iqd(total_exp)} ({len(expenses)} عملية صرف)"}, {"label": "أنواع المصاريف المتاحة", "value": "، ".join(t.type_name for t in types) if types else "لا توجد"}, ] for e in expenses[:12]: t_name = e.expense_type.type_name if e.expense_type else f"Type #{e.type_id}" dt_str = e.expense_date.strftime("%Y-%m-%d") if e.expense_date else "—" fields.append({ "label": f"{t_name} ({dt_str})", "value": f"{fmt_iqd(e.amount)}" + (f" — {e.note}" if e.note else ""), })
return { "assistant_message_ar": f"إجمالي المصاريف في النظام: **{fmt_iqd(total_exp)}** عبر **{len(expenses)} صرفية** و **{len(types)} نوع مصاريف**:", "preview_cards": [ { "mode": "info", "badge_ar": "تقرير المصاريف والصرفيات", "title": f"الإجمالي: {fmt_iqd(total_exp)}", "fields": fields, } ], }
def query_hr_and_users(session: Session) -> Dict[str, Any]: employees = session.exec(select(Employee).where(Employee.is_active == True).order_by(Employee.id.asc())).all() users = session.exec(select(User).order_by(User.id.asc())).all() total_salaries = sum((emp.salary or 0.0) for emp in employees)
emp_fields = [ {"label": "عدد الموظفين (HR)", "value": f"{len(employees)} موظف"}, {"label": "مجموع الرواتب الشهرية", "value": fmt_iqd(total_salaries)}, ] for emp in employees: hrs = f"{emp.working_hours_start or '—'} - {emp.working_hours_end or '—'}" emp_fields.append({ "label": f"👤 {emp.full_name}", "value": f"الراتب: {fmt_iqd(emp.salary)} | الدوام: {hrs} | 📞 {emp.phone or '—'}", })
user_fields = [ {"label": "عدد حسابات المستخدمين", "value": f"{len(users)} حساب"}, ] for u in users: status_str = "🟢 متصل" if u.is_online else "⚪ غير متصل" user_fields.append({ "label": f"{u.full_name} (@{u.username})", "value": f"الصلاحية: {u.role} | {status_str}", })
return { "assistant_message_ar": ( f"بيانات الموارد البشرية وحسابات النظام:\n" f"• عدد الموظفين: **{len(employees)}** (إجمالي الرواتب: **{fmt_iqd(total_salaries)}**)\n" f"• عدد حسابات المستخدمين: **{len(users)}**" ), "preview_cards": [ { "mode": "info", "badge_ar": "الموارد البشرية (HR)", "title": f"{len(employees)} موظف", "fields": emp_fields, }, { "mode": "info", "badge_ar": "مستخدمو النظام", "title": f"{len(users)} مستخدم", "fields": user_fields, }, ], }
def query_lab_info_and_rules(session: Session) -> Dict[str, Any]: lab = session.exec(select(LabInfo)).first() rules = session.exec(select(DiscountRule).order_by(DiscountRule.min_total.asc())).all() provinces = session.exec(select(Province)).all() regions = session.exec(select(Region)).all() partners = session.exec(select(Partner)).all()
lab_fields = [] if lab: lab_fields = [ {"label": "اسم المختبر", "value": lab.lab_name or "غير محدد"}, {"label": "العنوان الفرعي", "value": lab.lab_title or "—"}, {"label": "الأطباء", "value": f"{lab.first_doctor_name or '—'} | {lab.second_doctor_name or '—'}"}, {"label": "الهاتف", "value": f"{lab.lab_phone_1 or '—'} | {lab.lab_phone_2 or '—'}"}, {"label": "العنوان", "value": lab.lab_address or "—"}, {"label": "العملة / الضريبة", "value": f"{lab.lab_currency} | الضريبة: {lab.tax_percentage}%"}, {"label": "المحافظات / المناطق / الشركاء", "value": f"{len(provinces)} محافظة | {len(regions)} منطقة | {len(partners)} شريك"}, ] else: lab_fields = [{"label": "معلومات المختبر", "value": "لم يتم إعداد بيانات المختبر بعد"}]
rule_fields = [{"label": "عدد قواعد الخصم", "value": f"{len(rules)} قاعدة"}] for r in rules[:10]: rule_fields.append({ "label": f"من {fmt_iqd(r.min_total)} إلى {fmt_iqd(r.max_total)}", "value": f"أقصى خصم مسموح: {fmt_iqd(r.max_discount)}", })
return { "assistant_message_ar": ( f"معلومات المختبر وقواعد الخصم والمناطق:\n" f"• المختبر: **{lab.lab_name if lab and lab.lab_name else 'NexLab'}** | قواعد الخصم: **{len(rules)} قاعدة**" ), "preview_cards": [ { "mode": "info", "badge_ar": "معلومات المختبر والجغرافيا", "title": lab.lab_name if lab and lab.lab_name else "معلومات المختبر", "fields": lab_fields, }, { "mode": "info", "badge_ar": "قواعد الخصم (Discount Rules)", "title": f"{len(rules)} قاعدة خصم", "fields": rule_fields, }, ], }
def query_system_overview(session: Session) -> Dict[str, Any]: now = datetime.now() today_start = now.replace(hour=0, minute=0, second=0, microsecond=0) today_end = now.replace(hour=23, minute=59, second=59, microsecond=999999)
today_fin = _calc_financials_for_range(session, today_start, today_end) all_fin = _calc_financials_for_range(session, None, None)
total_patients = session.exec(select(func.count()).select_from(Patient).where(Patient.is_active == True)).one() total_tests = session.exec(select(func.count()).select_from(TestDefinition)).one() total_ranges = session.exec(select(func.count()).select_from(TestRange)).one() total_devices = session.exec(select(func.count()).select_from(Device)).one() total_depts = session.exec(select(func.count()).select_from(Department)).one() total_pkgs = session.exec(select(func.count()).select_from(Package)).one() total_orders = session.exec(select(func.count()).select_from(Order)).one() total_results = session.exec(select(func.count()).select_from(Result)).one() total_inv = session.exec(select(func.count()).select_from(Inventory).where(Inventory.is_active == True)).one() total_emp = session.exec(select(func.count()).select_from(Employee).where(Employee.is_active == True)).one()
cards = [ { "mode": "info", "badge_ar": "ملخص المرضى والمالية", "title": f"إجمالي المرضى: {total_patients} | الزيارات: {all_fin['visits_count']}", "fields": [ {"label": "زيارات اليوم / دخل اليوم", "value": f"{today_fin['visits_count']} زيارة | {fmt_iqd(today_fin['total_received'])}"}, {"label": "إجمالي المقبوضات الكلي", "value": fmt_iqd(all_fin["total_received"])}, {"label": "إجمالي الديون المتبقية", "value": fmt_iqd(all_fin["total_remain"])}, {"label": "إجمالي المصاريف الكلي", "value": fmt_iqd(all_fin["total_expense"])}, {"label": "صافي الدخل الكلي", "value": fmt_iqd(all_fin["net_income"])}, {"label": "الفحوصات المطلوبة / النتائج", "value": f"{total_orders} فحص مطلوب | {total_results} نتيجة مدخلة"}, ], }, { "mode": "info", "badge_ar": "ملخص إعدادات المختبر والمخزن", "title": f"{total_tests} تحليل | {total_devices} جهاز", "fields": [ {"label": "التحاليل / الرينجات الطبيعية", "value": f"{total_tests} تحليل | {total_ranges} رينج طبيعي"}, {"label": "الأقسام / الأجهزة / الباكجات", "value": f"{total_depts} قسم | {total_devices} جهاز | {total_pkgs} باكج"}, {"label": "مواد المخزن / الموظفين", "value": f"{total_inv} مادة بالمخزن | {total_emp} موظف"}, ], }, ]
return { "assistant_message_ar": ( "تدلل! هذا **الملخص الشامل لكل بيانات وإحصائيات النظام** حالياً:" ), "preview_cards": cards, }
# ===================================================================# 4. MASTER ROUTER FOR DATA QUERIES# ===================================================================
def try_answer_data_query(session: Session, norm_text: str, find_test_fn: Any) -> Optional[Dict[str, Any]]: """Detects if the user's message is a question / inquiry about system data and returns a structured response with `assistant_message_ar` and `preview_cards`. Returns None if the message is an action command (create/update/delete). """ t = (norm_text or "").strip().lower() if not t: return None
# Do NOT intercept explicit mutation commands (add / edit / delete / link) if re.search( r"^\s*(?:ضيف|اضافة|سوي|انشئ|عدل|غير|خلي|بدل|احذف|امسح|شيل|الغي|اربط|نقل|سجل|ادخل|add|create|update|edit|delete|remove)\b", t, re.I, ): return None
# 1. System overview / general stats if re.search(r"(?:ملخص\s+النظام|احصائيات\s+النظام|احصائيات\s+المختبر|ملخص\s+المختبر|شكو\s+ماكو\s+بالنظام|تقرير\s+شامل|لوحة\s+التحكم|dashboard|overview|summary)", t): return query_system_overview(session)
# 2. Remaining debts / unpaid balances (supports Iraqi 'باقي', 'متبقي', 'عليه باقي', 'مطلوب', 'بذمته', 'ما مسدد', etc.) if re.search( r"(?:\bباقي\b|\bالباقي\b|\bمتبقي\b|\bالمتبقي\b|الديون|\bديون\b|\bدين\b|المبالغ\s+المتبقية|عليه\s+فلوس|عليهم\s+فلوس|عليه\s+باقي|عليهم\s+باقي|بذمته|بذمتهم|مطلوبين|مطلوب\s+فلوس|ما\s+دافع|ما\s+مسدد|غير\s+مسدد|remaining|debts)", t, ): return query_remaining_debts(session, norm_text)
# 2b. Patient Discounts report if re.search( r"(?:تقرير\s+الخصم|تقرير\s+الخصومات|عنده\s+خصم|عدهم\s+خصم|عندهم\s+خصم|عليه\s+خصم|عليهم\s+خصم|شكد\s+خصمنا|الخصومات\s+الممنوحة)", t, ): return query_discount_visits(session)
# 3. Financial / Income / Revenue / Net Profit reports if re.search(r"(?:دخل|الدخل|وارد|الوارد|ايراد|الإيراد|الايرادات|مبيعات|أرباح|ارباح|صافي|الصافي|التقرير\s+المالي|تقرير\s+الدخل|شكد\s+المقبوض|income|revenue|profit)", t): return query_financial_report(session, norm_text)
# 4. Expenses report if re.search(r"(?:مصاريف|المصاريف|صرفيات|الصرفيات|انواع\s+المصاريف|شكد\s+صرفنا|expenses)", t): return query_expenses_info(session, norm_text)
# 5. Inventory / Expiring items / Supplies / CalControl if re.search(r"(?:مخزن|المخزن|مواد\s+المخزن|اكسباير|الاكسباير|منتهية\s+الصلاحية|قريبة\s+الانتهاء|مستلزمات|المستلزمات|معايرة|كونترول|inventory|supplies|expiry|expired)", t): return query_inventory_and_supplies(session)
# 6. HR Employees / Salaries / Users if re.search(r"(?:موظف|موظفين|الموظفين|رواتب|الرواتب|الموارد\s+البشرية|مستخدمين|المستخدمين|الحسابات|منو\s+متصل|employees|salaries|users|hr)", t): return query_hr_and_users(session)
# 7. Pending Orders / Results / Call Centre / Double Auth if re.search(r"(?:تحاليل\s+معلقة|التحاليل\s+المعلقة|غير\s+مكتملة|ما\s+كاملة|بانتظار\s+النتيجة|بانتظار\s+المصادقة|التوثيق\s+المزدوج|غير\s+مطبوعة|ما\s+انطبعت|ما\s+مطبوعة|ما\s+اندزله\s+واتساب|حالة\s+النتائج|حالة\s+الفحوصات|pending\s+orders|results\s+status)", t): return query_orders_and_results_status(session)
# 8. Patients & Visits if re.search(r"(?:المرضى|مرضى|المراجعين|مراجعين|زيارات|الزيارات|ابحث\s+عن\s+مريض|معلومات\s+المريض|نتائج\s+المريض|مريض\s+اسمه|كم\s+مريض|شكد\s+عدد\s+المرضى|patients|visits)", t): return query_patients_overview(session, norm_text)
# 9. Packages if re.search(r"(?:الباكجات|باكجات|العروض|البروفايلات|تفاصيل\s+باكج|شنو\s+الباكجات|كم\s+باكج|packages)", t): return query_packages_info(session)
# 10. Devices if re.search(r"(?:��لأجهزة|الاجهزة|اجهزة\s+المختبر|شنو\s+الاجهزة|كم\s+جهاز|قائمة\s+الاجهزة|devices)", t): return query_devices_info(session)
# 11. Departments / Sample Types / Parameters / Report Notes if re.search(r"(?:الأقسام|الاقسام|اقسام\s+المختبر|أنواع\s+العينات|انواع\s+العينات|العينات|البراميترات|ملاحظات\s+التقارير|departments|sample\s+types|parameters)", t) and not re.search(r"(?:تحاليل\s+قسم|فحوصات\s+قسم)", t): return query_departments_and_samples_info(session)
# 12. Lab Info / Discount Rules / Geography / Partners if re.search(r"(?:معلومات\s+المختبر|اسم\s+المختبر|عنوان\s+المختبر|قواعد\s+الخصم|الخصومات\s+المسموحة|المحافظات|المناطق|الشركاء|lab\s+info|discount\s+rules|partners)", t): return query_lab_info_and_rules(session)
# 13. Tests / Prices / Ranges / Specific Test Question if re.search(r"(?:التحاليل|الفحوصات|كم\s+تحليل|شكد\s+سعر|سعر\s+تحليل|سعر\s+فحص|تفاصيل\s+تحليل|معلومات\s+تحليل|رينج\s+تحليل|الرينج\s+الطبيعي|تحاليل\s+قسم|فحوصات\s+قسم|اسعار\s+التحاليل|tests)", t): return query_test_or_catalog(session, norm_text, find_test_fn)
# 14. Check if user simply typed a known test name, patient name, or device name to inquire about it t_cand = find_test_fn(session, norm_text) if t_cand and len(norm_text) <= 35: return query_test_or_catalog(session, f"تفاصيل تحليل {t_cand.test_name}", find_test_fn)
p_spec = query_patient_specific(session, norm_text) if p_spec and len(norm_text) <= 40: return p_spec
return None55 unmodified lines5657585960616263646566676869707135 unmodified lines10710810911011111211311411511669 unmodified lines18618718818919019119255 unmodified lineselements = json.loads(template.elements) if template.elements else []# Load fontfont_path = os.path.join(STATIC_DIR, 'vendor', 'fonts', 'Cairo-600.ttf')if not os.path.exists(font_path):font_path = None# Arabic reshapertry:reshaper_config = arabic_reshaper.config_for_true_type_font(font_path) if font_path else Noneexcept Exception:reshaper_config = Nonereshaper = arabic_reshaper.ArabicReshaper(configuration=reshaper_config) if reshaper_config else arabic_reshaper.ArabicReshaper()sample_types = list(tests_by_sample_type.keys()) or ['Unknown']pages = []35 unmodified linesif crop_box:bc_img = bc_img.crop(crop_box)# Scale to fill element boxbc_ratio = min(w / bc_img.width, h / bc_img.height)new_w = int(bc_img.width * bc_ratio)new_h = int(bc_img.height * bc_ratio)bc_img = bc_img.resize((new_w, new_h), Image.NEAREST)# Paste bars centered in element box69 unmodified linesbbox = draw.textbbox((0, 0), display_txt, font=pil_font)text_w = bbox[2] - bbox[0]text_h = bbox[3] - bbox[1]text_y = y + (h - text_h) // 2if align == 'center':text_x = x + (w - text_w) // 255 unmodified lines565758596061626364656667686935 unmodified lines10510610710810911011111211311469 unmodified lines18418518618718818919055 unmodified lineselements = json.loads(template.elements) if template.elements else []# Load fontfont_path = os.path.join(STATIC_DIR, 'vendor', 'fonts', 'Amiri-Bold.ttf')if not os.path.exists(font_path):font_path = None# Arabic reshaper — use default config, NOT config_for_true_type_font().# The font-scanner incorrectly marks isolated forms of letters like Alef and Dal# as missing, causing them to render as thin vertical bars on printed labels.reshaper = arabic_reshaper.ArabicReshaper()sample_types = list(tests_by_sample_type.keys()) or ['Unknown']pages = []35 unmodified linesif crop_box:bc_img = bc_img.crop(crop_box)# Scale to fit element box correctly (preserving actual bar height, scale width by barcodeScale)new_h = int(h * 0.85) if show_text else hbarcode_scale = el.get('barcodeScale', 3) / 3.0new_w = min(w, int(bc_img.width * barcode_scale))bc_img = bc_img.resize((new_w, new_h), Image.NEAREST)# Paste bars centered in element box69 unmodified linesbbox = draw.textbbox((0, 0), display_txt, font=pil_font)text_w = bbox[2] - bbox[0]text_h = bbox[3] - bbox[1]text_y = y + (h - text_h) // 2 - bbox[1]if align == 'center':text_x = x + (w - text_w) // 2
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262import osimport ioimport loggingfrom typing import Optional, Tuple
from google.oauth2.credentials import Credentialsfrom google.auth.transport.requests import Requestfrom google.auth.exceptions import RefreshErrorfrom googleapiclient.discovery import buildfrom googleapiclient.http import MediaIoBaseUpload
logger = logging.getLogger("nexlab.gdrive")
# ── Configuration ──────────────────────────────────────────────PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))TOKEN_FILE = os.path.join(PROJECT_ROOT, "token.json")
DEFAULT_ROOT_FOLDER_ID = "1rXfQ6qezsvnS0EpwrJ7r3wclYayQD6zC"_raw_folder_id = os.environ.get("GDRIVE_ROOT_FOLDER_ID", "").strip() or DEFAULT_ROOT_FOLDER_ID# If user pasted the full URL, extract just the ID partif "drive.google.com" in _raw_folder_id: import re # Extract ID from https://drive.google.com/drive/folders/ID or similar match = re.search(r'/folders/([a-zA-Z0-9_-]+)', _raw_folder_id) if match: ROOT_FOLDER_ID = match.group(1) else: ROOT_FOLDER_ID = _raw_folder_id.split("/")[-1].split("?")[0]else: ROOT_FOLDER_ID = _raw_folder_id
SCOPES = ["https://www.googleapis.com/auth/drive"]
_service = None
def _get_service(): """Lazily initialize and cache the Google Drive service.""" global _service if _service is not None: return _service
if not os.path.exists(TOKEN_FILE): # Support Render Secret Files mounted at /etc/secrets/token.json render_secret_token = "/etc/secrets/token.json" if os.path.exists(render_secret_token): try: import shutil shutil.copyfile(render_secret_token, TOKEN_FILE) logger.info("Copied Google Drive token from Render Secret Files (/etc/secrets/token.json)") except Exception as copy_err: logger.warning(f"Could not copy /etc/secrets/token.json to writable path: {copy_err}") if not os.path.exists(TOKEN_FILE): logger.error(f"Google Drive token file not found: {TOKEN_FILE}. Please run scripts/gdrive_auth.py") return None
if not ROOT_FOLDER_ID: logger.error("GDRIVE_ROOT_FOLDER_ID not set in environment") return None
try: creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES) if creds and creds.expired and creds.refresh_token: try: creds.refresh(Request()) with open(TOKEN_FILE, "w", encoding="utf-8") as token_file: token_file.write(creds.to_json()) logger.info("Google Drive token refreshed and updated in token.json successfully") except RefreshError as re: logger.error( f"Google Drive OAuth token refresh failed: {re}. The token has expired or was revoked. " f"Please re-authenticate by running: python scripts/gdrive_auth.py" ) _service = None return None
if not creds or not creds.valid: logger.error( "Google Drive credentials are not valid. " "Please re-authenticate by running: python scripts/gdrive_auth.py" ) _service = None return None
_service = build("drive", "v3", credentials=creds, cache_discovery=False) logger.info("Google Drive service initialized successfully using OAuth token") return _service except Exception as e: logger.error(f"Failed to initialize Google Drive service: {e}") _service = None return None
def find_patient_folder(patient_id: str) -> Optional[str]: """ Search for an existing patient folder inside the root folder. Returns the folder ID if found, None otherwise. """ service = _get_service() if not service: return None
try: query = ( f"mimeType='application/vnd.google-apps.folder' " f"and name contains '{patient_id}' " f"and '{ROOT_FOLDER_ID}' in parents " f"and trashed=false" ) results = service.files().list( q=query, fields="files(id, name)", spaces="drive" ).execute()
files = results.get("files", []) if files: return files[0]["id"] return None except Exception as e: if "invalid_grant" in str(e) or "RefreshError" in str(e): global _service _service = None logger.error(f"Google Drive authorization expired/revoked (invalid_grant). Please run: python scripts/gdrive_auth.py") else: logger.error(f"Error searching for patient folder: {e}") return None
def create_patient_folder(patient_id: str, patient_name: str) -> Optional[str]: """ Create a new folder for the patient inside the root folder. Returns the new folder ID. """ service = _get_service() if not service: return None
try: folder_metadata = { "name": f"{patient_id} - {patient_name}", "mimeType": "application/vnd.google-apps.folder", "parents": [ROOT_FOLDER_ID], } folder = service.files().create( body=folder_metadata, fields="id" ).execute()
folder_id = folder.get("id")
# Make the folder publicly viewable (anyone with the link can view) service.permissions().create( fileId=folder_id, body={"type": "anyone", "role": "reader"}, fields="id", ).execute()
logger.info(f"Created Google Drive folder for patient {patient_id}: {folder_id}") return folder_id except Exception as e: if "invalid_grant" in str(e) or "RefreshError" in str(e): global _service _service = None logger.error(f"Google Drive authorization expired/revoked (invalid_grant). Please run: python scripts/gdrive_auth.py") else: logger.error(f"Error creating patient folder: {e}") return None
def get_or_create_patient_folder(patient_id: str, patient_name: str) -> Optional[str]: """Get existing or create new patient folder. Returns folder ID.""" folder_id = find_patient_folder(patient_id) if folder_id: return folder_id return create_patient_folder(patient_id, patient_name)
def upload_pdf( folder_id: str, file_name: str, pdf_bytes: bytes) -> Optional[str]: """ Upload a PDF file to the given Drive folder. Returns the file ID on success, None on failure. """ service = _get_service() if not service: return None
try: file_metadata = { "name": file_name, "parents": [folder_id], } media = MediaIoBaseUpload( io.BytesIO(pdf_bytes), mimetype="application/pdf", resumable=True, ) uploaded = service.files().create( body=file_metadata, media_body=media, fields="id", ).execute()
file_id = uploaded.get("id")
# Make the file publicly viewable service.permissions().create( fileId=file_id, body={"type": "anyone", "role": "reader"}, fields="id", ).execute()
logger.info(f"Uploaded PDF '{file_name}' to folder {folder_id}: {file_id}") return file_id except Exception as e: if "invalid_grant" in str(e) or "RefreshError" in str(e): global _service _service = None logger.error(f"Google Drive authorization expired/revoked (invalid_grant). Please run: python scripts/gdrive_auth.py") else: logger.error(f"Error uploading PDF to Drive: {e}") return None
def get_folder_url(folder_id: str) -> str: """Get the public URL for a Google Drive folder.""" return f"https://drive.google.com/drive/folders/{folder_id}"
def get_file_url(file_id: str) -> str: """Get the public URL for a Google Drive file.""" return f"https://drive.google.com/file/d/{file_id}/view"
def upload_patient_visit_pdf( patient_id: str, patient_name: str, visit_id: str, visit_date: str, pdf_bytes: bytes,) -> Tuple[Optional[str], Optional[str]]: """ High-level function: creates patient folder if needed, uploads the visit PDF, returns (folder_id, file_id). """ folder_id = get_or_create_patient_folder(patient_id, patient_name) if not folder_id: return None, None
file_name = f"{visit_id}_{visit_date}.pdf" file_id = upload_pdf(folder_id, file_name, pdf_bytes)
return folder_id, file_id
def is_configured() -> bool: """Check if Google Drive integration is properly configured.""" return ( os.path.exists(TOKEN_FILE) and bool(ROOT_FOLDER_ID) )141 unmodified lines142143144145146147148149150141 unmodified linestest_info = {"name": order.test.test_name, "color": status_color}if order.package_name:if order.package_name not in packages:packages[order.package_name] = []packages[order.package_name].append(test_info)else:standalones.append(test_info)141 unmodified lines142143144145146147148149150151141 unmodified linestest_info = {"name": order.test.test_name, "color": status_color}if order.package_name:for pkg_name in [n.strip() for n in order.package_name.split(",") if n.strip()]:if pkg_name not in packages:packages[pkg_name] = []packages[pkg_name].append(test_info)else:standalones.append(test_info)
50 unmodified lines515253545556575 unmodified lines63646566676869707172737450 unmodified linesc = canvas.Canvas(buffer, pagesize=(width_pt, height_pt))# Font registryfont_path = os.path.join(STATIC_DIR, 'vendor', 'fonts', 'Cairo-600.ttf')if os.path.exists(font_path):try:pdfmetrics.registerFont(TTFont('ArabicFont', font_path))5 unmodified lineselements = json.loads(template.elements) if template.elements else []# Arabic reshapertry:reshaper_config = arabic_reshaper.config_for_true_type_font(font_path) if os.path.exists(font_path) else Noneexcept Exception:reshaper_config = Nonereshaper = arabic_reshaper.ArabicReshaper(configuration=reshaper_config) if reshaper_config else arabic_reshaper.ArabicReshaper()PX_TO_PT = 72.0 / 96.050 unmodified lines515253545556575 unmodified lines6364656667686970717250 unmodified linesc = canvas.Canvas(buffer, pagesize=(width_pt, height_pt))# Font registryfont_path = os.path.join(STATIC_DIR, 'vendor', 'fonts', 'Amiri-Bold.ttf')if os.path.exists(font_path):try:pdfmetrics.registerFont(TTFont('ArabicFont', font_path))5 unmodified lineselements = json.loads(template.elements) if template.elements else []# Arabic reshaper — use default config, NOT config_for_true_type_font().# The font-scanner incorrectly marks isolated forms of letters like Alef and Dal# as missing, causing them to render as thin vertical bars on printed labels.reshaper = arabic_reshaper.ArabicReshaper()PX_TO_PT = 72.0 / 96.0
123456789101112import rewith open(r"c:\Users\aliss\Desktop\Raya System\templates\base.html", "r", encoding="utf-8") as f: content = f.read()
pages_in_base = set()for match in re.finditer(r"has_page\s*\(\s*['\"]([^'\"]+)['\"]\s*\)", content): pages_in_base.add(match.group(1))
from audit_permissions import PAGES_REGISTRY
registry_pages = set(PAGES_REGISTRY.keys())print("Pages in Registry NOT checked in base.html:", registry_pages - pages_in_base)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256import osimport re
PAGES_REGISTRY = { # --- Main --- "dashboard": {"label": "Dashboard", "group": "Main", "buttons": []}, # --- Patient Management --- "patient_registration": {"label": "Patient Registration", "group": "Patient Management", "buttons": [ {"key": "save_registration", "label": "Save Registration"}, {"key": "discount", "label": "Discount"}, {"key": "print_barcode", "label": "Print Barcode"}, {"key": "print_receipt", "label": "Print Receipt"}, ]}, "patients": {"label": "Patients", "group": "Patient Management", "buttons": [ {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, {"key": "print_barcode", "label": "Print Barcode"}, {"key": "print_receipt", "label": "Print Receipt"}, {"key": "result_entry", "label": "Result Entry"}, ]}, "patient_edit": {"label": "Patient Edit", "group": "Patient Management", "buttons": [ {"key": "save", "label": "Save Changes"}, {"key": "print_barcode", "label": "Print Barcode"}, {"key": "print_receipt", "label": "Print Receipt"}, {"key": "discount", "label": "Discount"}, {"key": "remove", "label": "Remove Test"}, {"key": "delete_visit", "label": "Delete Visit"}, ]}, "deleted_patients": {"label": "Deleted Patients", "group": "Patient Management", "buttons": [ {"key": "restore", "label": "Restore"}, {"key": "view", "label": "View"}, ]}, "deleted_tests": {"label": "Deleted Tests", "group": "Patient Management", "buttons": []}, "patient_history": {"label": "Patient History", "group": "Patient Management", "buttons": []}, "patient_status": {"label": "Patient Status", "group": "Patient Management", "buttons": []}, # --- Results --- "result_entry": {"label": "Result Entry", "group": "Results", "buttons": [ {"key": "save", "label": "Save Result"}, {"key": "authorize", "label": "Authorize"}, {"key": "duplicate", "label": "Duplicate"}, {"key": "rerun", "label": "ReRun"}, {"key": "no_sample", "label": "No Sample"}, ]}, "double_auth": {"label": "Double Authorisation", "group": "Results", "buttons": [ {"key": "double_authorize", "label": "Double Authorize"}, {"key": "rerun", "label": "ReRun"}, {"key": "unauthorize", "label": "UnAUTH"}, ]}, "no_sample": {"label": "No Sample", "group": "Results", "buttons": [ {"key": "mark_no_sample", "label": "Mark No Sample"}, {"key": "receive_sample", "label": "Receive Sample"}, ]}, # --- Printing & Design --- "print_barcode": {"label": "Print Barcode", "group": "Printing & Design", "buttons": [ {"key": "print", "label": "Print"}, ]}, "barcode_designer": {"label": "Barcode Designer", "group": "Printing & Design", "buttons": [ {"key": "save", "label": "Save Design"}, ]}, "print_receipt": {"label": "Print Receipt", "group": "Printing & Design", "buttons": [ {"key": "print", "label": "Print"}, ]}, "receipt_designer": {"label": "Receipt Designer", "group": "Printing & Design", "buttons": [ {"key": "save", "label": "Save Design"}, ]}, "print_results": {"label": "Print Results", "group": "Printing & Design", "buttons": [ {"key": "print", "label": "Print"}, {"key": "view", "label": "View"}, ]}, "call_centre": {"label": "Call Centre", "group": "Printing & Design", "buttons": [ {"key": "mark_called", "label": "Mark Called"}, {"key": "send_whatsapp", "label": "Send WhatsApp"}, {"key": "mark_printed", "label": "Mark Printed"}, ]}, "result_designer": {"label": "Result Designer", "group": "Printing & Design", "buttons": [ {"key": "save", "label": "Save Design"}, ]}, # --- Lab Setup --- "departments": {"label": "Departments", "group": "Lab Setup", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "sample_types": {"label": "Sample Types", "group": "Lab Setup", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "inventory": {"label": "Inventory", "group": "Lab Setup", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "supplies": {"label": "Supplies", "group": "Lab Setup", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "devices": {"label": "Devices", "group": "Lab Setup", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "parameters": {"label": "Parameters", "group": "Lab Setup", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "report_notes": {"label": "Report Notes", "group": "Lab Setup", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, # --- Tests & Packages --- "tests": {"label": "Tests", "group": "Tests & Packages", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "formulas": {"label": "Formulas", "group": "Tests & Packages", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "cal_control": {"label": "Cal & Control", "group": "Tests & Packages", "buttons": [ {"key": "create", "label": "Create"}, ]}, "test_ranges": {"label": "Test Ranges", "group": "Tests & Packages", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "test_result_types": {"label": "Result Types", "group": "Tests & Packages", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "packages": {"label": "Packages", "group": "Tests & Packages", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, # --- Financials --- "expenses_types": {"label": "Expenses Types", "group": "Financials", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "expenses_entry": {"label": "Expenses Entry", "group": "Financials", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, # --- Reports --- "discount_report": {"label": "Discount Report", "group": "Reports", "buttons": [ {"key": "view", "label": "View Report"}, ]}, "detailed_income": {"label": "Detailed Income", "group": "Reports", "buttons": [ {"key": "view", "label": "View Report"}, ]}, "net_amounts": {"label": "Net Amounts", "group": "Reports", "buttons": [ {"key": "view", "label": "View Report"}, ]}, "payment_records": {"label": "Payment Records", "group": "Reports", "buttons": [ {"key": "view", "label": "View Report"}, ]}, "patients_number": {"label": "Patients Number", "group": "Reports", "buttons": [ {"key": "view", "label": "View Report"}, ]}, "tests_number": {"label": "Tests Number", "group": "Reports", "buttons": [ {"key": "view", "label": "View Report"}, ]}, "visits_number": {"label": "Visits Number", "group": "Reports", "buttons": [ {"key": "view", "label": "View Report"}, ]}, "expenses_report": {"label": "Expenses Report", "group": "Reports", "buttons": [ {"key": "view", "label": "View Report"}, {"key": "edit", "label": "Edit Expense"}, {"key": "delete", "label": "Delete Expense"}, ]}, "remain_report": {"label": "Remain Report", "group": "Reports", "buttons": [ {"key": "view", "label": "View Report"}, ]}, # --- Geography & Partners --- "partners": {"label": "Partners", "group": "Geography & Partners", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "provinces": {"label": "Provinces", "group": "Geography & Partners", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "regions": {"label": "Regions", "group": "Geography & Partners", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "patient_region": {"label": "Patient Region", "group": "Geography & Partners", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, # --- Settings --- "lab_info": {"label": "Lab Info", "group": "Settings", "buttons": [ {"key": "edit", "label": "Edit"}, {"key": "save", "label": "Save"}, ]}, "user_management": {"label": "User Management", "group": "Settings", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "hr": {"label": "Human Resources", "group": "Settings", "buttons": [ {"key": "create", "label": "Create"}, {"key": "edit", "label": "Edit"}, {"key": "delete", "label": "Delete"}, ]}, "activity_logs": {"label": "Activity Logs", "group": "Settings", "buttons": [ {"key": "view", "label": "View"}, ]}, "settings": {"label": "General Settings", "group": "Settings", "buttons": []},}
def extract_from_templates(directory): pages = set() buttons = set() for root, _, files in os.walk(directory): for file in files: if file.endswith(".html"): path = os.path.join(root, file) with open(path, "r", encoding="utf-8") as f: content = f.read() for match in re.finditer(r"has_page\s*\(\s*['\"]([^'\"]+)['\"]\s*\)", content): pages.add(match.group(1)) for match in re.finditer(r"has_button\s*\(\s*['\"]([^'\"]+)['\"]\s*,\s*['\"]([^'\"]+)['\"]\s*\)", content): buttons.add((match.group(1), match.group(2))) return pages, buttons
templates_pages, templates_buttons = extract_from_templates(r"c:\Users\aliss\Desktop\Raya System\templates")registry_pages = set(PAGES_REGISTRY.keys())registry_buttons = set()for page, info in PAGES_REGISTRY.items(): for btn in info.get("buttons", []): registry_buttons.add((page, btn["key"]))
missing_pages = templates_pages - registry_pagesmissing_buttons = templates_buttons - registry_buttons
print(f"Missing Pages: {missing_pages}")print(f"Missing Buttons: {missing_buttons}")
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import sqlite3import os
DB_PATH = "lab_database.db"
def migrate(): print("Checking for Google Drive columns...") if not os.path.exists(DB_PATH): print(f"Error: {DB_PATH} not found.") return
conn = sqlite3.connect(DB_PATH) cursor = conn.cursor()
try: # Check patient table columns cursor.execute("PRAGMA table_info(patient);") patient_cols = [column[1] for column in cursor.fetchall()]
if "gdrive_folder_id" not in patient_cols: print("Adding 'gdrive_folder_id' column to 'patient' table...") cursor.execute("ALTER TABLE patient ADD COLUMN gdrive_folder_id TEXT DEFAULT NULL;") conn.commit() print("Migration successful: 'gdrive_folder_id' column added to patient.") else: print("Migration skipped: 'gdrive_folder_id' already exists in patient.")
# Check patientvisit table columns cursor.execute("PRAGMA table_info(patientvisit);") visit_cols = [column[1] for column in cursor.fetchall()]
if "gdrive_file_id" not in visit_cols: print("Adding 'gdrive_file_id' column to 'patientvisit' table...") cursor.execute("ALTER TABLE patientvisit ADD COLUMN gdrive_file_id TEXT DEFAULT NULL;") conn.commit() print("Migration successful: 'gdrive_file_id' column added to patientvisit.") else: print("Migration skipped: 'gdrive_file_id' already exists in patientvisit.")
# Ensure GDRIVE_ROOT_FOLDER_ID is present in .env env_path = ".env" if os.path.exists(env_path): with open(env_path, "r", encoding="utf-8") as f: env_text = f.read() if "GDRIVE_ROOT_FOLDER_ID" not in env_text: with open(env_path, "a", encoding="utf-8") as f: f.write("\n# Google Drive Integration\nGDRIVE_ROOT_FOLDER_ID=https://drive.google.com/drive/folders/1rXfQ6qezsvnS0EpwrJ7r3wclYayQD6zC?usp=drive_link\n") print("Appended GDRIVE_ROOT_FOLDER_ID to .env.") except Exception as e: print(f"Migration failed: {e}") conn.rollback() finally: conn.close()
if __name__ == "__main__": migrate()12345678910111213141516171819202122232425262728import sqlite3from app.database import create_db_and_tables
def upgrade(): # 1. Add columns to labinfo conn = sqlite3.connect("lab_database.db") cursor = conn.cursor() try: cursor.execute("ALTER TABLE labinfo ADD COLUMN whatsapp_group_id VARCHAR") print("Added whatsapp_group_id to labinfo") except sqlite3.OperationalError: print("whatsapp_group_id already exists") try: cursor.execute("ALTER TABLE labinfo ADD COLUMN whatsapp_notify_enabled BOOLEAN DEFAULT 0") print("Added whatsapp_notify_enabled to labinfo") except sqlite3.OperationalError: print("whatsapp_notify_enabled already exists")
conn.commit() conn.close()
# 2. Create new tables (WhatsAppQueue, WhatsAppNotificationLog) create_db_and_tables() print("Created new tables via SQLModel metadata")
if __name__ == "__main__": upgrade()12 unmodified lines131415161718192021222312 unmodified linesos.makedirs(dist_dir)# 1. Copy application directoriesinclude_dirs = ['app', 'routes', 'templates', 'static', 'uploads', 'tmp', 'device_interfacing', 'migrations', 'tools']# Removed lab_database.db from include_files to prevent overwriting production datainclude_files = ['main.py', 'models.py', 'database.py', 'requirements.txt','update_system.bat', 'System_Update_Guide.md', '.env']for d in include_dirs:12 unmodified lines1314151617181920212223242512 unmodified linesos.makedirs(dist_dir)# 1. Copy application directoriesinclude_dirs = ['app', 'routes', 'templates', 'static', 'uploads', 'tmp', 'device_interfacing', 'migrations', 'tools', 'scripts']# Removed lab_database.db from include_files to prevent overwriting production data# NOTE: .env is NOT included — server has its own config with different secretsinclude_files = ['main.py', 'models.py', 'database.py', 'requirements.txt','update_system.bat', 'safe_update.bat', 'System_Update_Guide.md','token.json', 'client_secret.json']for d in include_dirs:
123456789101112131415161718192021222324252627282930313233# Render Blueprint — Raya System (NexLab LIS)# Deploy in one click on Render: New + -> Blueprint -> Connect alisaleem97/RayaSystem
services: - type: web name: nexlab runtime: docker repo: https://github.com/alisaleem97/RayaSystem branch: main plan: free # Change to 'starter' ($7/mo) for 24/7 uptime and persistent disk support healthCheckPath: /login envVars: - key: PORT value: "7860" - key: PYTHONUNBUFFERED value: "1" - key: NEXLAB_SECRET_KEY generateValue: true - key: DATABASE_URL value: sqlite:///./lab_database.db - key: GEMINI_API_KEY sync: false - key: GDRIVE_ROOT_FOLDER_ID sync: false
# ── Optional: Persistent Disk (Requires 'starter' plan or higher) ── # If you upgrade `plan: starter` above, uncomment the `disk:` block below # and change DATABASE_URL to: sqlite:////home/user/app/data/lab_database.db # # disk: # name: raya-data # mountPath: /home/user/app/data # sizeGB: 133 unmodified lines34353637383933 unmodified lines# WhatsApp / Google AIrequests==2.33.0google-generativeai==0.8.6# Device Interfacingwatchdog==6.0.033 unmodified lines34353637383940414243444533 unmodified lines# WhatsApp / Google AIrequests==2.33.0google-generativeai==0.8.6google-genai>=2.30.1# Google Drive Integrationgoogle-api-python-client>=2.100.0google-auth>=2.20.0google-auth-httplib2>=0.1.0# Device Interfacingwatchdog==6.0.0
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195# routes/ai_agent.py# API endpoints for the Iraqi Arabic AI Lab Setup Agent (Propose -> Confirm / Cancel).
import jsonfrom datetime import datetime, timedeltafrom typing import Optional
from fastapi import APIRouter, Depends, Request, statusfrom fastapi.responses import JSONResponsefrom pydantic import BaseModelfrom sqlmodel import Session, select
from database import get_sessionfrom models import AIActionPlanfrom routes.helpers import get_current_user, log_activity_actionfrom app.services.ai_setup_agent import ( propose_ai_plan, execute_confirmed_plan, save_gemini_api_key_to_env,)
router = APIRouter(tags=["AI Lab Setup Agent"])
class ProposeRequest(BaseModel): message: str previous_interaction_id: Optional[str] = None
class UpdateApiKeyRequest(BaseModel): api_key: str
@router.get("/api/ai-agent/pending")def get_pending_ai_plan( request: Request, session: Session = Depends(get_session),): current_user = get_current_user(request, session) if not current_user: return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={"success": False, "error": "Unauthorized"})
cutoff = datetime.now() - timedelta(hours=4) pending = session.exec( select(AIActionPlan) .where( AIActionPlan.user_id == current_user.id, AIActionPlan.status == "pending", AIActionPlan.created_at >= cutoff, ) .order_by(AIActionPlan.id.desc()) ).first()
if not pending: return {"success": True, "has_pending": False}
try: preview_cards = json.loads(pending.preview_json or "[]") except Exception: preview_cards = []
return { "success": True, "has_pending": True, "plan_id": pending.id, "user_prompt": pending.user_prompt, "assistant_message": pending.assistant_message, "interaction_id": pending.interaction_id, "preview_cards": preview_cards, }
@router.post("/api/ai-agent/propose")def ai_agent_propose( payload: ProposeRequest, request: Request, session: Session = Depends(get_session),): current_user = get_current_user(request, session) if not current_user: return JSONResponse( status_code=status.HTTP_401_UNAUTHORIZED, content={"success": False, "error": "يرجى تسجيل الدخول أولاً."}, )
msg = (payload.message or "").strip() if not msg: return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={"success": False, "error": "يرجى كتابة طلبك أولاً."}, )
result = propose_ai_plan( request=request, session=session, current_user=current_user, user_message=msg, previous_interaction_id=payload.previous_interaction_id, ) return result
@router.post("/api/ai-agent/confirm/{plan_id}")def ai_agent_confirm( plan_id: int, request: Request, session: Session = Depends(get_session),): current_user = get_current_user(request, session) if not current_user: return JSONResponse( status_code=status.HTTP_401_UNAUTHORIZED, content={"success": False, "error": "يرجى تسجيل الدخول أولاً."}, )
plan = session.get(AIActionPlan, plan_id) if not plan or plan.user_id != current_user.id: return JSONResponse( status_code=status.HTTP_404_NOT_FOUND, content={"success": False, "error": "المقترح غير موجود أو لا يخص حسابك."}, )
if plan.status != "pending": return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={"success": False, "error": f"تم التعامل مع هذا المقترح مسبقاً ({plan.status})."}, )
result = execute_confirmed_plan( request=request, session=session, plan=plan, current_user=current_user, ) return result
@router.post("/api/ai-agent/cancel/{plan_id}")def ai_agent_cancel( plan_id: int, request: Request, session: Session = Depends(get_session),): current_user = get_current_user(request, session) if not current_user: return JSONResponse( status_code=status.HTTP_401_UNAUTHORIZED, content={"success": False, "error": "يرجى تسجيل الدخول أولاً."}, )
plan = session.get(AIActionPlan, plan_id) if not plan or plan.user_id != current_user.id: return JSONResponse( status_code=status.HTTP_404_NOT_FOUND, content={"success": False, "error": "المقترح غير موجود."}, )
if plan.status == "pending": plan.status = "cancelled" plan.resolved_at = datetime.now() session.add(plan) session.commit()
return {"success": True}
@router.post("/api/ai-agent/api-key")def ai_agent_update_api_key( payload: UpdateApiKeyRequest, request: Request, session: Session = Depends(get_session),): current_user = get_current_user(request, session) if not current_user or not (current_user.role == "admin" or current_user.username == "admin"): return JSONResponse( status_code=status.HTTP_403_FORBIDDEN, content={"success": False, "error": "تحديث مفتاح الذكاء الاصطناعي متاح لمدير النظام (Admin) فقط."}, )
key = (payload.api_key or "").strip() if len(key) < 20: return JSONResponse( status_code=status.HTTP_400_BAD_REQUEST, content={"success": False, "error": "المفتاح المُدخل يبدو قصيراً أو غير صالح."}, )
save_gemini_api_key_to_env(key) log_activity_action( session, "AI_KEY_UPDATED", "Updated GEMINI_API_KEY configuration via AI Agent widget", current_user, ) session.commit() return {"success": True, "message": "تم حفظ مفتاح Gemini API بنجاح! يمكنك إرسال طلبك الآن."}216 unmodified lines217218219220221222223216 unmodified linestax_amount = visits[0].tax_amount if visits and visits[0].tax_amount else 0.0remaining_amount = visits[0].remaining_amount if visits else 0.0total_amount = sum([float(order.final_price) if order.final_price else 0 for order in orders])total_after_tax = total_amount - discount_amount + tax_amount216 unmodified lines217218219220221222223216 unmodified linestax_amount = visits[0].tax_amount if visits and visits[0].tax_amount else 0.0remaining_amount = visits[0].remaining_amount if visits else 0.0total_amount = sum([float(order.unit_price) if order.unit_price else 0 for order in orders])total_after_tax = total_amount - discount_amount + tax_amount
15 unmodified lines16171819202115 unmodified lines# DASHBOARD & AUTH# ===========================@router.get("/", response_class=HTMLResponse)def dashboard(request: Request, session: Session = Depends(get_session)):# Check logincurrent_user = get_current_user(request, session)15 unmodified lines1617181920212215 unmodified lines# DASHBOARD & AUTH# ===========================@router.get("/", response_class=HTMLResponse)@router.get("/dashboard", response_class=HTMLResponse)def dashboard(request: Request, session: Session = Depends(get_session)):# Check logincurrent_user = get_current_user(request, session)
12 unmodified lines131415161718192062 unmodified lines8384858687888912 unmodified lines@router.get("/cal-control", response_class=HTMLResponse)def cal_control_page(request: Request, session: Session = Depends(get_session)):# Use inventory permission as primary for accessing this pageif not (require_permission(request, session, "inventory") or require_permission(request, session, "tests")):return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all()62 unmodified linesrequest: Request = None,session: Session = Depends(get_session)):if not (require_permission(request, session, "inventory", "edit") or require_permission(request, session, "tests")):return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)if quantity <= 0:12 unmodified lines131415161718192062 unmodified lines8384858687888912 unmodified lines@router.get("/cal-control", response_class=HTMLResponse)def cal_control_page(request: Request, session: Session = Depends(get_session)):# Use cal_control permission for accessing this pageif not require_permission(request, session, "cal_control"):return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all()62 unmodified linesrequest: Request = None,session: Session = Depends(get_session)):if not require_permission(request, session, "cal_control", "create"):return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)if quantity <= 0:
123459 unmodified lines151617181920218 unmodified lines303132333435153 unmodified lines1891901911921931941951961971985 unmodified lines20420520620720820921021121221321421521621721821922 unmodified lines24224324424524624724824925025125225325425525625725825926026126226326426515 unmodified lines2812822832842852862874 unmodified lines2922932942952962972982991 unmodified line30130230330430530610 unmodified lines31731831932032132220 unmodified lines3433443453463473483493503513523533543554 unmodified lines36036136236336436527 unmodified lines3933943953963973983994004014024034044054064076 unmodified lines414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460# routes/call_centre.pyfrom fastapi import APIRouter, Depends, HTTPException, Requestfrom fastapi.responses import HTMLResponsefrom fastapi.encoders import jsonable_encoderfrom pydantic import BaseModel9 unmodified lines# ✅ Shared templates (with AutoUserTemplates) + helpersfrom routes.helpers import templates, get_current_user, log_audit_action, log_activity_action, require_permission, age_to_daysfrom fastapi.responses import RedirectResponse, JSONResponsefrom routes.whatsapp_utils import generate_report_pdf, send_wati_pdf# --- Google Gemini AI Setup ---import os8 unmodified linesclass WhatsAppPayload(BaseModel):order_ids: Optional[List[int]] = Nonerouter = APIRouter(tags=["Call Centre"])@router.get("/call-centre", response_class=HTMLResponse)153 unmodified linesif user:visit_user_name = user.full_name or user.username# Fetch all visits for the "Previous Results" barall_visits = session.exec(select(PatientVisit).where(PatientVisit.patient_id == patient.id).order_by(PatientVisit.visit_date.asc())).all()5 unmodified lines"all_visits": all_visits})# ✅ NEW: Added request dependency to track WHO marked the patient as called@router.post("/api/mark-called/{visit_id}")def mark_called(visit_id: str, request: Request, session: Session = Depends(get_session)):if not require_permission(request, session, "call_centre", "mark_called"):return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403)current_user = get_current_user(request, session)visit = session.exec(select(PatientVisit).where(PatientVisit.visit_id == visit_id)).first()if not visit:raise HTTPException(status_code=404, detail="Visit not found")visit.is_called = Truesession.add(visit)22 unmodified linesif not visit:raise HTTPException(status_code=404, detail="Visit not found")if not visit.is_printed:# Automatic deduction of tests from inventoryfor order in visit.orders:if order.test_id and order.status != "no_sample":# Find available tests in inventory ordered by nearest expiration_dateinventory_items = session.exec(select(Inventory).where(Inventory.material_type == "Test",Inventory.test_id == order.test_id,Inventory.quantity > 0).order_by(Inventory.expiration_date.asc())).all()if inventory_items:# Deduct 1 from the nearest expiring iteminventory_items[0].quantity -= 1session.add(inventory_items[0])visit.is_printed = Truesession.add(visit)15 unmodified lines# ✅ NEW: Added request dependency to track WHO sent the WhatsApp message@router.post("/api/send-whatsapp/{visit_id}")def send_whatsapp_results(visit_id: str, request: Request, payload: Optional[WhatsAppPayload] = None, session: Session = Depends(get_session)):if not require_permission(request, session, "call_centre", "send_whatsapp"):return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403)current_user = get_current_user(request, session)4 unmodified linespatient = session.get(Patient, visit.patient_id)if not patient:raise HTTPException(status_code=404, detail="Patient not found")query = select(Order).options(selectinload(Order.test).selectinload(TestDefinition.test_parameters).selectinload(TestParameter.parameter),selectinload(Order.result).selectinload(Result.details)).where(Order.visit_id == visit.id, Order.status != "no_sample")1 unmodified linequery = query.where(Order.id.in_(payload.order_ids))orders = session.exec(query).all()test_ids = [order.test_id for order in orders if order.test_id]all_result_types = session.exec(select(TestResultType).where(TestResultType.test_id.in_(test_ids), TestResultType.is_active == True)10 unmodified linestest = order.testres = order.resultif not test: continue# Fetch ranges for this test/patient (same logic as print report)ranges = session.exec(20 unmodified linesreturn bestif test.test_parameters:structured_results.append({"type": "parent", "test_name": test.test_name, "print_separately": test.print_separately, "note": res.note if res else ""})for tp in test.test_parameters:p = tp.parameterd = next((dt for dt in res.details if dt.parameter_id == p.id), None) if res else Nonerng = find_range(p.id)structured_results.append({"type": "child", "parameter_name": p.parameter_name, "result_value": d.result_value if d else "-","result_type": get_result_type(test.id, p.id),"unit": rng.unit if rng else "","range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""),4 unmodified linesrng = find_range(None)structured_results.append({"type": "standalone", "test_name": test.test_name, "result_value": res.result_value if res else "-","result_type": get_result_type(test.id, None),"unit": rng.unit if rng else "","range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""),27 unmodified linesbarcode_data = barcode_data.split("base64,")[1]try:pdf_bytes = generate_report_pdf(jsonable_encoder(patient),jsonable_encoder(visit),structured_results,jsonable_encoder(lab_info),template_data,barcode_data)to_phone = patient.phone_numberif not to_phone:raise HTTPException(status_code=400, detail="Patient phone number not found")6 unmodified linessafe_name = "".join(c for c in patient.full_name if c.isalnum() or c in (' ', '_', '-')).strip()filename = f"{safe_name}.pdf"caption = f"{patient.full_name}"# Using dynamic lab_info credentials!report = send_wati_pdf(to_phone, pdf_bytes, filename, caption, jsonable_encoder(lab_info))if report.get('status') != 'error' and not str(report.get('result')).lower() == 'error':visit.is_whatsapp_sent = Truesession.add(visit)# ---------------------------------------------------------# ✅ NEW: INJECT AUDIT LOG HERE (Tracking WhatsApp Dispatch)# ---------------------------------------------------------log_audit_action(session=session,table_name="patientvisit",record_id=visit.id,action="DISPATCH",current_user=current_user,new_values={"action": "Results sent to patient via WhatsApp", "phone": to_phone})# ---------------------------------------------------------session.commit()# Activity Log: WhatsApp sentlog_activity_action(session, "SEND_WHATSAPP", f"Sent results via WhatsApp to {to_phone} for patient {patient.full_name}", current_user, "patient", patient.id)session.commit()return {"success": True, "message": "Result sent successfully"}else:return {"success": False, "error": report.get('message', 'WhatsApp API Error')}except Exception as e:traceback.print_exc()raise HTTPException(status_code=500, detail=f"Error: {str(e)}")# ==========================================# 🤖 FREE AI ANALYSIS ROUTE# ==========================================@router.post("/api/ai-analyse")async def ai_analyse_results(req: AIRequest):if not _gemini_key:return {"success": False, "error": "AI service not configured. Set GEMINI_API_KEY environment variable."}try:123459 unmodified lines151617181920218 unmodified lines303132333435363738394041153 unmodified lines1951961971981992002012022032042052062072082095 unmodified lines21521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025122 unmodified lines27427527627727827928028128215 unmodified lines2982993003013023033044 unmodified lines3093103113123133143153163173183193201 unmodified line32232332432532632732832933033133233333433510 unmodified lines34634734834935035135235320 unmodified lines3743753763773783793803813823833843853863873883893903913923933943954 unmodified lines40040140240340440540640727 unmodified lines4354364374384394406 unmodified lines447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567# routes/call_centre.pyfrom fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Requestfrom fastapi.responses import HTMLResponsefrom fastapi.encoders import jsonable_encoderfrom pydantic import BaseModel9 unmodified lines# ✅ Shared templates (with AutoUserTemplates) + helpersfrom routes.helpers import templates, get_current_user, log_audit_action, log_activity_action, require_permission, age_to_daysfrom fastapi.responses import RedirectResponse, JSONResponsefrom routes.whatsapp_utils import generate_report_pdf, send_whatsapp_pdf# --- Google Gemini AI Setup ---import os8 unmodified linesclass WhatsAppPayload(BaseModel):order_ids: Optional[List[int]] = None# =============================================================# ⚡ IN-MEMORY TRACKER for background WhatsApp tasks# =============================================================# Keyed by visit_id → { "status": "pending"|"sent"|"failed", "message": str }_whatsapp_tasks: dict = {}router = APIRouter(tags=["Call Centre"])@router.get("/call-centre", response_class=HTMLResponse)153 unmodified linesif user:visit_user_name = user.full_name or user.username# Fetch visits with double-authorized results for the "Previous Results" barall_visits = session.exec(select(PatientVisit).join(Order, Order.visit_id == PatientVisit.id).where(PatientVisit.patient_id == patient.id,Order.status == "double_authorized",).distinct().order_by(PatientVisit.visit_date.asc())).all()5 unmodified lines"all_visits": all_visits})def _deduct_inventory_if_first_action(visit: PatientVisit, session: Session):if not visit.is_printed and not visit.is_called:# Automatic deduction of tests from inventoryfor order in visit.orders:if order.test_id and order.status != "no_sample":# Find available tests in inventory ordered by nearest expiration_dateinventory_items = session.exec(select(Inventory).where(Inventory.material_type == "Test",Inventory.test_id == order.test_id,Inventory.quantity > 0).order_by(Inventory.expiration_date.asc())).all()if inventory_items:# Deduct 1 from the nearest expiring iteminventory_items[0].quantity -= 1session.add(inventory_items[0])# ✅ NEW: Added request dependency to track WHO marked the patient as called@router.post("/api/mark-called/{visit_id}")def mark_called(visit_id: str, request: Request, session: Session = Depends(get_session)):if not require_permission(request, session, "call_centre", "mark_called"):return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403)current_user = get_current_user(request, session)visit = session.exec(select(PatientVisit).options(selectinload(PatientVisit.orders)).where(PatientVisit.visit_id == visit_id)).first()if not visit:raise HTTPException(status_code=404, detail="Visit not found")_deduct_inventory_if_first_action(visit, session)visit.is_called = Truesession.add(visit)22 unmodified linesif not visit:raise HTTPException(status_code=404, detail="Visit not found")_deduct_inventory_if_first_action(visit, session)if not visit.is_printed:visit.is_printed = Truesession.add(visit)15 unmodified lines# ✅ NEW: Added request dependency to track WHO sent the WhatsApp message@router.post("/api/send-whatsapp/{visit_id}")def send_whatsapp_results(visit_id: str, request: Request, background_tasks: BackgroundTasks, payload: Optional[WhatsAppPayload] = None, session: Session = Depends(get_session)):if not require_permission(request, session, "call_centre", "send_whatsapp"):return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403)current_user = get_current_user(request, session)4 unmodified linespatient = session.get(Patient, visit.patient_id)if not patient:raise HTTPException(status_code=404, detail="Patient not found")if visit.remaining_amount > 0:return JSONResponse({"success": False, "error": "The patient has remaining money not paid."}, status_code=400)query = select(Order).options(selectinload(Order.test).selectinload(TestDefinition.department),selectinload(Order.test).selectinload(TestDefinition.test_parameters).selectinload(TestParameter.parameter),selectinload(Order.result).selectinload(Result.details)).where(Order.visit_id == visit.id, Order.status != "no_sample")1 unmodified linequery = query.where(Order.id.in_(payload.order_ids))orders = session.exec(query).all()orders = sorted(orders,key=lambda o: (o.test.department_id if (o.test and o.test.department_id is not None) else 999999,bool(o.test.print_separately) if o.test else False,o.id or 0))test_ids = [order.test_id for order in orders if order.test_id]all_result_types = session.exec(select(TestResultType).where(TestResultType.test_id.in_(test_ids), TestResultType.is_active == True)10 unmodified linestest = order.testres = order.resultif not test: continuedept_id = test.department_iddept_name = test.department.department_name if test.department else ""# Fetch ranges for this test/patient (same logic as print report)ranges = session.exec(20 unmodified linesreturn bestif test.test_parameters:structured_results.append({"type": "parent","test_name": test.test_name,"department_id": dept_id,"department_name": dept_name,"print_separately": test.print_separately,"note": res.note if res else ""})for tp in test.test_parameters:p = tp.parameterd = next((dt for dt in res.details if dt.parameter_id == p.id), None) if res else Nonerng = find_range(p.id)structured_results.append({"type": "child", "parameter_name": p.parameter_name, "result_value": d.result_value if d else "-","department_id": dept_id,"department_name": dept_name,"result_type": get_result_type(test.id, p.id),"unit": rng.unit if rng else "","range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""),4 unmodified linesrng = find_range(None)structured_results.append({"type": "standalone", "test_name": test.test_name, "result_value": res.result_value if res else "-","department_id": dept_id,"department_name": dept_name,"result_type": get_result_type(test.id, None),"unit": rng.unit if rng else "","range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""),27 unmodified linesbarcode_data = barcode_data.split("base64,")[1]try:to_phone = patient.phone_numberif not to_phone:raise HTTPException(status_code=400, detail="Patient phone number not found")6 unmodified linessafe_name = "".join(c for c in patient.full_name if c.isalnum() or c in (' ', '_', '-')).strip()filename = f"{safe_name}.pdf"caption = f"{patient.full_name}"# Serialize required data for backgroundpatient_data = jsonable_encoder(patient)visit_data = jsonable_encoder(visit)lab_info_data = jsonable_encoder(lab_info)user_id = current_user.id if current_user else Nonepatient_id_val = patient.idvisit_id_val = visit.id# Optional base_url if generate_report_pdf needs it in Raya# req_base_url = str(request.base_url)# Mark this visit as "pending" in the in-memory tracker_whatsapp_tasks[visit_id] = {"status": "pending", "message": "Generating PDF and sending..."}async def process_and_send():try:from database import enginefrom sqlmodel import Session as BgSession# generate_report_pdf is async (wraps sync Playwright in asyncio.to_thread internally)pdf_bytes = await generate_report_pdf(patient_data,visit_data,structured_results,lab_info_data,template_data,barcode_data)_whatsapp_tasks[visit_id] = {"status": "pending", "message": "PDF ready, sending via WhatsApp..."}# send_whatsapp_pdf is synchronous (queue insert) — offload to threadimport asyncioreport = await asyncio.to_thread(send_whatsapp_pdf,to_phone, pdf_bytes, filename, caption, lab_info_data, visit_id=visit_id_val)if report.get('status') == 'queued':# ✅ Successfully queuedwith BgSession(engine) as bg_session:from models import PatientVisitbg_visit = bg_session.exec(select(PatientVisit).where(PatientVisit.id == visit_id_val)).first()if bg_visit:bg_visit.is_whatsapp_sent = Truebg_visit.is_called = Truebg_session.add(bg_visit)from models import Userbg_user = bg_session.get(User, user_id) if user_id else Nonelog_audit_action(session=bg_session,table_name="patientvisit",record_id=bg_visit.id,action="DISPATCH",current_user=bg_user,new_values={"action": "Results sent to patient via WhatsApp and marked as Called", "phone": to_phone})log_activity_action(bg_session,"SEND_WHATSAPP",f"Sent results via WhatsApp to {to_phone} for patient {patient_data.get('full_name', '')}",bg_user,"patient",patient_id_val)bg_session.commit()_whatsapp_tasks[visit_id] = {"status": "sent", "message": "WhatsApp message sent successfully."}else:# ❌ UltraMsg did NOT confirmerror_msg = report.get("message", "") or report.get("error", "") or "not send"_whatsapp_tasks[visit_id] = {"status": "failed", "message": error_msg}except Exception as e:import tracebacktraceback.print_exc()_whatsapp_tasks[visit_id] = {"status": "failed", "message": str(e)}# Fire background task and return immediatelybackground_tasks.add_task(process_and_send)return {"success": True, "message": "Sending in progress...", "poll": True}except Exception as e:traceback.print_exc()_whatsapp_tasks[visit_id] = {"status": "failed", "message": str(e)}raise HTTPException(status_code=500, detail=f"Error: {str(e)}")# ============================================================# ⚡ POLLING ENDPOINT — frontend checks this every 2 seconds# ============================================================@router.get("/api/whatsapp-status/{visit_id}")def whatsapp_send_status(visit_id: str, request: Request, session: Session = Depends(get_session)):task = _whatsapp_tasks.get(visit_id)if not task:return {"status": "unknown", "message": "No active WhatsApp task for this visit."}response = {"status": task["status"], "message": task["message"]}# Clean up completed tasks from memoryif task["status"] in ("sent", "failed"):_whatsapp_tasks.pop(visit_id, None)return response# ==========================================# 🤖 FREE AI ANALYSIS ROUTE# ==========================================@router.post("/api/ai-analyse")def ai_analyse_results(req: AIRequest):if not _gemini_key:return {"success": False, "error": "AI service not configured. Set GEMINI_API_KEY environment variable."}try:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110from fastapi import APIRouter, Depends, Request, Form, HTTPException, statusfrom fastapi.responses import HTMLResponse, JSONResponsefrom sqlmodel import Session, selectfrom typing import List, Optionalfrom datetime import datetime
from app.database import get_sessionfrom app.models import DiscountRule, Userfrom app.middleware import get_current_userfrom routes.helpers import templates
router = APIRouter(tags=["Discount Rules"])
def require_admin(request: Request, session: Session = Depends(get_session)): current_user = get_current_user(request, session) if not current_user or current_user.role != "admin": raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Only administrators can access this page.", ) return current_user
@router.get("/discount-rules", response_class=HTMLResponse)def discount_rules_page( request: Request, session: Session = Depends(get_session)): current_user = require_admin(request, session) return templates.TemplateResponse( "discount_rules.html", {"request": request, "current_user": current_user} )
@router.get("/api/discount-rules", response_class=JSONResponse)def get_discount_rules( request: Request, session: Session = Depends(get_session)): # Any logged in user can read the rules for validation on the frontend current_user = get_current_user(request, session) if not current_user: raise HTTPException(status_code=401, detail="Unauthorized") rules = session.exec(select(DiscountRule).order_by(DiscountRule.min_total)).all() return [ { "id": r.id, "min_total": r.min_total, "max_total": r.max_total, "max_discount": r.max_discount } for r in rules ]
@router.post("/api/discount-rules")def create_discount_rule( request: Request, min_total: float = Form(...), max_total: float = Form(...), max_discount: float = Form(...), session: Session = Depends(get_session)): current_user = require_admin(request, session) rule = DiscountRule( min_total=min_total, max_total=max_total, max_discount=max_discount, created_by=current_user.id ) session.add(rule) session.commit() session.refresh(rule) return {"message": "Rule created successfully"}
@router.put("/api/discount-rules/{rule_id}")def update_discount_rule( request: Request, rule_id: int, min_total: float = Form(...), max_total: float = Form(...), max_discount: float = Form(...), session: Session = Depends(get_session)): current_user = require_admin(request, session) rule = session.get(DiscountRule, rule_id) if not rule: raise HTTPException(status_code=404, detail="Rule not found") rule.min_total = min_total rule.max_total = max_total rule.max_discount = max_discount rule.edited_by = current_user.id rule.edited_at = datetime.now() session.add(rule) session.commit() return {"message": "Rule updated successfully"}
@router.post("/api/discount-rules/{rule_id}/delete")def delete_discount_rule( request: Request, rule_id: int, session: Session = Depends(get_session)): current_user = require_admin(request, session) rule = session.get(DiscountRule, rule_id) if not rule: raise HTTPException(status_code=404, detail="Rule not found") session.delete(rule) session.commit() return {"message": "Rule deleted successfully"}5 unmodified lines678910111247 unmodified lines6061626364656667686989 unmodified lines1591601611621631645 unmodified linesfrom datetime import datetimefrom database import get_sessionfrom models import Patient, PatientVisit, Order, TestDefinition, Result, ResultDetail# ✅ NEW: Added log_audit_action to importsfrom routes.helpers import templates, get_current_user, log_audit_action, log_activity_action, require_permission, build_patient_visit_data47 unmodified linesif user:visit_user_name = user.full_name or user.username# Fetch all visits for the "Previous Results" barall_visits = session.exec(select(PatientVisit).where(PatientVisit.patient_id == patient.id).order_by(PatientVisit.visit_date.asc())).all()89 unmodified linesif order.status not in ("authorized", "double_authorized"):return JSONResponse({"success": False, "message": f"Cannot rerun from status '{order.status}'. Only authorized tests can be rerun."}, status_code=400)result = session.exec(select(Result).where(Result.order_id == order_id)).first()if result:# Standalone result value backup5 unmodified lines678910111247 unmodified lines60616263646566676869707172737489 unmodified lines1641651661671681691701711721731741751761771781791801811821835 unmodified linesfrom datetime import datetimefrom database import get_sessionfrom models import Patient, PatientVisit, Order, TestDefinition, Result, ResultDetail, Inventory# ✅ NEW: Added log_audit_action to importsfrom routes.helpers import templates, get_current_user, log_audit_action, log_activity_action, require_permission, build_patient_visit_data47 unmodified linesif user:visit_user_name = user.full_name or user.username# Fetch visits with double-authorized results for the "Previous Results" barall_visits = session.exec(select(PatientVisit).join(Order, Order.visit_id == PatientVisit.id).where(PatientVisit.patient_id == patient.id,Order.status == "double_authorized",).distinct().order_by(PatientVisit.visit_date.asc())).all()89 unmodified linesif order.status not in ("authorized", "double_authorized"):return JSONResponse({"success": False, "message": f"Cannot rerun from status '{order.status}'. Only authorized tests can be rerun."}, status_code=400)# Automatic deduction of tests from inventory for ReRunif order.test_id:inventory_items = session.exec(select(Inventory).where(Inventory.material_type == "Test",Inventory.test_id == order.test_id,Inventory.quantity > 0).order_by(Inventory.expiration_date.asc())).all()if inventory_items:inventory_items[0].quantity -= 1session.add(inventory_items[0])result = session.exec(select(Result).where(Result.order_id == order_id)).first()if result:# Standalone result value backup
120 unmodified lines12112212312412512612717 unmodified lines14514614714814915015122 unmodified lines17417517617717817918029 unmodified lines210211212213214215216120 unmodified lines})@router.post("/expenses-entry/create")async def create_expense(type_id: int = Form(...),expense_date: str = Form(...),amount: float = Form(...),17 unmodified linesfile_name = file.filenamewith open(file_path, "wb") as buffer:content = await file.read()buffer.write(content)# Parse date22 unmodified linesreturn RedirectResponse(url=f"/expenses-entry?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER)@router.post("/expenses-entry/update/{expense_id}")async def update_expense(expense_id: int,type_id: int = Form(...),expense_date: str = Form(...),29 unmodified linesexpense.file_name = file.filenamewith open(file_path, "wb") as buffer:content = await file.read()buffer.write(content)# Update other fields120 unmodified lines12112212312412512612717 unmodified lines14514614714814915015122 unmodified lines17417517617717817918029 unmodified lines210211212213214215216120 unmodified lines})@router.post("/expenses-entry/create")def create_expense(type_id: int = Form(...),expense_date: str = Form(...),amount: float = Form(...),17 unmodified linesfile_name = file.filenamewith open(file_path, "wb") as buffer:content = file.file.read()buffer.write(content)# Parse date22 unmodified linesreturn RedirectResponse(url=f"/expenses-entry?error={str(e).replace(' ', '%20')}", status_code=status.HTTP_303_SEE_OTHER)@router.post("/expenses-entry/update/{expense_id}")def update_expense(expense_id: int,type_id: int = Form(...),expense_date: str = Form(...),29 unmodified linesexpense.file_name = file.filenamewith open(file_path, "wb") as buffer:content = file.file.read()buffer.write(content)# Update other fields
282 unmodified lines28328428528628728828929029129229329429520 unmodified lines316317318319320321322323324325326327282 unmodified lines})@router.post("/lab-info/update")async def update_lab_info(request: Request, lab_name: str = Form(...), lab_title: Optional[str] = Form(None),welcome_message: Optional[str] = Form(None), welcome_template_name: Optional[str] = Form(None),province_id: Optional[int] = Form(None),first_doctor_name: Optional[str] = Form(None), second_doctor_name: Optional[str] = Form(None),lab_address: Optional[str] = Form(None), lab_phone_1: str = Form(...),lab_phone_2: Optional[str] = Form(None), whatsapp_api: Optional[str] = Form(None),whatsapp_token: Optional[str] = Form(None), telegram_api: Optional[str] = Form(None),telegram_token: Optional[str] = Form(None), lab_email: Optional[str] = Form(None),lab_website: Optional[str] = Form(None), tax_percentage: Optional[float] = Form(0.0),lab_note_1: Optional[str] = Form(None),20 unmodified lineslab_info.lab_phone_2 = lab_phone_2lab_info.whatsapp_api = whatsapp_apilab_info.whatsapp_token = whatsapp_tokenlab_info.telegram_api = telegram_apilab_info.telegram_token = telegram_tokenlab_info.lab_email = lab_emaillab_info.lab_website = lab_websitelab_info.welcome_message = welcome_messagelab_info.welcome_template_name = welcome_template_namelab_info.province_id = province_idlab_info.tax_percentage = tax_percentage if tax_percentage is not None else 0.0lab_info.lab_note_1 = lab_note_1282 unmodified lines28328428528628728828929029129229329429529629729820 unmodified lines319320321322323324325326327328329330331282 unmodified lines})@router.post("/lab-info/update")def update_lab_info(request: Request, lab_name: str = Form(...), lab_title: Optional[str] = Form(None),welcome_message: Optional[str] = Form(None),province_id: Optional[int] = Form(None),first_doctor_name: Optional[str] = Form(None), second_doctor_name: Optional[str] = Form(None),lab_address: Optional[str] = Form(None), lab_phone_1: str = Form(...),lab_phone_2: Optional[str] = Form(None), whatsapp_api: Optional[str] = Form(None),whatsapp_token: Optional[str] = Form(None),whatsapp_group_id: Optional[str] = Form(None),whatsapp_notify_enabled: Optional[str] = Form(None),telegram_api: Optional[str] = Form(None),telegram_token: Optional[str] = Form(None), lab_email: Optional[str] = Form(None),lab_website: Optional[str] = Form(None), tax_percentage: Optional[float] = Form(0.0),lab_note_1: Optional[str] = Form(None),20 unmodified lineslab_info.lab_phone_2 = lab_phone_2lab_info.whatsapp_api = whatsapp_apilab_info.whatsapp_token = whatsapp_tokenlab_info.whatsapp_group_id = whatsapp_group_idlab_info.whatsapp_notify_enabled = (whatsapp_notify_enabled == "1")lab_info.telegram_api = telegram_apilab_info.telegram_token = telegram_tokenlab_info.lab_email = lab_emaillab_info.lab_website = lab_websitelab_info.welcome_message = welcome_messagelab_info.province_id = province_idlab_info.tax_percentage = tax_percentage if tax_percentage is not None else 0.0lab_info.lab_note_1 = lab_note_1
11 unmodified lines121314151617188 unmodified lines27282930313233343538 unmodified lines74757677787980818248 unmodified lines13113213313413513613713813936 unmodified lines17617717817918018118218318413 unmodified lines1981992002012022032048 unmodified lines21321421521621721821922022129 unmodified lines25125225325425525625725825911 unmodified linesfrom database import get_sessionfrom app.models.hr import Employee, EmployeeAttachmentfrom routes.helpers import templates, get_current_userrouter = APIRouter()8 unmodified lines# ===========================@router.get("/hr", response_class=HTMLResponse)def hr_page(request: Request, session: Session = Depends(get_session)):current_user = get_current_user(request, session)if not current_user:return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER)employees = session.exec(select(Employee).where(Employee.is_active == True).order_by(Employee.created_at.desc())).all()38 unmodified linesrequest: Request = None,session: Session = Depends(get_session)):current_user = get_current_user(request, session)if not current_user:return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER)try:sd = datetime.strptime(start_date, "%Y-%m-%d")48 unmodified linesrequest: Request = None,session: Session = Depends(get_session)):current_user = get_current_user(request, session)if not current_user:return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER)try:emp = session.get(Employee, employee_id)36 unmodified linesrequest: Request,session: Session = Depends(get_session)):current_user = get_current_user(request, session)if not current_user:return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER)try:emp = session.get(Employee, employee_id)13 unmodified lines# GET ATTACHMENTS API# ===========================@router.get("/api/hr/employees/{employee_id}/attachments")def get_employee_attachments(employee_id: int, session: Session = Depends(get_session)):attachments = session.exec(select(EmployeeAttachment).where(EmployeeAttachment.employee_id == employee_id)).all()return {"attachments": [{"id": a.id, "file_name": a.file_name, "file_path": a.file_path, "uploaded_at": a.uploaded_at.isoformat()} for a in attachments]}8 unmodified linesrequest: Request = None,session: Session = Depends(get_session)):current_user = get_current_user(request, session)if not current_user:return JSONResponse(status_code=401, content={"success": False, "error": "Not authenticated"})try:emp = session.get(Employee, employee_id)29 unmodified linesrequest: Request,session: Session = Depends(get_session)):current_user = get_current_user(request, session)if not current_user:return JSONResponse(status_code=401, content={"success": False, "error": "Not authenticated"})try:attachment = session.get(EmployeeAttachment, attachment_id)11 unmodified lines121314151617188 unmodified lines27282930313233343538 unmodified lines74757677787980818248 unmodified lines13113213313413513613713813936 unmodified lines17617717817918018118218318413 unmodified lines1981992002012022032042052068 unmodified lines21521621721821922022122222329 unmodified lines25325425525625725825926026111 unmodified linesfrom database import get_sessionfrom app.models.hr import Employee, EmployeeAttachmentfrom routes.helpers import templates, get_current_user, require_permissionrouter = APIRouter()8 unmodified lines# ===========================@router.get("/hr", response_class=HTMLResponse)def hr_page(request: Request, session: Session = Depends(get_session)):if not require_permission(request, session, "hr"):return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)current_user = get_current_user(request, session)employees = session.exec(select(Employee).where(Employee.is_active == True).order_by(Employee.created_at.desc())).all()38 unmodified linesrequest: Request = None,session: Session = Depends(get_session)):if not require_permission(request, session, "hr", "create"):return RedirectResponse(url="/hr?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)current_user = get_current_user(request, session)try:sd = datetime.strptime(start_date, "%Y-%m-%d")48 unmodified linesrequest: Request = None,session: Session = Depends(get_session)):if not require_permission(request, session, "hr", "edit"):return RedirectResponse(url="/hr?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)current_user = get_current_user(request, session)try:emp = session.get(Employee, employee_id)36 unmodified linesrequest: Request,session: Session = Depends(get_session)):if not require_permission(request, session, "hr", "delete"):return RedirectResponse(url="/hr?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)current_user = get_current_user(request, session)try:emp = session.get(Employee, employee_id)13 unmodified lines# GET ATTACHMENTS API# ===========================@router.get("/api/hr/employees/{employee_id}/attachments")def get_employee_attachments(employee_id: int, request: Request, session: Session = Depends(get_session)):if not require_permission(request, session, "hr"):return JSONResponse(status_code=403, content={"success": False, "error": "Permission Denied"})attachments = session.exec(select(EmployeeAttachment).where(EmployeeAttachment.employee_id == employee_id)).all()return {"attachments": [{"id": a.id, "file_name": a.file_name, "file_path": a.file_path, "uploaded_at": a.uploaded_at.isoformat()} for a in attachments]}8 unmodified linesrequest: Request = None,session: Session = Depends(get_session)):if not require_permission(request, session, "hr", "edit"):return JSONResponse(status_code=403, content={"success": False, "error": "Permission Denied"})current_user = get_current_user(request, session)try:emp = session.get(Employee, employee_id)29 unmodified linesrequest: Request,session: Session = Depends(get_session)):if not require_permission(request, session, "hr", "edit"):return JSONResponse(status_code=403, content={"success": False, "error": "Permission Denied"})current_user = get_current_user(request, session)try:attachment = session.get(EmployeeAttachment, attachment_id)
21 unmodified lines222324252627282 unmodified lines3132333435363710 unmodified lines4849505152535461 unmodified lines11611711811912012112247 unmodified lines17017117217317417517630 unmodified lines2072082092102112122137 unmodified lines22122222322422522622721 unmodified linesreturn user_id@router.get("/", response_class=HTMLResponse)async def messages_page(request: Request, session: Session = Depends(get_session)):user_id = get_current_user_id(request)current_user = session.get(User, user_id)if not current_user:2 unmodified linesreturn templates.TemplateResponse("messages.html", {"request": request, "current_user": current_user})@router.get("/api/users")async def get_all_users(request: Request, session: Session = Depends(get_session)):user_id = get_current_user_id(request)users = session.exec(select(User).where(User.is_active == True)).all()# Exclude admin if it's not relevant, or just return all except self10 unmodified linesreturn {"users": users_data}@router.get("/api/chats")async def get_user_chats(request: Request, session: Session = Depends(get_session)):user_id = get_current_user_id(request)# Get all chats the user is a member of61 unmodified linesreturn {"chats": chats_data}@router.get("/api/chats/{chat_id}/history")async def get_chat_history(chat_id: int, request: Request, session: Session = Depends(get_session)):user_id = get_current_user_id(request)# Verify membership47 unmodified linesreturn {"messages": msg_data}@router.post("/api/chats/create")async def create_chat(data: dict, request: Request, session: Session = Depends(get_session)):user_id = get_current_user_id(request)is_group = data.get("is_group", False)members_ids = data.get("members", [])30 unmodified linesreturn {"chat_id": new_chat.id}@router.post("/api/upload")async def upload_attachment(request: Request, file: UploadFile, type: str = Form(...), session: Session = Depends(get_session)):user_id = get_current_user_id(request)upload_dir = Path("uploads/chat_media")7 unmodified linesfilepath = upload_dir / filenamecontent = await file.read()with open(filepath, "wb") as f:f.write(content)21 unmodified lines222324252627282 unmodified lines3132333435363710 unmodified lines4849505152535461 unmodified lines11611711811912012112247 unmodified lines17017117217317417517630 unmodified lines2072082092102112122137 unmodified lines22122222322422522622721 unmodified linesreturn user_id@router.get("/", response_class=HTMLResponse)def messages_page(request: Request, session: Session = Depends(get_session)):user_id = get_current_user_id(request)current_user = session.get(User, user_id)if not current_user:2 unmodified linesreturn templates.TemplateResponse("messages.html", {"request": request, "current_user": current_user})@router.get("/api/users")def get_all_users(request: Request, session: Session = Depends(get_session)):user_id = get_current_user_id(request)users = session.exec(select(User).where(User.is_active == True)).all()# Exclude admin if it's not relevant, or just return all except self10 unmodified linesreturn {"users": users_data}@router.get("/api/chats")def get_user_chats(request: Request, session: Session = Depends(get_session)):user_id = get_current_user_id(request)# Get all chats the user is a member of61 unmodified linesreturn {"chats": chats_data}@router.get("/api/chats/{chat_id}/history")def get_chat_history(chat_id: int, request: Request, session: Session = Depends(get_session)):user_id = get_current_user_id(request)# Verify membership47 unmodified linesreturn {"messages": msg_data}@router.post("/api/chats/create")def create_chat(data: dict, request: Request, session: Session = Depends(get_session)):user_id = get_current_user_id(request)is_group = data.get("is_group", False)members_ids = data.get("members", [])30 unmodified linesreturn {"chat_id": new_chat.id}@router.post("/api/upload")def upload_attachment(request: Request, file: UploadFile, type: str = Form(...), session: Session = Depends(get_session)):user_id = get_current_user_id(request)upload_dir = Path("uploads/chat_media")7 unmodified linesfilepath = upload_dir / filenamecontent = file.file.read()with open(filepath, "wb") as f:f.write(content)
93 unmodified lines94959697989910010110293 unmodified lines}if order.package_name:if order.package_name not in packages:packages[order.package_name] = []packages[order.package_name].append(test_obj)else:standalones.append(test_obj)93 unmodified lines94959697989910010110210393 unmodified lines}if order.package_name:for pkg_name in [n.strip() for n in order.package_name.split(",") if n.strip()]:if pkg_name not in packages:packages[pkg_name] = []packages[pkg_name].append(test_obj)else:standalones.append(test_obj)
9 unmodified lines10111213141593 unmodified lines10911011111211311411556 unmodified lines172173174175176177178111 unmodified lines29029129229329429529612 unmodified lines30931031131231331431531656 unmodified lines373374375376377378379380103 unmodified lines48448548648748848949049149249349449549649749834 unmodified lines53353453553653753853954054154254354454554654754854955042 unmodified lines59359459559659759859921 unmodified lines621622623624625626627628629630631632633634635636637638639640641642643302 unmodified lines94694794894995095195295395495595644 unmodified lines100110021003100410051006100713 unmodified lines102110221023102410251026102710281 unmodified line1030103110321033103410351036103751 unmodified lines1089109010911092109310941 unmodified line109610971098109911001101110211031104110511069 unmodified linesfrom typing import Optionalimport jsonfrom pydantic import BaseModelfrom database import get_sessionfrom models import (Patient, PatientVisit, Order, TestDefinition, Package, PackageTest,93 unmodified lines# PATIENT REGISTRATION CREATE (WITH PRICE SNAPSHOT)# ===========================@router.post("/patient-registration/create")async def create_patient_registration(request: Request,patient_id: str = Form(...),full_name: str = Form(...),56 unmodified linesis_tax_applied = apply_tax_toggle == "on"tax_amount = 0.0if is_tax_applied:from models import LabInfolab_info = session.exec(select(LabInfo)).first()tax_percentage = lab_info.tax_percentage if lab_info else 0.0tax_amount = (tax_percentage / 100) * final_total111 unmodified lineselif item['type'] == 'package':package_id = int(item['id'])package = session.get(Package, package_id)package_name = package.package_name if package else ''package_price = package.price if package else 0.0package_tests = session.exec(select(PackageTest).where(PackageTest.package_id == package_id)12 unmodified linesexisting_order.discount_amount += order_discountexisting_order.final_price += final_priceif existing_order.package_name:if package_name and package_name not in existing_order.package_name:existing_order.package_name += f", {package_name}"else:existing_order.package_name = package_nameelse:56 unmodified linesdef _send_welcome():try:from routes.whatsapp_utils import send_wati_textsend_wati_text(to_phone, welcome_msg, lab_info_data)except Exception as e:import logginglogging.getLogger("nexlab.whatsapp").warning(f"Welcome message failed: {e}")103 unmodified lines"total_count": total_count,})@router.get("/api/patients/{patient_id}/has-resulted-tests")def check_has_resulted_tests(patient_id: str, session: Session = Depends(get_session)):patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first()if not patient:return JSONResponse({"success": False, "error": "Patient not found"})orders = session.exec(select(Order).where(Order.patient_id == patient.id)).all()has_results = any(o.status in ['resulted', 'received', 'authorized', 'double_authorized'] for o in orders)return JSONResponse({"success": True, "has_results": has_results})@router.get("/patients/edit/{patient_id}", response_class=HTMLResponse)def patient_edit_page(request: Request, patient_id: str, session: Session = Depends(get_session)):34 unmodified lines.options(selectinload(Order.test)).where(Order.visit_id == latest_visit.id)).all()for order in orders:test = order.testorders_json.append({"id": order.test_id,"name": test.test_name if test else 'Unknown Test',"type": 'test',"price": float(order.unit_price) if order.unit_price else (float(test.price) if test else 0.0),"package_name": order.package_name,"status": order.status})orders_json_str = json.dumps(orders_json if orders_json else [])# [NEW] Fetch payments for the latest visitpayments = []42 unmodified lines@router.post("/api/patients/{patient_id}/remove-test")def api_remove_test(patient_id: str, request: Request, session: Session = Depends(get_session)):"""Immediately delete a specific test order from the patient's latest visit."""if not require_permission(request, session, "patient_edit", "save"):return JSONResponse({"success": False, "error": "Permission Denied"}, status_code=403)try:current_user = get_current_user(request, session)21 unmodified lines# Parse query params since this is called from JStest_id = int(request.query_params.get("test_id", 0))reason = request.query_params.get("reason", "Removed from patient edit")if not test_id:return JSONResponse({"success": False, "error": "test_id is required"}, status_code=400)# Find matching order(s)orders_to_delete = session.exec(select(Order).options(selectinload(Order.result).selectinload(Result.details)).where(Order.visit_id == latest_visit.id, Order.test_id == test_id)).all()if not orders_to_delete:return JSONResponse({"success": False, "error": "Order not found"}, status_code=404)deleted_test_names = []for order in orders_to_delete:# Resolve test name for loggingtest_def = session.get(TestDefinition, order.test_id)test_name = test_def.test_name if test_def else f"Test #{order.test_id}"302 unmodified lines# map old active ordersactive_orders_map = {o.test_id: o for o in old_orders if o.test_id in active_old_order_test_ids}# Reset their prices to 0 so we can recalculate them from the current items listfor o in active_orders_map.values():o.unit_price = 0.0o.discount_amount = 0.0o.final_price = 0.0created_orders = {}44 unmodified lineselif item.get('type') == 'package':package_id = int(item['id'])package = session.get(Package, package_id)package_name = package.package_name if package else ''package_price = package.price if package else 0.0package_tests = session.exec(select(PackageTest).where(PackageTest.package_id == package_id)13 unmodified linesorder.final_price += final_priceif not order.package_name:order.package_name = package_nameelif package_name and package_name not in order.package_name:order.package_name += f", {package_name}"elif test_id in created_orders:order = created_orders[test_id]order.unit_price += unit_price1 unmodified lineorder.final_price += final_priceif not order.package_name:order.package_name = package_nameelif package_name and package_name not in order.package_name:order.package_name += f", {package_name}"else:order = Order(order_number=f"ORD-{latest_visit.visit_id}-{test_id}",51 unmodified linesstatus_code=status.HTTP_303_SEE_OTHER)# ===========================# PATIENT SOFT DELETE# ===========================1 unmodified linedef delete_patient(patient_id: str, request: Request, deleted_reason: str = Form(...), session: Session = Depends(get_session)):if not require_permission(request, session, "patients", "delete"):return RedirectResponse(url="/patients?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)try:current_user = get_current_user(request, session)patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first()if patient:old_values = model_to_dict(patient)patient.is_active = Falsepatient.deleted_by = current_user.id if current_user else None9 unmodified lines10111213141516171819202193 unmodified lines11511611711811912012156 unmodified lines178179180181182183111 unmodified lines29529629729829930030112 unmodified lines31431531631731831932032132256 unmodified lines379380381382383384385386103 unmodified lines49049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152234 unmodified lines55755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760842 unmodified lines65165265365465565665721 unmodified lines679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735302 unmodified lines10381039104010411042104310441045104610471048104944 unmodified lines109410951096109710981099110013 unmodified lines11141115111611171118111911201121112211231 unmodified line112511261127112811291130113111321133113451 unmodified lines118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311 unmodified line13331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913609 unmodified linesfrom typing import Optionalimport jsonfrom pydantic import BaseModelimport redef is_valid_reason(reason: str) -> bool:if not reason: return Falsereturn bool(re.match(r"^[a-zA-Z\u0600-\u06FF\s]+$", reason.strip()))from database import get_sessionfrom models import (Patient, PatientVisit, Order, TestDefinition, Package, PackageTest,93 unmodified lines# PATIENT REGISTRATION CREATE (WITH PRICE SNAPSHOT)# ===========================@router.post("/patient-registration/create")def create_patient_registration(request: Request,patient_id: str = Form(...),full_name: str = Form(...),56 unmodified linesis_tax_applied = apply_tax_toggle == "on"tax_amount = 0.0if is_tax_applied:lab_info = session.exec(select(LabInfo)).first()tax_percentage = lab_info.tax_percentage if lab_info else 0.0tax_amount = (tax_percentage / 100) * final_total111 unmodified lineselif item['type'] == 'package':package_id = int(item['id'])package = session.get(Package, package_id)package_name = package.package_name.strip() if package and package.package_name else ''package_price = package.price if package else 0.0package_tests = session.exec(select(PackageTest).where(PackageTest.package_id == package_id)12 unmodified linesexisting_order.discount_amount += order_discountexisting_order.final_price += final_priceif existing_order.package_name:existing_pkgs = [n.strip() for n in existing_order.package_name.split(",") if n.strip()]if package_name and package_name not in existing_pkgs:existing_order.package_name = ", ".join(existing_pkgs + [package_name])else:existing_order.package_name = package_nameelse:56 unmodified linesdef _send_welcome():try:from routes.whatsapp_utils import send_whatsapp_textsend_whatsapp_text(to_phone, welcome_msg, lab_info_data)except Exception as e:import logginglogging.getLogger("nexlab.whatsapp").warning(f"Welcome message failed: {e}")103 unmodified lines"total_count": total_count,})@router.get("/api/patients/{patient_id}/has-resulted-tests")def check_has_resulted_tests(patient_id: str, request: Request, session: Session = Depends(get_session)):patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first()if not patient:return JSONResponse({"success": False, "error": "Patient not found"})visit_id = request.query_params.get("visit_id")order_query = select(Order).where(Order.patient_id == patient.id)if visit_id:visit = session.exec(select(PatientVisit).where(PatientVisit.patient_id == patient.id, PatientVisit.visit_id == visit_id)).first()if visit:order_query = order_query.where(Order.visit_id == visit.id)orders = session.exec(order_query).all()has_results = any(o.status in ['resulted', 'received', 'authorized', 'double_authorized'] for o in orders)# Check explicitly for double authorized tests (by checking Order status and also Results directly if necessary, but Order status is usually synced)has_double_authorized = any(o.status == 'double_authorized' for o in orders)# To be extremely safe, also check if any results have double_authorized flagif not has_double_authorized and orders:order_ids = [o.id for o in orders]from sqlmodel import colresults = session.exec(select(Result).where(col(Result.order_id).in_(order_ids))).all()has_double_authorized = any(r.double_authorized for r in results)return JSONResponse({"success": True, "has_results": has_results, "has_double_authorized": has_double_authorized})@router.get("/patients/edit/{patient_id}", response_class=HTMLResponse)def patient_edit_page(request: Request, patient_id: str, session: Session = Depends(get_session)):34 unmodified lines.options(selectinload(Order.test)).where(Order.visit_id == latest_visit.id)).all()# Load ALL packages (including inactive) for matching against order.package_nameall_packages = session.exec(select(Package)).all()# Strip keys so trailing/leading whitespace in package_name doesn't cause mismatchesall_packages_map = {p.package_name.strip(): p for p in all_packages}processed_packages = {}for order in orders:test = order.testis_in_package = Falseif order.package_name:pkg_names = [n.strip() for n in order.package_name.split(",") if n.strip()]for p_name in pkg_names:if p_name in all_packages_map:is_in_package = Trueif p_name not in processed_packages:p = all_packages_map[p_name]processed_packages[p_name] = {"id": p.id,"name": p.package_name,"type": 'package',"price": float(p.price),"package_name": p.package_name,"status": order.status}else:# Preserve the worst-case status (resulted > ordered)if order.status in ['resulted', 'received', 'authorized', 'double_authorized']:processed_packages[p_name]["status"] = order.statusif not is_in_package:orders_json.append({"id": order.test_id,"name": test.test_name if test else 'Unknown Test',"type": 'test',"price": float(order.unit_price) if order.unit_price else (float(test.price) if test else 0.0),"package_name": order.package_name,"status": order.status})orders_json.extend(processed_packages.values())orders_json_str = json.dumps(orders_json if orders_json else [])print(f"📋 Edit page orders_json for {patient_id}: {orders_json_str}")# [NEW] Fetch payments for the latest visitpayments = []42 unmodified lines@router.post("/api/patients/{patient_id}/remove-test")def api_remove_test(patient_id: str, request: Request, session: Session = Depends(get_session)):"""Immediately delete a specific test order from the patient's latest visit."""if not require_permission(request, session, "patient_edit", "remove"):return JSONResponse({"success": False, "error": "Permission Denied"}, status_code=403)try:current_user = get_current_user(request, session)21 unmodified lines# Parse query params since this is called from JStest_id = int(request.query_params.get("test_id", 0))item_type = request.query_params.get("item_type", "test")reason = request.query_params.get("reason", "Removed from patient edit")if not is_valid_reason(reason):return JSONResponse({"success": False, "error": "Invalid deletion reason. Please use only letters."}, status_code=400)if not test_id:return JSONResponse({"success": False, "error": "test_id is required"}, status_code=400)# Find matching order(s)removed_pkg_name = Nonepkg_price_per_test = 0.0if item_type == "package":package_id = test_idpackage = session.get(Package, package_id)if not package:return JSONResponse({"success": False, "error": "Package not found"}, status_code=404)removed_pkg_name = package.package_name.strip() if package.package_name else ""package_test_ids = [pt.test_id for pt in session.exec(select(PackageTest).where(PackageTest.package_id == package_id)).all()]pkg_price_per_test = (float(package.price) / len(package_test_ids)) if package_test_ids else 0.0orders_to_delete = session.exec(select(Order).options(selectinload(Order.result).selectinload(Result.details)).where(Order.visit_id == latest_visit.id, Order.test_id.in_(package_test_ids))).all()else:orders_to_delete = session.exec(select(Order).options(selectinload(Order.result).selectinload(Result.details)).where(Order.visit_id == latest_visit.id, Order.test_id == test_id)).all()if not orders_to_delete:return JSONResponse({"success": False, "error": "Order not found"}, status_code=404)deleted_test_names = []disc_pct = latest_visit.discount_percentage or 0.0for order in orders_to_delete:# If removing a package and this test also belongs to another ordered package, keep the order for the remaining package(s)if item_type == "package" and order.package_name:existing_pkgs = [n.strip() for n in order.package_name.split(",") if n.strip()]remaining_pkgs = [n for n in existing_pkgs if n != removed_pkg_name]if remaining_pkgs:order.package_name = ", ".join(remaining_pkgs)order.unit_price = max(0.0, (order.unit_price or 0.0) - pkg_price_per_test)order.discount_amount = order.unit_price * (disc_pct / 100.0) if disc_pct > 0 else 0.0order.final_price = order.unit_price - order.discount_amountsession.add(order)continue# Resolve test name for loggingtest_def = session.get(TestDefinition, order.test_id)test_name = test_def.test_name if test_def else f"Test #{order.test_id}"302 unmodified lines# map old active ordersactive_orders_map = {o.test_id: o for o in old_orders if o.test_id in active_old_order_test_ids}# Reset their prices and package_name to recalculate them from the current items listfor o in active_orders_map.values():o.unit_price = 0.0o.discount_amount = 0.0o.final_price = 0.0o.package_name = Nonecreated_orders = {}44 unmodified lineselif item.get('type') == 'package':package_id = int(item['id'])package = session.get(Package, package_id)package_name = package.package_name.strip() if package and package.package_name else ''package_price = package.price if package else 0.0package_tests = session.exec(select(PackageTest).where(PackageTest.package_id == package_id)13 unmodified linesorder.final_price += final_priceif not order.package_name:order.package_name = package_nameelse:existing_pkgs = [n.strip() for n in order.package_name.split(",") if n.strip()]if package_name and package_name not in existing_pkgs:order.package_name = ", ".join(existing_pkgs + [package_name])elif test_id in created_orders:order = created_orders[test_id]order.unit_price += unit_price1 unmodified lineorder.final_price += final_priceif not order.package_name:order.package_name = package_nameelse:existing_pkgs = [n.strip() for n in order.package_name.split(",") if n.strip()]if package_name and package_name not in existing_pkgs:order.package_name = ", ".join(existing_pkgs + [package_name])else:order = Order(order_number=f"ORD-{latest_visit.visit_id}-{test_id}",51 unmodified linesstatus_code=status.HTTP_303_SEE_OTHER)# ===========================# DELETE VISIT (and all child records)# ===========================@router.post("/patients/{patient_id}/delete-visit/{visit_id}")def delete_patient_visit(patient_id: str,visit_id: str,request: Request,deleted_reason: str = Form(...),session: Session = Depends(get_session)):"""Delete a specific visit and all its child records: orders, results, result details, payments, attachments."""if not require_permission(request, session, "patient_edit", "delete_visit"):return RedirectResponse(url=f"/patients/edit/{patient_id}?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)redirect_url = "/patients" if request.query_params.get("redirect") == "patients" else f"/patients/edit/{patient_id}"if not is_valid_reason(deleted_reason):return RedirectResponse(url=f"{redirect_url}?error=Invalid deletion reason. Please use only letters.", status_code=status.HTTP_303_SEE_OTHER)try:current_user = get_current_user(request, session)patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first()if not patient:return RedirectResponse(url="/patients?error=Patient not found", status_code=status.HTTP_303_SEE_OTHER)visit = session.exec(select(PatientVisit).where(PatientVisit.patient_id == patient.id,PatientVisit.visit_id == visit_id)).first()if not visit:return RedirectResponse(url=f"/patients/edit/{patient_id}?error=Visit not found", status_code=status.HTTP_303_SEE_OTHER)# 1. Retrieve all orders (and their results + result details)orders = session.exec(select(Order).options(selectinload(Order.result).selectinload(Result.details)).where(Order.visit_id == visit.id)).all()# Prevent deletion if there are double-authorized tests in this visithas_double_authorized = any(o.status == 'double_authorized' for o in orders)if not has_double_authorized and orders:order_ids = [o.id for o in orders]from sqlmodel import colresults = session.exec(select(Result).where(col(Result.order_id).in_(order_ids))).all()if any(r.double_authorized for r in results):has_double_authorized = Trueredirect_url = "/patients" if request.query_params.get("redirect") == "patients" else f"/patients/edit/{patient_id}"if has_double_authorized:return RedirectResponse(url=f"{redirect_url}?error=Cannot delete visit with double-authorised tests", status_code=status.HTTP_303_SEE_OTHER)# Archive the visit before deletionarchive_deleted_record(session, "patientvisit", visit.id, model_to_dict(visit), current_user, deleted_reason)deleted_test_names = []for order in orders:test_def = session.get(TestDefinition, order.test_id)test_name = test_def.test_name if test_def else f"Test #{order.test_id}"deleted_test_names.append(test_name)archive_deleted_record(session, "order", order.id, model_to_dict(order), current_user, deleted_reason)# Delete result details → resultif order.result:for det in order.result.details:session.delete(det)session.delete(order.result)session.delete(order)# 2. Delete all payment records for this visitpayments = session.exec(select(Payment).where(Payment.visit_id == visit.id)).all()for payment in payments:archive_deleted_record(session, "payment", payment.id, model_to_dict(payment), current_user, deleted_reason)session.delete(payment)# 3. Delete all attachments for this visitattachments = session.exec(select(Attachment).where(Attachment.visit_id == visit.id)).all()for att in attachments:archive_deleted_record(session, "attachment", att.id, model_to_dict(att), current_user, deleted_reason)# Delete physical fileimport osif att.file_path and os.path.exists(att.file_path):try:os.remove(att.file_path)except Exception:passsession.delete(att)# 4. Delete the visit itselfsession.delete(visit)# Audit log & activitycreate_audit_log(session,"patient",patient.id,"delete",current_user,old_values=model_to_dict(visit),new_values={"action": f"Visit Deleted (ID: {visit_id}). Tests: {', '.join(deleted_test_names)}. Reason: {deleted_reason}","deleted_tests": deleted_test_names,"deleted_payments_count": len(payments),"deleted_attachments_count": len(attachments)})log_activity_action(session,"DELETE_VISIT",f"Deleted visit {visit_id} from patient {patient.full_name} (ID: {patient_id}). "f"Tests: {', '.join(deleted_test_names)}. Payments: {len(payments)}. Reason: {deleted_reason}",current_user,"patientvisit",visit.id)session.commit()print(f"✅ Deleted visit {visit_id} from patient {patient_id}: "f"{len(orders)} orders, {len(payments)} payments, {len(attachments)} attachments")return RedirectResponse(url=f"{redirect_url}?success=Visit deleted successfully!",status_code=status.HTTP_303_SEE_OTHER)except Exception as e:session.rollback()print(f"❌ Error deleting visit: {str(e)}")import tracebacktraceback.print_exc()return RedirectResponse(url=f"/patients/edit/{patient_id}?error={str(e).replace(' ', '%20')}",status_code=status.HTTP_303_SEE_OTHER)# ===========================# PATIENT SOFT DELETE# ===========================1 unmodified linedef delete_patient(patient_id: str, request: Request, deleted_reason: str = Form(...), session: Session = Depends(get_session)):if not require_permission(request, session, "patients", "delete"):return RedirectResponse(url="/patients?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)if not is_valid_reason(deleted_reason):return RedirectResponse(url="/patients?error=Invalid deletion reason. Please use only letters.", status_code=status.HTTP_303_SEE_OTHER)try:current_user = get_current_user(request, session)patient = session.exec(select(Patient).where(Patient.patient_id == patient_id)).first()if patient:# Prevent deletion if there are double-authorized testsorders = session.exec(select(Order).where(Order.patient_id == patient.id)).all()has_double_authorized = any(o.status == 'double_authorized' for o in orders)if not has_double_authorized and orders:order_ids = [o.id for o in orders]from sqlmodel import colresults = session.exec(select(Result).where(col(Result.order_id).in_(order_ids))).all()if any(r.double_authorized for r in results):has_double_authorized = Trueif has_double_authorized:return RedirectResponse(url="/patients?error=Cannot delete patient with double-authorised tests", status_code=status.HTTP_303_SEE_OTHER)old_values = model_to_dict(patient)patient.is_active = Falsepatient.deleted_by = current_user.id if current_user else None
16 unmodified lines1718192021222324252665 unmodified lines9293949596976 unmodified lines10410510610710810916 unmodified lines12612712812913013113213313423 unmodified lines15815916016116216316416516616711 unmodified lines17918018118218318418518618718818919019119280 unmodified lines2732742752762772782 unmodified lines28128228328428528610 unmodified lines29729829930030130225 unmodified lines3283293303313323336 unmodified lines3403413423433443458 unmodified lines35435535635735835943 unmodified lines40340440540640740840941041141212 unmodified lines42542642742842943036 unmodified lines4674684694704714725 unmodified lines47847948048148248312 unmodified lines49649749849950050115 unmodified lines517518519520521522523524525526527528529530234 unmodified lines76576676776876977077177277377477577677777877978078178278378478578616 unmodified linesimport osimport uuidimport loggingfrom routes.helpers import templates, get_current_user, generate_barcode_base64, calculate_age, log_audit_action, log_activity_action, require_permission, age_to_days, build_patient_visit_datafrom fastapi.responses import RedirectResponsefrom routes.generate_pdf import generate_native_barcode_pdffrom io import BytesIOrouter = APIRouter()65 unmodified lines.where(PatientVisit.patient_id == patient.id).order_by(PatientVisit.id.desc())).first()lab_info = session.exec(select(LabInfo).limit(1)).first()template = session.exec(select(PrintTemplate).where(PrintTemplate.template_name == "result_report")).first()6 unmodified linesencoded_template = jsonable_encoder(template) if template else {}# ---------------------------------------------------------# ✅ NEW: INJECT AUDIT LOG HERE (Tracking the print action)# ---------------------------------------------------------16 unmodified lines"visit": encoded_visit,"lab_info": encoded_lab_info,"template": encoded_template,"barcode_data": barcode_data})@router.get("/view-results/{patient_id}", response_class=HTMLResponse)def view_results(patient_id: str, request: Request, session: Session = Depends(get_session)):if not require_permission(request, session, "print_results"):23 unmodified linesif user:visit_user_name = user.full_name or user.username# Fetch all visits for the "Previous Results" barall_visits = session.exec(select(PatientVisit).where(PatientVisit.patient_id == patient.id).order_by(PatientVisit.visit_date.asc())).all()11 unmodified lines# PRINT TEMPLATE API ROUTES# ===========================@router.post("/api/print-template/save")async def save_print_template(request: Request, session: Session = Depends(get_session)):try:data = await request.json()template_name = data.get("template_name", "")# Check permissions based on template_namereq_page = "result_designer"if template_name == "barcode_label":req_page = "barcode_designer"elif template_name == "receipt":req_page = "receipt_designer"80 unmodified lines# Get double authorized ordersquery = select(Order).options(selectinload(Order.test).selectinload(TestDefinition.test_parameters).selectinload(TestParameter.parameter),selectinload(Order.result).selectinload(Result.details).selectinload(ResultDetail.parameter)).where(Order.visit_id == visit.id, Order.status == "double_authorized")2 unmodified linesquery = query.where(Order.id.in_(order_ids))orders = session.exec(query).all()test_ids = [order.test_id for order in orders if order.test_id]all_result_types = session.exec(10 unmodified linesfor order in orders:test = order.testres = order.result# Fetch ranges for this test/patientranges = session.exec(25 unmodified lines"test_name": test.test_name,"order_id": order.id,"status": order.status,"print_separately": test.print_separately,"note": res.note if res else ""})6 unmodified linesgrid_rows.append({"type": "child","parameter_name": param.parameter_name,"result_value": detail.result_value if detail else "","result_type": get_result_type(test.id, param.id),"range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""),8 unmodified lines"type": "standalone","test_name": test.test_name,"order_id": order.id,"result_value": res.result_value if res else "","result_type": get_result_type(test.id, None),"range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""),43 unmodified linesorders = session.exec(select(Order).options(selectinload(Order.test).selectinload(TestDefinition.test_parameters).selectinload(TestParameter.parameter),selectinload(Order.result).selectinload(Result.details).selectinload(ResultDetail.parameter)).where(Order.visit_id == visit.id, Order.status != "no_sample")).all()test_ids = [order.test_id for order in orders if order.test_id]all_result_types = session.exec(12 unmodified linesres = order.resultif not test:continue# Determine display statusif order.status == "double_authorized":36 unmodified lines"order_id": order.id,"status": order.status,"display_status": display_status,"print_separately": test.print_separately,"note": res.note if res else ""})5 unmodified linesgrid_rows.append({"type": "child","parameter_name": param.parameter_name,"result_value": detail.result_value if detail else "","result_type": get_result_type(test.id, param.id),"range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""),12 unmodified lines"order_id": order.id,"status": order.status,"display_status": display_status,"result_value": res.result_value if res else "","result_type": get_result_type(test.id, None),"range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""),15 unmodified linesreturn {"success": False, "error": str(e)}@router.post("/api/upload-watermark")async def upload_watermark(file: UploadFile = File(...)):try:os.makedirs("uploads", exist_ok=True)ext = os.path.splitext(file.filename)[1]filename = f"watermark_{uuid.uuid4().hex}{ext}"filepath = os.path.join("uploads", filename)with open(filepath, "wb") as f:f.write(await file.read())return {"success": True, "filename": filename}except Exception as e:return {"success": False, "error": str(e)}234 unmodified lines).where(Order.visit_id == visit.id)).all() if visit else []# Build orders data for templateorders_data = []for order in orders:test = order.testorders_data.append({"test_name": test.test_name if test else 'Unknown',"test_short_name": test.test_short_name if test and test.test_short_name else (test.test_name if test else 'Unknown'),"package_name": order.package_name or None,"unit_price": order.unit_price or (test.price if test else 0),"final_price": order.final_price or (order.unit_price or 0),"test_id": order.test_id})# Calculate accounting totals (same logic as /api/patient/)total_amount = sum([float(o["final_price"]) if o["final_price"] else 0 for o in orders_data])total_after_tax = total_amount - discount_amount + tax_amount# --- Compute page_size as a clean CSS string (MUST be done in Python, not Jinja inside CSS!) ---def normalize_dim(val, default_unit='mm'):16 unmodified lines1718192021222324252627282930313233343565 unmodified lines1011021031041051061071081091101111126 unmodified lines11912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515616 unmodified lines17317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838923 unmodified lines41341441541641741841942042142242342442542642711 unmodified lines43944044144244344444544644744844945045145280 unmodified lines5335345355365375385392 unmodified lines54254354454554654754854955055155255355455510 unmodified lines56656756856957057157257325 unmodified lines5996006016026036046056066 unmodified lines6136146156166176186196208 unmodified lines62963063163263363463563643 unmodified lines68068168268368468568668768868969069169269369469569669769812 unmodified lines71171271371471571671771836 unmodified lines7557567577587597607617625 unmodified lines76876977077177277377477512 unmodified lines78878979079179279379479515 unmodified lines811812813814815816817818819820821822823824234 unmodified lines10591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112116 unmodified linesimport osimport uuidimport loggingimport threadingimport qrcodeimport base64from io import BytesIOfrom routes.helpers import templates, get_current_user, generate_barcode_base64, calculate_age, log_audit_action, log_activity_action, require_permission, age_to_days, build_patient_visit_datafrom fastapi.responses import RedirectResponsefrom routes.generate_pdf import generate_native_barcode_pdffrom app.services.gdrive_service import (upload_patient_visit_pdf, get_folder_url, is_configured as gdrive_is_configured,get_or_create_patient_folder)logger = logging.getLogger("nexlab.printing")router = APIRouter()65 unmodified lines.where(PatientVisit.patient_id == patient.id).order_by(PatientVisit.id.desc())).first()if visit and visit.remaining_amount > 0:return HTMLResponse(content="<script>alert('The patient has remaining money not paid.'); window.close();</script>",status_code=403)lab_info = session.exec(select(LabInfo).limit(1)).first()template = session.exec(select(PrintTemplate).where(PrintTemplate.template_name == "result_report")).first()6 unmodified linesencoded_template = jsonable_encoder(template) if template else {}# ---------------------------------------------------------# ✅ Google Drive QR Code data# ---------------------------------------------------------gdrive_qr_data = ""if gdrive_is_configured():folder_id = patient.gdrive_folder_idif not folder_id:# Pre-create the folder so the QR code is ready immediatelyfolder_id = get_or_create_patient_folder(patient.patient_id, patient.full_name)if folder_id:patient.gdrive_folder_id = folder_idsession.add(patient)session.commit()else:logger.warning(f"⚠️ Could not retrieve or create Google Drive folder for patient {patient.patient_id}. Google Drive QR code cannot be rendered.")if folder_id:gdrive_qr_data = get_folder_url(folder_id)# Generate QR code image as base64 if we have a Drive URLgdrive_qr_base64 = ""if gdrive_qr_data:try:qr = qrcode.QRCode(version=1, box_size=6, border=2, error_correction=qrcode.constants.ERROR_CORRECT_M)qr.add_data(gdrive_qr_data)qr.make(fit=True)qr_img = qr.make_image(fill_color="black", back_color="white")buf = BytesIO()qr_img.save(buf, format="PNG")gdrive_qr_base64 = base64.b64encode(buf.getvalue()).decode("utf-8")except Exception as e:logger.warning(f"Failed to generate QR code: {e}")# ---------------------------------------------------------# ✅ NEW: INJECT AUDIT LOG HERE (Tracking the print action)# ---------------------------------------------------------16 unmodified lines"visit": encoded_visit,"lab_info": encoded_lab_info,"template": encoded_template,"barcode_data": barcode_data,"gdrive_qr_base64": gdrive_qr_base64,"gdrive_folder_url": gdrive_qr_data})# ===========================# GOOGLE DRIVE PDF UPLOAD API# ===========================from pydantic import BaseModel as PydanticBaseModelclass GDriveUploadRequest(PydanticBaseModel):patient_id: strvisit_id: strpdf_base64: str # Base64-encoded PDF content@router.post("/api/upload-to-gdrive")def api_upload_to_gdrive(payload: GDriveUploadRequest, request: Request, session: Session = Depends(get_session)):"""Upload a PDF to the patient's Google Drive folder."""if not gdrive_is_configured():return JSONResponse({"success": False, "error": "Google Drive not configured"})try:patient = session.exec(select(Patient).where(Patient.patient_id == payload.patient_id)).first()if not patient:return JSONResponse({"success": False, "error": "Patient not found"})visit = session.exec(select(PatientVisit).where(PatientVisit.visit_id == payload.visit_id, PatientVisit.patient_id == patient.id)).first()if not visit:return JSONResponse({"success": False, "error": "Visit not found"})# Skip if already uploaded for this visitif visit.gdrive_file_id:return JSONResponse({"success": True, "message": "Already uploaded", "file_id": visit.gdrive_file_id})# Decode PDFpdf_bytes = base64.b64decode(payload.pdf_base64)# Upload in a background thread to not block the responsevisit_date_str = visit.visit_date.strftime("%Y-%m-%d") if visit.visit_date else "unknown"def _upload():try:from database import get_session as _get_sessionfrom sqlmodel import Session as _Sessionfrom app.database import enginefolder_id, file_id = upload_patient_visit_pdf(patient_id=patient.patient_id,patient_name=patient.full_name,visit_id=payload.visit_id,visit_date=visit_date_str,pdf_bytes=pdf_bytes,)if folder_id and file_id:# Update DB in a new session (we're in a background thread)with _Session(engine) as bg_session:p = bg_session.exec(select(Patient).where(Patient.patient_id == patient.patient_id)).first()v = bg_session.exec(select(PatientVisit).where(PatientVisit.visit_id == payload.visit_id)).first()if p and not p.gdrive_folder_id:p.gdrive_folder_id = folder_idbg_session.add(p)if v:v.gdrive_file_id = file_idbg_session.add(v)bg_session.commit()logger.info(f"✅ Uploaded PDF to Drive for patient {patient.patient_id}, visit {payload.visit_id}")else:logger.error(f"❌ Drive upload returned None for patient {patient.patient_id}")except Exception as e:logger.error(f"❌ Background Drive upload failed: {e}", exc_info=True)threading.Thread(target=_upload, daemon=True).start()return JSONResponse({"success": True, "message": "Upload started"})except Exception as e:logger.error(f"Upload to GDrive error: {e}", exc_info=True)return JSONResponse({"success": False, "error": str(e)})class GDriveHtmlUploadRequest(PydanticBaseModel):patient_id: strvisit_id: strhtml_content: str@router.post("/api/generate-and-upload-pdf")def api_generate_and_upload_pdf(payload: GDriveHtmlUploadRequest, request: Request, session: Session = Depends(get_session)):"""Receive rendered HTML from client, convert to PDF via Playwright, upload to Drive."""if not gdrive_is_configured():return JSONResponse({"success": False, "error": "Google Drive not configured"})try:patient = session.exec(select(Patient).where(Patient.patient_id == payload.patient_id)).first()if not patient:return JSONResponse({"success": False, "error": "Patient not found"})visit = session.exec(select(PatientVisit).where(PatientVisit.visit_id == payload.visit_id, PatientVisit.patient_id == patient.id)).first()if not visit:return JSONResponse({"success": False, "error": "Visit not found"})# Skip if already uploaded for this visitif visit.gdrive_file_id:return JSONResponse({"success": True, "message": "Already uploaded", "file_id": visit.gdrive_file_id})visit_date_str = visit.visit_date.strftime("%Y-%m-%d") if visit.visit_date else "unknown"patient_id_copy = patient.patient_idpatient_name_copy = patient.full_namevisit_id_copy = payload.visit_idhtml_content = payload.html_content# --- INLINE CSS FOR PLAYWRIGHT ---# Playwright sometimes fails to load relative <link> stylesheets in set_content.# We read them from disk and inline them to guarantee 100% perfect styling.import osproject_root = os.path.dirname(os.path.dirname(__file__))try:with open(os.path.join(project_root, "static", "tailwind.min.css"), "r", encoding="utf-8") as f:tailwind_css = f.read()html_content = html_content.replace('<link href="/static/tailwind.min.css" rel="stylesheet">',f"<style>{tailwind_css}</style>")with open(os.path.join(project_root, "static", "vendor", "fonts", "fonts.css"), "r", encoding="utf-8") as f:fonts_css = f.read()html_content = html_content.replace('<link href="/static/vendor/fonts/fonts.css" rel="stylesheet">',f"<style>{fonts_css}</style>")except Exception as e:logger.warning(f"Failed to inline CSS: {e}")# --- INLINE IMAGES FOR PLAYWRIGHT ---import re, base64def _encode_image(match):img_filename = match.group(1).split("/")[-1]full_path = os.path.join(project_root, "uploads", img_filename)try:with open(full_path, "rb") as f:encoded = base64.b64encode(f.read()).decode()ext = img_filename.split('.')[-1].lower()mime = "image/jpeg" if ext in ["jpg", "jpeg"] else f"image/{ext}"return f"data:{mime};base64,{encoded}"except Exception as e:logger.error(f"Failed to inline image {img_filename}: {e}")return match.group(0) # fallback to original if failed# Replace src=".../uploads/filename.ext" with src="data:image/..."html_content = re.sub(r'src="[^"]*/uploads/([^"]+)"', lambda m: f'src="{_encode_image(m)}"', html_content)# Replace url('.../uploads/filename.ext') with url('data:image/...')html_content = re.sub(r"url\(['\"]?[^'\")]*/uploads/([^'\")]+)['\"]?\)", lambda m: f"url('{_encode_image(m)}')", html_content)def _generate_and_upload():try:from playwright.sync_api import sync_playwright# Generate PDF from HTML using Playwrightwith sync_playwright() as p:browser = p.chromium.launch(headless=True)page = browser.new_page()page.set_content(html_content, wait_until="networkidle")pdf_bytes = page.pdf(print_background=True,prefer_css_page_size=True,)browser.close()# Upload to Drivefolder_id, file_id = upload_patient_visit_pdf(patient_id=patient_id_copy,patient_name=patient_name_copy,visit_id=visit_id_copy,visit_date=visit_date_str,pdf_bytes=pdf_bytes,)if folder_id and file_id:from sqlmodel import Session as _Sessionfrom app.database import enginewith _Session(engine) as bg_session:p = bg_session.exec(select(Patient).where(Patient.patient_id == patient_id_copy)).first()v = bg_session.exec(select(PatientVisit).where(PatientVisit.visit_id == visit_id_copy)).first()if p and not p.gdrive_folder_id:p.gdrive_folder_id = folder_idbg_session.add(p)if v:v.gdrive_file_id = file_idbg_session.add(v)bg_session.commit()logger.info(f"✅ Generated PDF and uploaded to Drive for {patient_id_copy}, visit {visit_id_copy}")else:logger.error(f"❌ Drive upload returned None for {patient_id_copy}")except Exception as e:logger.error(f"❌ PDF generation/upload failed: {e}", exc_info=True)threading.Thread(target=_generate_and_upload, daemon=True).start()return JSONResponse({"success": True, "message": "PDF generation and upload started"})except Exception as e:logger.error(f"Generate and upload PDF error: {e}", exc_info=True)return JSONResponse({"success": False, "error": str(e)})@router.get("/view-results/{patient_id}", response_class=HTMLResponse)def view_results(patient_id: str, request: Request, session: Session = Depends(get_session)):if not require_permission(request, session, "print_results"):23 unmodified linesif user:visit_user_name = user.full_name or user.username# Fetch visits with double-authorized results for the "Previous Results" barall_visits = session.exec(select(PatientVisit).join(Order, Order.visit_id == PatientVisit.id).where(PatientVisit.patient_id == patient.id,Order.status == "double_authorized",).distinct().order_by(PatientVisit.visit_date.asc())).all()11 unmodified lines# PRINT TEMPLATE API ROUTES# ===========================@router.post("/api/print-template/save")def save_print_template(payload: dict, request: Request, session: Session = Depends(get_session)):try:data = payloadtemplate_name = data.get("template_name", "")# Check permissions based on template_namereq_page = "result_designer"if template_name in ("barcode", "barcode_label"):req_page = "barcode_designer"elif template_name == "receipt":req_page = "receipt_designer"80 unmodified lines# Get double authorized ordersquery = select(Order).options(selectinload(Order.test).selectinload(TestDefinition.department),selectinload(Order.test).selectinload(TestDefinition.test_parameters).selectinload(TestParameter.parameter),selectinload(Order.result).selectinload(Result.details).selectinload(ResultDetail.parameter)).where(Order.visit_id == visit.id, Order.status == "double_authorized")2 unmodified linesquery = query.where(Order.id.in_(order_ids))orders = session.exec(query).all()orders = sorted(orders,key=lambda o: (o.test.department_id if (o.test and o.test.department_id is not None) else 999999,bool(o.test.print_separately) if o.test else False,o.id or 0))test_ids = [order.test_id for order in orders if order.test_id]all_result_types = session.exec(10 unmodified linesfor order in orders:test = order.testres = order.resultdept_id = test.department_id if test else Nonedept_name = (test.department.department_name if (test and test.department) else "")# Fetch ranges for this test/patientranges = session.exec(25 unmodified lines"test_name": test.test_name,"order_id": order.id,"status": order.status,"department_id": dept_id,"department_name": dept_name,"print_separately": test.print_separately,"note": res.note if res else ""})6 unmodified linesgrid_rows.append({"type": "child","parameter_name": param.parameter_name,"department_id": dept_id,"department_name": dept_name,"result_value": detail.result_value if detail else "","result_type": get_result_type(test.id, param.id),"range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""),8 unmodified lines"type": "standalone","test_name": test.test_name,"order_id": order.id,"department_id": dept_id,"department_name": dept_name,"result_value": res.result_value if res else "","result_type": get_result_type(test.id, None),"range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""),43 unmodified linesorders = session.exec(select(Order).options(selectinload(Order.test).selectinload(TestDefinition.department),selectinload(Order.test).selectinload(TestDefinition.test_parameters).selectinload(TestParameter.parameter),selectinload(Order.result).selectinload(Result.details).selectinload(ResultDetail.parameter)).where(Order.visit_id == visit.id, Order.status != "no_sample")).all()orders = sorted(orders,key=lambda o: (o.test.department_id if (o.test and o.test.department_id is not None) else 999999,bool(o.test.print_separately) if o.test else False,o.id or 0))test_ids = [order.test_id for order in orders if order.test_id]all_result_types = session.exec(12 unmodified linesres = order.resultif not test:continuedept_id = test.department_iddept_name = test.department.department_name if test.department else ""# Determine display statusif order.status == "double_authorized":36 unmodified lines"order_id": order.id,"status": order.status,"display_status": display_status,"department_id": dept_id,"department_name": dept_name,"print_separately": test.print_separately,"note": res.note if res else ""})5 unmodified linesgrid_rows.append({"type": "child","parameter_name": param.parameter_name,"department_id": dept_id,"department_name": dept_name,"result_value": detail.result_value if detail else "","result_type": get_result_type(test.id, param.id),"range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""),12 unmodified lines"order_id": order.id,"status": order.status,"display_status": display_status,"department_id": dept_id,"department_name": dept_name,"result_value": res.result_value if res else "","result_type": get_result_type(test.id, None),"range": rng.text_range if rng and rng.range_type == "text" else (f"{rng.normal_from} - {rng.normal_to}" if rng and rng.normal_from is not None else ""),15 unmodified linesreturn {"success": False, "error": str(e)}@router.post("/api/upload-watermark")def upload_watermark(file: UploadFile = File(...)):try:os.makedirs("uploads", exist_ok=True)ext = os.path.splitext(file.filename)[1]filename = f"watermark_{uuid.uuid4().hex}{ext}"filepath = os.path.join("uploads", filename)with open(filepath, "wb") as f:f.write(file.file.read())return {"success": True, "filename": filename}except Exception as e:return {"success": False, "error": str(e)}234 unmodified lines).where(Order.visit_id == visit.id)).all() if visit else []# Build orders data for template, resolving packages (including packages sharing overlapping tests)from models import Packageall_packages = session.exec(select(Package)).all()all_packages_map = {p.package_name.strip(): p for p in all_packages if p.package_name}pkg_order_counts = {}single_pkg_unit_prices = {}ordered_pkg_names = []for order in orders:if order.package_name:pkg_names = [n.strip() for n in order.package_name.split(",") if n.strip()]for p_name in pkg_names:pkg_order_counts[p_name] = pkg_order_counts.get(p_name, 0) + 1if p_name not in ordered_pkg_names:ordered_pkg_names.append(p_name)if len(pkg_names) == 1 and order.unit_price is not None:single_pkg_unit_prices[pkg_names[0]] = float(order.unit_price)orders_data = []# 1. Add resolved packages with their full package pricesfor p_name in ordered_pkg_names:if p_name in single_pkg_unit_prices and pkg_order_counts.get(p_name, 0) > 0:pkg_price = round(single_pkg_unit_prices[p_name] * pkg_order_counts[p_name], 2)elif p_name in all_packages_map:pkg_price = float(all_packages_map[p_name].price)else:pkg_price = 0.0orders_data.append({"test_name": p_name,"test_short_name": p_name,"package_name": p_name,"unit_price": pkg_price,"final_price": pkg_price,"test_id": None})# 2. Add standalone tests (orders not belonging to a package)for order in orders:pkg_names = [n.strip() for n in (order.package_name or "").split(",") if n.strip()]if not pkg_names:test = order.testu_price = float(order.unit_price) if order.unit_price is not None else (float(test.price) if test else 0.0)f_price = float(order.final_price) if order.final_price is not None else u_priceorders_data.append({"test_name": test.test_name if test else 'Unknown',"test_short_name": test.test_short_name if test and test.test_short_name else (test.test_name if test else 'Unknown'),"package_name": None,"unit_price": u_price,"final_price": f_price,"test_id": order.test_id})# Calculate accounting totals using pre-discount unit_price so discount isn't double-countedtotal_amount = round(sum([float(o["unit_price"]) if o["unit_price"] else 0.0 for o in orders_data]), 2)total_after_tax = round(total_amount - discount_amount + tax_amount, 2)# --- Compute page_size as a clean CSS string (MUST be done in Python, not Jinja inside CSS!) ---def normalize_dim(val, default_unit='mm'):
2 unmodified lines3456789101112131421 unmodified lines36373839404142434456 unmodified lines10110210310410510610710810996 unmodified lines20620720820921021121276 unmodified lines28929029129229329429560 unmodified lines35635735835936036136243 unmodified lines40640740840941041126 unmodified lines438439440441442443444445446447448449450451452453454455456457241 unmodified lines69970070170270370470570670770870971071171271371471571671771873 unmodified lines7927937947957967977987998008018028032 unmodified linesfrom fastapi.responses import HTMLResponse, RedirectResponsefrom sqlmodel import Session, selectfrom datetime import datetime, timedeltafrom typing import Optionalimport osimport secretsfrom database import get_sessionfrom models import PatientVisit, Expense, User, Order, TestDefinition, Device, ExpenseTypefrom routes.helpers import templates, require_permission, get_current_user, create_audit_log, model_to_dictrouter = APIRouter()21 unmodified linesexcept ValueError:return RedirectResponse(url="/reports/detailed-income?error=Invalid date format", status_code=status.HTTP_303_SEE_OTHER)# 1. Fetch Visits for the selected datevisits = session.exec(select(PatientVisit).where(PatientVisit.visit_date >= start_date).where(PatientVisit.visit_date <= end_date)).all()56 unmodified linesexcept ValueError:return RedirectResponse(url="/reports/net-amounts?error=Invalid date format", status_code=status.HTTP_303_SEE_OTHER)# 1. Fetch Visitsvisits = session.exec(select(PatientVisit).where(PatientVisit.visit_date >= start_date).where(PatientVisit.visit_date <= end_date)).all()96 unmodified linesrecords = []if record_type in ["all", "receive"]:query = select(PatientVisit).where(PatientVisit.visit_date >= start_datetime, PatientVisit.visit_date <= end_datetime)if user_filter != "all":query = query.where(PatientVisit.created_by == int(user_filter))76 unmodified linesexcept ValueError:return RedirectResponse(url="/reports/patients-number?error=Invalid datetime format", status_code=status.HTTP_303_SEE_OTHER)query = select(PatientVisit).where(PatientVisit.visit_date >= start_datetime, PatientVisit.visit_date <= end_datetime)visits = session.exec(query).all()# Group by date60 unmodified linestests_list = session.exec(select(TestDefinition).where(TestDefinition.deleted_at == None)).all()devices_list = session.exec(select(Device).where(Device.deleted_at == None)).all()query = select(Order).where(Order.order_date >= start_datetime, Order.order_date <= end_datetime)if test_filter != "all":query = query.where(Order.test_id == int(test_filter))43 unmodified lines"total_tests": total_tests})# ===========================# DISCOUNT REPORT# ===========================26 unmodified linesusers = session.exec(select(User)).all()user_dict = {u.id: u.full_name for u in users}# Query PatientVisit where discount_amount > 0 and within date rangefrom models import Patientquery = select(PatientVisit).where(PatientVisit.discount_amount > 0,PatientVisit.visit_date >= start_datetime,PatientVisit.visit_date <= end_datetime)if patient_id_filter or patient_name_filter:query = query.join(Patient)if patient_id_filter:query = query.where(Patient.patient_id.ilike(f"%{patient_id_filter}%"))if patient_name_filter:query = query.where(Patient.full_name.ilike(f"%{patient_name_filter}%"))if user_filter != "all":# Check if the user either created or edited the visit241 unmodified linesusers = session.exec(select(User)).all()user_dict = {u.id: u.full_name for u in users}# Query PatientVisit where remaining_amount > 0 and within date rangefrom models import Patientquery = select(PatientVisit).where(PatientVisit.remaining_amount > 0,PatientVisit.visit_date >= start_datetime,PatientVisit.visit_date <= end_datetime)if patient_id_filter or patient_name_filter:query = query.join(Patient)if patient_id_filter:query = query.where(Patient.patient_id.ilike(f"%{patient_id_filter}%"))if patient_name_filter:query = query.where(Patient.full_name.ilike(f"%{patient_name_filter}%"))if user_filter != "all":query = query.where(PatientVisit.created_by == int(user_filter))73 unmodified linesexcept ValueError:return RedirectResponse(url="/reports/patient-region?error=Invalid date format", status_code=status.HTTP_303_SEE_OTHER)from models import Patient, Region# Fetch all active regions for dropdownregions_list = session.exec(select(Region).where(Region.is_active == True)).all()query = select(Patient).where(Patient.created_at >= start_datetime, Patient.created_at <= end_datetime)if region_filter != "all":query = query.where(Patient.region_id == int(region_filter))2 unmodified lines345678910111213141521 unmodified lines373839404142434445464756 unmodified lines10410510610710810911011111211311496 unmodified lines21121221321421521621776 unmodified lines29429529629729829930060 unmodified lines36136236336436536636743 unmodified lines41141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048126 unmodified lines508509510511512513514515516517518519520521522523524525241 unmodified lines76776876977077177277377477577677777877978078178278378473 unmodified lines8588598608618628638648658668678688698702 unmodified linesfrom fastapi.responses import HTMLResponse, RedirectResponsefrom sqlmodel import Session, selectfrom datetime import datetime, timedeltafrom sqlalchemy.orm import selectinloadfrom typing import Optionalimport osimport secretsfrom database import get_sessionfrom models import Patient, PatientVisit, Expense, User, Order, TestDefinition, Device, ExpenseTypefrom routes.helpers import templates, require_permission, get_current_user, create_audit_log, model_to_dictrouter = APIRouter()21 unmodified linesexcept ValueError:return RedirectResponse(url="/reports/detailed-income?error=Invalid date format", status_code=status.HTTP_303_SEE_OTHER)# 1. Fetch Visits for the selected date (exclude soft-deleted patients)visits = session.exec(select(PatientVisit).options(selectinload(PatientVisit.patient)).join(Patient, PatientVisit.patient_id == Patient.id).where(Patient.is_active == True).where(PatientVisit.visit_date >= start_date).where(PatientVisit.visit_date <= end_date)).all()56 unmodified linesexcept ValueError:return RedirectResponse(url="/reports/net-amounts?error=Invalid date format", status_code=status.HTTP_303_SEE_OTHER)# 1. Fetch Visits (exclude soft-deleted patients)visits = session.exec(select(PatientVisit).options(selectinload(PatientVisit.patient)).join(Patient, PatientVisit.patient_id == Patient.id).where(Patient.is_active == True).where(PatientVisit.visit_date >= start_date).where(PatientVisit.visit_date <= end_date)).all()96 unmodified linesrecords = []if record_type in ["all", "receive"]:query = select(PatientVisit).options(selectinload(PatientVisit.patient)).join(Patient, PatientVisit.patient_id == Patient.id).where(Patient.is_active == True, PatientVisit.visit_date >= start_datetime, PatientVisit.visit_date <= end_datetime)if user_filter != "all":query = query.where(PatientVisit.created_by == int(user_filter))76 unmodified linesexcept ValueError:return RedirectResponse(url="/reports/patients-number?error=Invalid datetime format", status_code=status.HTTP_303_SEE_OTHER)query = select(PatientVisit).options(selectinload(PatientVisit.patient)).join(Patient, PatientVisit.patient_id == Patient.id).where(Patient.is_active == True, PatientVisit.visit_date >= start_datetime, PatientVisit.visit_date <= end_datetime)visits = session.exec(query).all()# Group by date60 unmodified linestests_list = session.exec(select(TestDefinition).where(TestDefinition.deleted_at == None)).all()devices_list = session.exec(select(Device).where(Device.deleted_at == None)).all()query = select(Order).options(selectinload(Order.test), selectinload(Order.result)).join(Patient, Order.patient_id == Patient.id).where(Patient.is_active == True, Order.order_date >= start_datetime, Order.order_date <= end_datetime)if test_filter != "all":query = query.where(Order.test_id == int(test_filter))43 unmodified lines"total_tests": total_tests})# ===========================# VISITS NUMBER REPORT# ===========================@router.get("/reports/visits-number", response_class=HTMLResponse)def visits_number_page(request: Request, session: Session = Depends(get_session)):if not require_permission(request, session, "visits_number"):return RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)start_date_str = request.query_params.get("start_date")start_time_str = request.query_params.get("start_time", "00:00")end_date_str = request.query_params.get("end_date")end_time_str = request.query_params.get("end_time", "23:59")if not start_date_str:start_date_str = datetime.now().strftime("%Y-%m-%d")if not end_date_str:end_date_str = start_date_strtry:start_datetime = datetime.strptime(f"{start_date_str} {start_time_str}", "%Y-%m-%d %H:%M")end_datetime = datetime.strptime(f"{end_date_str} {end_time_str}", "%Y-%m-%d %H:%M").replace(second=59, microsecond=999999)except ValueError:return RedirectResponse(url="/reports/visits-number?error=Invalid datetime format", status_code=status.HTTP_303_SEE_OTHER)query = select(PatientVisit).options(selectinload(PatientVisit.patient)).join(Patient, PatientVisit.patient_id == Patient.id).where(Patient.is_active == True, PatientVisit.visit_date >= start_datetime, PatientVisit.visit_date <= end_datetime)visits = session.exec(query).all()# Group by patientfrom collections import defaultdictpatient_visits = defaultdict(int)patient_info = {}for v in visits:patient_visits[v.patient_id] += 1if v.patient_id not in patient_info and v.patient:patient_info[v.patient_id] = {"patient_code": v.patient.patient_id,"patient_name": v.patient.full_name}rows = []total_visits = 0for pid, count in patient_visits.items():info = patient_info.get(pid, {"patient_code": "-", "patient_name": "-"})rows.append({"patient_code": info["patient_code"],"patient_name": info["patient_name"],"visit_count": count})total_visits += count# Sort rows by visit count descendingrows.sort(key=lambda x: x["visit_count"], reverse=True)return templates.TemplateResponse("visits_number.html", {"request": request,"start_date": start_date_str,"start_time": start_time_str,"end_date": end_date_str,"end_time": end_time_str,"rows": rows,"total_visits": total_visits})# ===========================# DISCOUNT REPORT# ===========================26 unmodified linesusers = session.exec(select(User)).all()user_dict = {u.id: u.full_name for u in users}# Query PatientVisit where discount_amount > 0 and within date range (exclude soft-deleted patients)query = select(PatientVisit).options(selectinload(PatientVisit.patient)).join(Patient, PatientVisit.patient_id == Patient.id).where(Patient.is_active == True,PatientVisit.discount_amount > 0,PatientVisit.visit_date >= start_datetime,PatientVisit.visit_date <= end_datetime)if patient_id_filter:query = query.where(Patient.patient_id.ilike(f"%{patient_id_filter}%"))if patient_name_filter:query = query.where(Patient.full_name.ilike(f"%{patient_name_filter}%"))if user_filter != "all":# Check if the user either created or edited the visit241 unmodified linesusers = session.exec(select(User)).all()user_dict = {u.id: u.full_name for u in users}# Query PatientVisit where remaining_amount > 0 and within date range (exclude soft-deleted patients)query = select(PatientVisit).options(selectinload(PatientVisit.patient)).join(Patient, PatientVisit.patient_id == Patient.id).where(Patient.is_active == True,PatientVisit.remaining_amount > 0,PatientVisit.visit_date >= start_datetime,PatientVisit.visit_date <= end_datetime)if patient_id_filter:query = query.where(Patient.patient_id.ilike(f"%{patient_id_filter}%"))if patient_name_filter:query = query.where(Patient.full_name.ilike(f"%{patient_name_filter}%"))if user_filter != "all":query = query.where(PatientVisit.created_by == int(user_filter))73 unmodified linesexcept ValueError:return RedirectResponse(url="/reports/patient-region?error=Invalid date format", status_code=status.HTTP_303_SEE_OTHER)from models import Region# Fetch all active regions for dropdownregions_list = session.exec(select(Region).where(Region.is_active == True)).all()# Exclude soft-deleted patientsquery = select(Patient).where(Patient.is_active == True, Patient.created_at >= start_datetime, Patient.created_at <= end_datetime)if region_filter != "all":query = query.where(Patient.region_id == int(region_filter))
119 unmodified lines12012112212312412512612712867 unmodified lines196197198199200201202203204205321 unmodified lines52752852953053153253353453553653753879 unmodified lines61861962062162262321 unmodified lines645646647648649650651652653654117 unmodified lines7727737747757767777781 unmodified line780781782783784785786119 unmodified lines"color": status_color}if order.package_name:if order.package_name not in packages:packages[order.package_name] = []packages[order.package_name].append(test_info)else:standalones.append(test_info)67 unmodified linesif user:visit_user_name = user.full_name or user.username# Fetch all visits for the "Previous Results" barall_visits = session.exec(select(PatientVisit).where(PatientVisit.patient_id == patient.id).order_by(PatientVisit.visit_date.asc())).all()321 unmodified lines# SAVE RESULTS API# ===========================@router.post("/api/result-entry/save")async def save_results(request: Request, session: Session = Depends(get_session)):if not require_permission(request, session, "result_entry", "save"):return JSONResponse({"error": "Permission Denied"}, status_code=403)try:current_user = get_current_user(request, session)body = await request.json()rows = body.get("rows", [])now = datetime.now()user_id = current_user.id if current_user else 179 unmodified lines# Process child parameter detailschildren = row.get("children", [])has_any_value = Falsefor child in children:param_id = child.get("parameter_id")if not param_id:21 unmodified linesif detail.result_value:has_any_value = True# Enforce status machine: ordered -> resulted -> authorized# Allow authorization when result + auth are submitted together (order still "ordered")can_authorize = authorized and order.status in ("ordered", "resulted", "authorized")result.authorized = can_authorizeif can_authorize:result.authorized_by = user_id117 unmodified lines# NO SAMPLE ACTIONS & PAGE# ===========================@router.post("/api/result-entry/no-sample/{order_id}")async def mark_no_sample(order_id: int, request: Request, session: Session = Depends(get_session)):if not require_permission(request, session, "result_entry", "no_sample"):return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403)current_user = get_current_user(request, session)1 unmodified linereturn JSONResponse({"success": False, "message": "Unauthorized"}, status_code=401)try:data = await request.json()reason = data.get("reason", "")order = session.get(Order, order_id)119 unmodified lines12012112212312412512612712812967 unmodified lines197198199200201202203204205206207208209210211321 unmodified lines53353453553653753853954054154254354479 unmodified lines62462562662762862963021 unmodified lines652653654655656657658659660661662663117 unmodified lines7817827837847857867871 unmodified line789790791792793794795119 unmodified lines"color": status_color}if order.package_name:for pkg_name in [n.strip() for n in order.package_name.split(",") if n.strip()]:if pkg_name not in packages:packages[pkg_name] = []packages[pkg_name].append(test_info)else:standalones.append(test_info)67 unmodified linesif user:visit_user_name = user.full_name or user.username# Fetch visits with double-authorized results for the "Previous Results" barall_visits = session.exec(select(PatientVisit).join(Order, Order.visit_id == PatientVisit.id).where(PatientVisit.patient_id == patient.id,Order.status == "double_authorized",).distinct().order_by(PatientVisit.visit_date.asc())).all()321 unmodified lines# SAVE RESULTS API# ===========================@router.post("/api/result-entry/save")def save_results(payload: dict, request: Request, session: Session = Depends(get_session)):if not require_permission(request, session, "result_entry", "save"):return JSONResponse({"error": "Permission Denied"}, status_code=403)try:current_user = get_current_user(request, session)body = payloadrows = body.get("rows", [])now = datetime.now()user_id = current_user.id if current_user else 179 unmodified lines# Process child parameter detailschildren = row.get("children", [])has_any_value = Falseall_have_values = Truefor child in children:param_id = child.get("parameter_id")if not param_id:21 unmodified linesif detail.result_value:has_any_value = Trueelse:all_have_values = False# Enforce status machine: ordered -> resulted -> authorized# AUTH only allowed when ALL parameters have results (not just some)can_authorize = authorized and all_have_values and order.status in ("ordered", "resulted", "authorized")result.authorized = can_authorizeif can_authorize:result.authorized_by = user_id117 unmodified lines# NO SAMPLE ACTIONS & PAGE# ===========================@router.post("/api/result-entry/no-sample/{order_id}")def mark_no_sample(order_id: int, payload: dict, request: Request, session: Session = Depends(get_session)):if not require_permission(request, session, "result_entry", "no_sample"):return JSONResponse({"success": False, "message": "Permission Denied"}, status_code=403)current_user = get_current_user(request, session)1 unmodified linereturn JSONResponse({"success": False, "message": "Unauthorized"}, status_code=401)try:data = payloadreason = data.get("reason", "")order = session.get(Order, order_id)
200 unmodified lines20120220320420520620720820921021121279 unmodified lines2922932942952962972981 unmodified line300301302303304305306200 unmodified linesformulas = session.exec(select(Formula).order_by(Formula.id.asc())).all()formulas_json = [model_to_dict(f) for f in formulas]tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all()parameters = session.exec(select(Parameter)).all()success = request.query_params.get("success")error = request.query_params.get("error")return templates.TemplateResponse("formulas.html", {"request": request, "formulas": formulas, "formulas_json": formulas_json,"tests": tests, "parameters": parameters,"message_success": success, "message_error": error})79 unmodified linesreturn RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)ranges = session.exec(select(TestRange).order_by(TestRange.id.asc())).all()ranges_json = [model_to_dict(r) for r in ranges]tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all()parameters = session.exec(select(Parameter)).all()devices = session.exec(select(Device).where(Device.is_active == True)).all()departments = session.exec(select(Department).where(Department.is_active == True)).all()1 unmodified lineerror = request.query_params.get("error")return templates.TemplateResponse("test_ranges.html", {"request": request, "ranges": ranges, "ranges_json": ranges_json,"tests": tests, "parameters": parameters, "devices": devices, "departments": departments,"message_success": success, "message_error": error})200 unmodified lines20120220320420520620720820921021121221321421521621721821922079 unmodified lines3003013023033043053063073083093103113123133141 unmodified line316317318319320321322323200 unmodified linesformulas = session.exec(select(Formula).order_by(Formula.id.asc())).all()formulas_json = [model_to_dict(f) for f in formulas]tests = session.exec(select(TestDefinition).where(TestDefinition.is_available == True)).all()tests_metadata = {t.id: {"has_params": len(t.test_parameters) > 0,"parameters": [tp.parameter_id for tp in t.test_parameters],"devices": [td.device_id for td in t.test_devices]}for t in tests}parameters = session.exec(select(Parameter)).all()success = request.query_params.get("success")error = request.query_params.get("error")return templates.TemplateResponse("formulas.html", {"request": request, "formulas": formulas, "formulas_json": formulas_json,"tests": tests, "tests_metadata": tests_metadata, "parameters": parameters,"message_success": success, "message_error": error})79 unmodified linesreturn RedirectResponse(url="/dashboard?error=Permission Denied", status_code=status.HTTP_303_SEE_OTHER)ranges = session.exec(select(TestRange).order_by(TestRange.id.asc())).all()ranges_json = [model_to_dict(r) for r in ranges]tests = session.exec(select(TestDefinition).options(selectinload(TestDefinition.test_parameters), selectinload(TestDefinition.test_devices)).where(TestDefinition.is_available == True)).all()tests_metadata = {t.id: {"has_params": bool(t.test_parameters),"parameters": [tp.parameter_id for tp in t.test_parameters],"devices": [td.device_id for td in t.test_devices]}for t in tests}parameters = session.exec(select(Parameter)).all()devices = session.exec(select(Device).where(Device.is_active == True)).all()departments = session.exec(select(Department).where(Department.is_active == True)).all()1 unmodified lineerror = request.query_params.get("error")return templates.TemplateResponse("test_ranges.html", {"request": request, "ranges": ranges, "ranges_json": ranges_json,"tests": tests, "tests_metadata": tests_metadata, "parameters": parameters,"devices": devices, "departments": departments,"message_success": success, "message_error": error})
38 unmodified lines39404142434439 unmodified lines8485868788899 unmodified lines9910010110210310420 unmodified lines12512612712812913063 unmodified lines1941951961971981994 unmodified lines2042052062072082092102112122132142155 unmodified lines221222223224225226227228229230207 unmodified lines4384394404414424437 unmodified lines45145245345445545645738 unmodified lines{"key": "print_barcode", "label": "Print Barcode"},{"key": "print_receipt", "label": "Print Receipt"},{"key": "discount", "label": "Discount"},]},"deleted_patients": {"label": "Deleted Patients", "group": "Patient Management", "buttons": [{"key": "restore", "label": "Restore"},39 unmodified lines"call_centre": {"label": "Call Centre", "group": "Printing & Design", "buttons": [{"key": "mark_called", "label": "Mark Called"},{"key": "send_whatsapp", "label": "Send WhatsApp"},]},"result_designer": {"label": "Result Designer", "group": "Printing & Design", "buttons": [{"key": "save", "label": "Save Design"},9 unmodified lines{"key": "edit", "label": "Edit"},{"key": "delete", "label": "Delete"},]},"devices": {"label": "Devices", "group": "Lab Setup", "buttons": [{"key": "create", "label": "Create"},{"key": "edit", "label": "Edit"},20 unmodified lines{"key": "edit", "label": "Edit"},{"key": "delete", "label": "Delete"},]},"test_ranges": {"label": "Test Ranges", "group": "Tests & Packages", "buttons": [{"key": "create", "label": "Create"},{"key": "edit", "label": "Edit"},63 unmodified lines{"key": "edit", "label": "Edit"},{"key": "delete", "label": "Delete"},]},# --- Settings ---"lab_info": {"label": "Lab Info", "group": "Settings", "buttons": [{"key": "edit", "label": "Edit"},4 unmodified lines{"key": "edit", "label": "Edit"},{"key": "delete", "label": "Delete"},]},"activity_logs": {"label": "Activity Logs", "group": "Settings", "buttons": [{"key": "view", "label": "View"},]},}# ===========================# USERS PAGE# ===========================5 unmodified linesusers = session.exec(select(User).order_by(User.id.asc())).all()success = request.query_params.get("success")error = request.query_params.get("error")return templates.TemplateResponse("users.html", {"request": request,"users": users,"pages_registry": PAGES_REGISTRY,"message_success": success,"message_error": error,"current_user": current_user207 unmodified linesbuttons = []permissions[p.page_key] = buttonsreturn JSONResponse({"success": True,"user": {7 unmodified lines"address": user.address or "",},"permissions": permissions,"pages_registry": PAGES_REGISTRY})# ===========================38 unmodified lines394041424344454639 unmodified lines868788899091929 unmodified lines10210310410510610710810911011111211311411511611720 unmodified lines13813914014114214314414514663 unmodified lines2102112122132142152162172182192204 unmodified lines2252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712725 unmodified lines278279280281282283284285286287288289290291207 unmodified lines4995005015025035045055065075087 unmodified lines51651751851952052152238 unmodified lines{"key": "print_barcode", "label": "Print Barcode"},{"key": "print_receipt", "label": "Print Receipt"},{"key": "discount", "label": "Discount"},{"key": "remove", "label": "Remove Test"},{"key": "delete_visit", "label": "Delete Visit"},]},"deleted_patients": {"label": "Deleted Patients", "group": "Patient Management", "buttons": [{"key": "restore", "label": "Restore"},39 unmodified lines"call_centre": {"label": "Call Centre", "group": "Printing & Design", "buttons": [{"key": "mark_called", "label": "Mark Called"},{"key": "send_whatsapp", "label": "Send WhatsApp"},{"key": "mark_printed", "label": "Mark Printed"},]},"result_designer": {"label": "Result Designer", "group": "Printing & Design", "buttons": [{"key": "save", "label": "Save Design"},9 unmodified lines{"key": "edit", "label": "Edit"},{"key": "delete", "label": "Delete"},]},"inventory": {"label": "Inventory", "group": "Lab Setup", "buttons": [{"key": "create", "label": "Create"},{"key": "edit", "label": "Edit"},{"key": "delete", "label": "Delete"},]},"supplies": {"label": "Supplies", "group": "Lab Setup", "buttons": [{"key": "create", "label": "Create"},{"key": "edit", "label": "Edit"},{"key": "delete", "label": "Delete"},]},"devices": {"label": "Devices", "group": "Lab Setup", "buttons": [{"key": "create", "label": "Create"},{"key": "edit", "label": "Edit"},20 unmodified lines{"key": "edit", "label": "Edit"},{"key": "delete", "label": "Delete"},]},"cal_control": {"label": "Cal & Control", "group": "Tests & Packages", "buttons": [{"key": "create", "label": "Create"},]},"test_ranges": {"label": "Test Ranges", "group": "Tests & Packages", "buttons": [{"key": "create", "label": "Create"},{"key": "edit", "label": "Edit"},63 unmodified lines{"key": "edit", "label": "Edit"},{"key": "delete", "label": "Delete"},]},"patient_region": {"label": "Patient Region", "group": "Geography & Partners", "buttons": [{"key": "create", "label": "Create"},{"key": "edit", "label": "Edit"},{"key": "delete", "label": "Delete"},]},# --- Settings ---"lab_info": {"label": "Lab Info", "group": "Settings", "buttons": [{"key": "edit", "label": "Edit"},4 unmodified lines{"key": "edit", "label": "Edit"},{"key": "delete", "label": "Delete"},]},"hr": {"label": "Human Resources", "group": "Settings", "buttons": [{"key": "create", "label": "Create"},{"key": "edit", "label": "Edit"},{"key": "delete", "label": "Delete"},]},"activity_logs": {"label": "Activity Logs", "group": "Settings", "buttons": [{"key": "view", "label": "View"},]},"settings": {"label": "General Settings", "group": "Settings", "buttons": []},}# ===========================# Helper: Filter Registry for Current User# ===========================def _get_filtered_registry(user: User, session: Session) -> dict:"""Returns a filtered PAGES_REGISTRY containing only the pages and buttons the user has."""if user.role == 'admin' or user.username == 'admin':return PAGES_REGISTRYperms = session.exec(select(UserPermission).where(UserPermission.user_id == user.id)).all()user_perms = {}for p in perms:buttons = []if p.allowed_buttons:try:buttons = json.loads(p.allowed_buttons)except Exception:passuser_perms[p.page_key] = buttonsfiltered = {}for page_key, page_info in PAGES_REGISTRY.items():if page_key in user_perms:allowed_btns = user_perms[page_key]filtered_page = page_info.copy()# Only keep buttons the user actually has permission forfiltered_page["buttons"] = [btn for btn in page_info.get("buttons", []) if btn["key"] in allowed_btns]filtered[page_key] = filtered_pagereturn filtered# ===========================# USERS PAGE# ===========================5 unmodified linesusers = session.exec(select(User).order_by(User.id.asc())).all()success = request.query_params.get("success")error = request.query_params.get("error")# Filter the registry so users can only assign permissions they possessfiltered_registry = _get_filtered_registry(current_user, session)return templates.TemplateResponse("users.html", {"request": request,"users": users,"pages_registry": filtered_registry,"message_success": success,"message_error": error,"current_user": current_user207 unmodified linesbuttons = []permissions[p.page_key] = buttons# Include filtered registry in API response as well, so frontend knows what to displaycurrent_user = get_current_user(request, session)filtered_registry = _get_filtered_registry(current_user, session)return JSONResponse({"success": True,"user": {7 unmodified lines"address": user.address or "",},"permissions": permissions,"pages_registry": filtered_registry})# ===========================
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266# routes/whatsapp_notifier.py# Background WhatsApp Group Notification Engine# Checks every 15 minutes for patients stuck in Pending (>2h) or Authorize (>5m)# and sends a one-time notification to the configured WhatsApp group.
import tracebackfrom datetime import datetime, timedeltafrom sqlmodel import Session, selectfrom sqlalchemy.orm import selectinloadimport requestsimport jsonimport asyncio
from database import enginefrom models import LabInfo, PatientVisit, Order, Result, Patient, WhatsAppNotificationLogfrom routes.whatsapp_utils import send_whatsapp_text
def check_and_notify(): """ Main notification check — called by scheduled loop every 15 minutes. Scans today's visits for: 1. Pending status for > 2 hours → send Arabic notification 2. Authorize status for > 5 minutes → send Arabic notification Each notification is sent ONCE per visit per type (tracked in whatsapp_notification_log). """ try: with Session(engine) as session: # 1. Load lab info & check if notifications are enabled lab_info = session.exec(select(LabInfo).limit(1)).first() if not lab_info: return if not getattr(lab_info, 'whatsapp_notify_enabled', False): return if not getattr(lab_info, 'whatsapp_group_id', None) or not lab_info.whatsapp_group_id.strip(): return if not getattr(lab_info, 'whatsapp_api', None) or not getattr(lab_info, 'whatsapp_token', None): return
group_id = lab_info.whatsapp_group_id.strip() lab_name = lab_info.lab_name or "المختبر"
# Build lab_info dict for send_whatsapp_text lab_info_dict = { "whatsapp_api": lab_info.whatsapp_api, "whatsapp_token": lab_info.whatsapp_token, }
now = datetime.now() today_str = now.strftime('%Y-%m-%d')
# 2. Load today's visits with orders and results visits = session.exec( select(PatientVisit).options( selectinload(PatientVisit.patient), selectinload(PatientVisit.orders).selectinload(Order.result) ).where( PatientVisit.visit_date >= today_str, PatientVisit.visit_date <= f"{today_str} 23:59:59" ) ).all()
# 3. Load existing notification logs for today to skip already-notified existing_logs = session.exec( select(WhatsAppNotificationLog).where( WhatsAppNotificationLog.sent_at >= today_str ) ).all() notified_set = {(log.visit_id, log.notification_type) for log in existing_logs}
pending_2h_threshold = now - timedelta(hours=2) authorize_5m_threshold = now - timedelta(minutes=5)
notifications_to_send = []
for visit in visits: if not visit.orders or not visit.patient: continue
patient_name = visit.patient.full_name visit_id = visit.id total_orders = len(visit.orders) if total_orders == 0: continue
# Determine visit status (same logic as call_centre.py) has_pending = False all_authorized = True all_double_auth = True earliest_authorize_at = None
for order in visit.orders: res = order.result if not res or not res.authorized: has_pending = True all_authorized = False all_double_auth = False else: is_da = getattr(res, 'double_authorized', getattr(res, 'is_double_authorized', False)) if not is_da: all_double_auth = False # Track when this was authorized (for the 5-minute check) if res.authorized_at: if earliest_authorize_at is None or res.authorized_at < earliest_authorize_at: earliest_authorize_at = res.authorized_at
# Check 1: Pending for > 2 hours if has_pending and visit.visit_date and visit.visit_date <= pending_2h_threshold: if (visit_id, "pending_2h") not in notified_set: msg = ( f"مرحبا، مرت اكثر من ساعتين ولا تزال نتائج المراجع " f"( {patient_name} ) " f"غير مكتملة في ({lab_name})" ) notifications_to_send.append((visit_id, "pending_2h", msg))
# Check 2: Authorize (not double auth) for > 5 minutes if all_authorized and not all_double_auth and not has_pending: if earliest_authorize_at and earliest_authorize_at <= authorize_5m_threshold: if (visit_id, "authorize_5m") not in notified_set: msg = ( f"مرحبا، لا تزال حالة المراجع " f"( {patient_name} ) " f"اثرايز ، يرجى اعطاء دبل اثرايز\n" f"في ( {lab_name} )" ) notifications_to_send.append((visit_id, "authorize_5m", msg))
# 4. Send notifications for visit_id, notif_type, message in notifications_to_send: try: result = send_whatsapp_text(group_id, message, lab_info_dict) status = result.get("status", "unknown")
if status == "queued": # Log successful notification log_entry = WhatsAppNotificationLog( visit_id=visit_id, notification_type=notif_type, sent_at=datetime.now() ) session.add(log_entry) print(f"✅ WhatsApp group notification queued: {notif_type} for visit {visit_id}") else: print(f"⚠️ WhatsApp group notification failed for visit {visit_id}: {result}")
except Exception as e: print(f"❌ Error sending WhatsApp group notification for visit {visit_id}: {e}") traceback.print_exc()
if notifications_to_send: session.commit() print(f"📤 Sent {len(notifications_to_send)} WhatsApp group notification(s)") else: pass
except Exception as e: print(f"❌ WhatsApp notifier error: {e}") traceback.print_exc()
def process_whatsapp_queue(): """ Background worker that polls the WhatsAppQueue and sends pending messages. Deletes the payload if it fails completely (to save space), but leaves the row. If success, it marks status as 'sent' and saves the Meta message ID. """ try: from app.models.lab import WhatsAppQueue with Session(engine) as session: # Get LabInfo for credentials lab_info = session.exec(select(LabInfo).limit(1)).first() if not lab_info or not getattr(lab_info, 'whatsapp_api', None) or not getattr(lab_info, 'whatsapp_token', None): return
instance_id = lab_info.whatsapp_api.strip() token = lab_info.whatsapp_token.strip()
pending_items = session.exec( select(WhatsAppQueue) .where(WhatsAppQueue.status == "pending") .where(WhatsAppQueue.retries < 3) .order_by(WhatsAppQueue.created_at.asc()) .limit(10) ).all()
for item in pending_items: try: payload_dict = json.loads(item.payload) msg_type = payload_dict.get("type") if msg_type == "pdf": url = f"https://api.ultramsg.com/{instance_id}/messages/document" api_payload = { 'token': token, 'to': payload_dict.get('to'), 'filename': payload_dict.get('filename'), 'document': payload_dict.get('document'), 'caption': payload_dict.get('caption') } else: url = f"https://api.ultramsg.com/{instance_id}/messages/chat" api_payload = { 'token': token, 'to': payload_dict.get('to'), 'body': payload_dict.get('body') }
response = requests.post(url, data=api_payload, timeout=15) if response.status_code in [200, 201]: res_json = response.json() if str(res_json.get("sent", "")).lower() != "false" and not res_json.get("error"): item.status = "sent" item.message_id = str(res_json.get("id", "")) item.updated_at = datetime.now() else: # API returned success HTTP code but logically failed item.retries += 1 item.updated_at = datetime.now() if item.retries >= 3: item.status = "failed" item.payload = "{}" # CLEAR LARGE PAYLOAD else: item.retries += 1 item.updated_at = datetime.now() if item.retries >= 3: item.status = "failed" item.payload = "{}" # CLEAR LARGE PAYLOAD except Exception as e: print(f"❌ Error processing queue item {item.id}: {e}") item.retries += 1 item.updated_at = datetime.now() if item.retries >= 3: item.status = "failed" item.payload = "{}" # CLEAR LARGE PAYLOAD
if pending_items: session.commit()
except Exception as e: print(f"❌ WhatsApp queue worker error: {e}") traceback.print_exc()
async def notifier_loop(): while True: try: # Sleep 15 mins (900 seconds) await asyncio.sleep(900) # Run the sync function in a thread to not block event loop await asyncio.to_thread(check_and_notify) except asyncio.CancelledError: break except Exception as e: print(f"Notifier loop error: {e}")
async def whatsapp_queue_loop(): while True: try: await asyncio.to_thread(process_whatsapp_queue) await asyncio.sleep(10) except asyncio.CancelledError: break except Exception as e: print(f"Queue loop error: {e}") await asyncio.sleep(10)123452 unmodified lines891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731746 unmodified lines181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219import osimport base64import requestsimport tracebackfrom fastapi.templating import Jinja2Templates2 unmodified lines# Setup Jinja2 to point to your templates foldertemplates = Jinja2Templates(directory="templates")def send_wati_pdf(phone_number, pdf_bytes, filename, caption, lab_info_dict):"""Sends the generated PDF via Wati API using dynamic database credentials."""try:# Dynamically fetch from the LabInfo dictionarywati_endpoint = lab_info_dict.get("whatsapp_api", "") if lab_info_dict else ""token = lab_info_dict.get("whatsapp_token", "") if lab_info_dict else ""# Clean token just in case user pasted 'Bearer ' with itif token.lower().startswith("bearer "):token = token[7:].strip()# If no credentials exist in the database, abort and return a clear errorif not wati_endpoint or not token:print("⚠️ Wati credentials missing from LabInfo database.")return {"status": "error", "message": "WhatsApp API credentials are not configured in settings."}# Ensure the endpoint does not end with a slash and has https://wati_endpoint = wati_endpoint.strip()if wati_endpoint and not wati_endpoint.startswith("http"):wati_endpoint = f"https://{wati_endpoint}"# If the user included /api/v1 in the URL, strip it to prevent duplicationif "/api/v1" in wati_endpoint:wati_endpoint = wati_endpoint.split("/api/v1")[0]base_url = wati_endpoint.rstrip("/")# Wati API expects the phone number without the '+' signclean_phone = phone_number.replace("+", "")url = f"{base_url}/api/v1/sendSessionFile/{clean_phone}"headers = {"Authorization": f"Bearer {token}"# Requests will set Content-Type correctly for multipart/form-data}files = {'file': (filename, pdf_bytes, 'application/pdf')}# Wati generally expects caption as a query parameter for sendSessionFileparams = {"caption": caption}response = requests.post(url, headers=headers, params=params, files=files)print("WATI API RESPONSE CODE:", response.status_code)print("WATI API RESPONSE TEXT:", response.text)res_json = {}try:res_json = response.json()except Exception:res_json = {"status": "success" if response.status_code in [200, 201] else "error", "message": response.text}if response.status_code not in [200, 201] or str(res_json.get("result", "")).lower() == "error" or res_json.get("error"):res_json["status"] = "error"return res_jsonexcept Exception as e:print(f"WhatsApp sending failed: {e}")traceback.print_exc()return {"status": "error", "message": str(e)}def send_wati_text(phone_number, message_text, lab_info_dict, template_name=None):"""Sends a WhatsApp message via Wati API.Tries session message first. If contact is new (hasn't messaged first),automatically falls back to template message."""try:wati_endpoint = lab_info_dict.get("whatsapp_api", "") if lab_info_dict else ""token = lab_info_dict.get("whatsapp_token", "") if lab_info_dict else ""if token.lower().startswith("bearer "):token = token[7:].strip()if not wati_endpoint or not token:return {"status": "error", "message": "WhatsApp API credentials are not configured."}wati_endpoint = wati_endpoint.strip()if not wati_endpoint.startswith("http"):wati_endpoint = f"https://{wati_endpoint}"if "/api/v1" in wati_endpoint:wati_endpoint = wati_endpoint.split("/api/v1")[0]base_url = wati_endpoint.rstrip("/")clean_phone = phone_number.replace("+", "")headers = {"Authorization": f"Bearer {token}"}# --- Step 1: Try session message (works if contact messaged before) ---url = f"{base_url}/api/v1/sendSessionMessage/{clean_phone}"response = requests.post(url, headers=headers, params={"messageText": message_text})print("WATI SESSION RESPONSE:", response.status_code, response.text[:200])res_json = {}try:res_json = response.json()except Exception:res_json = {"status": "success" if response.status_code in [200, 201] else "error"}# Check if session message succeededis_invalid_contact = "invalid contact" in str(res_json.get("info", "")).lower()session_ok = response.status_code in [200, 201] and res_json.get("result") != False and not is_invalid_contactif session_ok:return res_json# --- Step 2: Fallback to template message (works for new contacts) ---if not template_name:template_name = lab_info_dict.get("welcome_template_name", "") if lab_info_dict else ""if not template_name:print("⚠️ No template name configured — cannot send to new contact")return {"status": "error", "message": "Contact hasn't messaged first and no Wati template name is configured."}print(f"📨 Falling back to template message: {template_name}")template_url = f"{base_url}/api/v1/sendTemplateMessage/{clean_phone}"template_payload = {"template_name": template_name,"broadcast_name": "welcome_registration"}tmpl_response = requests.post(template_url, headers={**headers, "Content-Type": "application/json"}, json=template_payload)print("WATI TEMPLATE RESPONSE:", tmpl_response.status_code, tmpl_response.text[:200])tmpl_json = {}try:tmpl_json = tmpl_response.json()except Exception:tmpl_json = {"status": "success" if tmpl_response.status_code in [200, 201] else "error", "message": tmpl_response.text}if tmpl_response.status_code not in [200, 201] or str(tmpl_json.get("result", "")).lower() == "error":tmpl_json["status"] = "error"return tmpl_jsonexcept Exception as e:print(f"WhatsApp text sending failed: {e}")traceback.print_exc()return {"status": "error", "message": str(e)}def generate_report_pdf(patient, visit, results, lab_info, template_data, barcode_data=None):"""Optimized Playwright PDF generator for maximum speed."""print("🚀🚀🚀 PLAYWRIGHT ENGINE IS STARTING (OPTIMIZED)! 🚀🚀🚀")try:# Fetch formatted results quicklytry:patient_id = patient.get("patient_id")api_url = f"http://127.0.0.1:8000/api/double-authorized-tests/{patient_id}"api_resp = requests.get(api_url, timeout=3)if api_resp.status_code == 200:api_data = api_resp.json()if api_data.get("success"):results = api_data.get("results", [])except Exception as api_err:print(f"⚠️ Local API fetch failed: {api_err}")# Render Templatetemplate = templates.get_template("print_report.html")6 unmodified lines"results": results})paper_size = template_data.get('paperSize', 'A4').upper()os.makedirs("tmp", exist_ok=True)html_content = html_content.replace("<head>", "<head><base href='http://127.0.0.1:8000/'>")# Fire up Headless Chrome with Speed Optimizationswith sync_playwright() as p:browser = p.chromium.launch(headless=True,args=['--disable-gpu','--disable-dev-shm-usage','--disable-setuid-sandbox','--no-sandbox','--single-process'])page = browser.new_page()page.set_content(html_content, wait_until="load")page.evaluate("document.fonts.ready")pdf_bytes = page.pdf(format=paper_size,print_background=True,margin={"top": "0", "right": "0", "bottom": "0", "left": "0"})browser.close()with open("tmp/last_whatsapp_report.pdf", "wb") as f:f.write(pdf_bytes)return pdf_bytesexcept Exception as e:traceback.print_exc()raise e12345672 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992006 unmodified lines207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302import osimport reimport base64import jsonimport requestsimport tracebackfrom fastapi.templating import Jinja2Templates2 unmodified lines# Setup Jinja2 to point to your templates foldertemplates = Jinja2Templates(directory="templates")# =============================================================# ⚡ STATIC ASSET CACHE — read CSS/fonts from disk only once# =============================================================_static_cache = {}def _get_cached_asset(path, mode="r"):if path not in _static_cache:if os.path.exists(path):with open(path, mode, encoding="utf-8" if mode == "r" else None) as f:_static_cache[path] = f.read()else:_static_cache[path] = Nonereturn _static_cache[path]def _get_tailwind_css():return _get_cached_asset("static/tailwind.min.css", "r")def _get_fonts_css_with_embedded_fonts():cache_key = "__fonts_css_embedded__"if cache_key in _static_cache:return _static_cache[cache_key]fonts_css = _get_cached_asset("static/vendor/fonts/fonts.css", "r")if not fonts_css:_static_cache[cache_key] = Nonereturn Noneurls = set(re.findall(r"url\('(/static/vendor/fonts/[^']+)'\)", fonts_css))for url_path in urls:local_path = url_path.lstrip('/')if os.path.exists(local_path):with open(local_path, "rb") as font_file:b64 = base64.b64encode(font_file.read()).decode('utf-8')fonts_css = fonts_css.replace(f"url('{url_path}')", f"url('data:font/truetype;base64,{b64}')")_static_cache[cache_key] = fonts_cssreturn fonts_cssdef _get_alfont_b64():cache_key = "__alfont_b64__"if cache_key in _static_cache:return _static_cache[cache_key]alfont_path = "uploads/alfont_com_FormaDJRArabicDeck-Bold-Testing.otf"if os.path.exists(alfont_path):with open(alfont_path, "rb") as f:_static_cache[cache_key] = base64.b64encode(f.read()).decode('utf-8')else:_static_cache[cache_key] = Nonereturn _static_cache[cache_key]def send_whatsapp_pdf(phone_number, pdf_bytes, filename, caption, lab_info_dict, visit_id=None):"""Queues the generated PDF for sending via UltraMsg API using dynamic database credentials."""try:from database import enginefrom sqlmodel import Sessionfrom app.models.lab import WhatsAppQueue# Dynamically fetch from the LabInfo dictionaryinstance_id = lab_info_dict.get("whatsapp_api", "") if lab_info_dict else ""token = lab_info_dict.get("whatsapp_token", "") if lab_info_dict else ""# If no credentials exist in the database, abort and return a clear errorif not instance_id or not token:print("⚠️ UltraMsg credentials missing from LabInfo database.")return {"status": "error", "message": "WhatsApp API credentials are not configured in settings."}clean_phone = phone_number.replace("+", "")# Convert PDF bytes to Base64encoded_string = base64.b64encode(pdf_bytes).decode('utf-8')document_data = f"data:application/pdf;base64,{encoded_string}"payload_dict = {'type': 'pdf','to': clean_phone,'filename': filename,'document': document_data,'caption': caption}with Session(engine) as session:queue_item = WhatsAppQueue(visit_id=str(visit_id) if visit_id else None,payload=json.dumps(payload_dict),status="pending")session.add(queue_item)session.commit()print("✅ WhatsApp PDF queued successfully!")return {"status": "queued"}except Exception as e:print(f"WhatsApp PDF queueing failed: {e}")traceback.print_exc()return {"status": "error", "message": str(e)}def send_whatsapp_text(phone_number, message_text, lab_info_dict, visit_id=None):"""Queues a WhatsApp text message via UltraMsg API."""try:from database import enginefrom sqlmodel import Sessionfrom app.models.lab import WhatsAppQueueinstance_id = lab_info_dict.get("whatsapp_api", "") if lab_info_dict else ""token = lab_info_dict.get("whatsapp_token", "") if lab_info_dict else ""if not instance_id or not token:return {"status": "error", "message": "WhatsApp API credentials are not configured."}clean_phone = phone_number.replace("+", "")payload_dict = {'type': 'text','to': clean_phone,'body': message_text}with Session(engine) as session:queue_item = WhatsAppQueue(visit_id=str(visit_id) if visit_id else None,payload=json.dumps(payload_dict),status="pending")session.add(queue_item)session.commit()print("✅ WhatsApp text queued successfully!")return {"status": "queued"}except Exception as e:print(f"WhatsApp text queueing failed: {e}")traceback.print_exc()return {"status": "error", "message": str(e)}import asynciodef _generate_report_pdf_sync(patient, visit, results, lab_info, template_data, barcode_data=None, base_url="http://127.0.0.1:8000/"):"""Optimized Playwright PDF generator — cached assets + fast wait strategy.Each call launches its own Playwright context to avoid greenlet threading issueswhen called from FastAPI background tasks."""print("🚀🚀🚀 PLAYWRIGHT ENGINE IS STARTING (OPTIMIZED)! 🚀🚀🚀")try:# Use the provided 'results' list directly (which correctly reflects the user's selected tests)# Convert all LabInfo images and Template Watermarks to Base64 to bypass network errors completelydef to_base64(filename):if not filename: return filenamefilepath = os.path.join("uploads", filename)if os.path.exists(filepath):try:with open(filepath, "rb") as img_file:b64 = base64.b64encode(img_file.read()).decode('utf-8')ext = filepath.split('.')[-1].lower()mime = f"image/{ext}" if ext in ['png', 'jpeg', 'jpg', 'gif', 'svg'] else "image/png"return f"data:{mime};base64,{b64}"except Exception as e:print(f"⚠️ Failed to encode image {filename}: {e}")return filenameif isinstance(lab_info, dict):for key in ['lab_logo', 'lab_stamp_1', 'lab_stamp_2', 'lab_signature_1', 'lab_signature_2', 'lab_image_1', 'lab_image_2', 'lab_qr_1', 'lab_qr_2']:if lab_info.get(key):lab_info[key] = to_base64(lab_info[key])if template_data and isinstance(template_data, dict):elements_data = template_data.get("elements", "[]")if isinstance(elements_data, str):try:elements_data = json.loads(elements_data)except:elements_data = []# Process watermark imageselements_list = elements_data.get("elements", []) if isinstance(elements_data, dict) else elements_datafor el in elements_list:if isinstance(el, dict) and el.get("type") == "watermark" and el.get("image"):el["image"] = to_base64(el["image"])# MUST put it back as a string so print_report.html `JSON.parse` doesn't crash!template_data["elements"] = json.dumps(elements_data)# Render Templatetemplate = templates.get_template("print_report.html")6 unmodified lines"results": results})# Base64 embed the custom Arabic font (cached — no disk I/O after first call)alfont_b64 = _get_alfont_b64()if alfont_b64:html_content = html_content.replace("url('/uploads/alfont_com_FormaDJRArabicDeck-Bold-Testing.otf')",f"url('data:font/opentype;base64,{alfont_b64}')")# Inject Tailwind CSS inline (cached — no disk I/O after first call)tailwind_css = _get_tailwind_css()if tailwind_css:html_content = html_content.replace('<link href="/static/tailwind.min.css" rel="stylesheet">',f"<style>{tailwind_css}</style>")# Inject fonts.css and its fonts directly (cached — no disk I/O after first call)fonts_css = _get_fonts_css_with_embedded_fonts()if fonts_css:html_content = html_content.replace('<link href="/static/vendor/fonts/fonts.css" rel="stylesheet">',f"<style>{fonts_css}</style>")paper_size = template_data.get('paperSize', 'A4').upper()os.makedirs("tmp", exist_ok=True)html_content = html_content.replace("<head>", f"<head><base href='{base_url}'>")# ⚡ Launch Playwright fresh in THIS thread's greenlet context (safe for background tasks)# Retry once if Chromium crashes (can happen with very large HTML payloads)last_error = Nonefor attempt in range(2):try:with sync_playwright() as p:browser = p.chromium.launch(headless=True,args=['--disable-gpu','--disable-dev-shm-usage','--disable-setuid-sandbox','--no-sandbox','--disable-extensions','--disable-background-networking','--disable-sync','--disable-translate',])try:context = browser.new_context(viewport={'width': 794, 'height': 1122},device_scale_factor=1)page = context.new_page()# ⚡ Use 'domcontentloaded' — all assets are already inlined (CSS, fonts, images),# so no network requests need to finish.page.set_content(html_content, wait_until="domcontentloaded", timeout=30000)# CRITICAL: Emulate print media so elements render with @media print CSS rules perfectlypage.emulate_media(media="print")page.evaluate("document.fonts.ready")pdf_bytes = page.pdf(format=paper_size,prefer_css_page_size=False,print_background=True,margin={"top": "0", "right": "0", "bottom": "0", "left": "0"})finally:browser.close()with open("tmp/last_whatsapp_report.pdf", "wb") as f:f.write(pdf_bytes)return pdf_bytesexcept Exception as e:last_error = eif attempt == 0:print(f"⚠️ Playwright attempt 1 failed ({e}), retrying...")continueelse:raise last_errorexcept Exception as e:traceback.print_exc()raise easync def generate_report_pdf(*args, **kwargs):"""Async wrapper that offloads the entire synchronous Playwright blockto a background thread, preventing the FastAPI event loop from freezing."""return await asyncio.to_thread(_generate_report_pdf_sync, *args, **kwargs)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166@echo offsetlocal EnableDelayedExpansioncd /d "%~dp0"
echo ==========================================echo NexLab Safe System Updateecho ==========================================echo.
set "VENV_PATH=venv"set "PYTHON_EXE=%VENV_PATH%\Scripts\python.exe"set "DB_FILE=lab_database.db"set "UPDATE_FOLDER=NexLab_Update"
:: ──────────────────────────────────────────────:: PRE-FLIGHT CHECKS:: ──────────────────────────────────────────────
:: Check Python / venv existsif not exist "%PYTHON_EXE%" ( echo [ERROR] Virtual environment not found at '%VENV_PATH%'. echo Please run 'install_requirements.bat' first. pause exit /b 1)
:: Check database existsif not exist "%DB_FILE%" ( echo [ERROR] Database file '%DB_FILE%' not found. echo This script must be run from inside the NexLab_Published folder. pause exit /b 1)
:: Check update folder existsif not exist "%UPDATE_FOLDER%" ( echo [ERROR] Update folder '%UPDATE_FOLDER%' not found! echo. echo HOW TO USE THIS SCRIPT: echo 1. Stop the NexLab server ^(close the start_nexlab window^) echo 2. Copy the new NexLab_Published folder NEXT to this script echo and rename it to '%UPDATE_FOLDER%' echo 3. Run this script again echo. pause exit /b 1)
:: ──────────────────────────────────────────────:: STEP 1: Confirm server is stopped:: ──────────────────────────────────────────────echo [IMPORTANT] Make sure the NexLab server is STOPPED before continuing.echo Close the 'start_nexlab.bat' window if it is open.echo.set /p confirm="Is the server stopped? (y/n): "if /i "%confirm%" NEQ "y" ( echo Update cancelled. Please stop the server and try again. pause exit /b 0)echo.
:: ──────────────────────────────────────────────:: STEP 2: Checkpoint the database (flush WAL):: ──────────────────────────────────────────────echo [Step 1/5] Flushing database writes (WAL checkpoint)..."%PYTHON_EXE%" tools\checkpoint_db.pyif %ERRORLEVEL% NEQ 0 ( echo [ERROR] Database checkpoint failed. Update cancelled for safety. echo Make sure the server is completely stopped and try again. pause exit /b 1)echo Done.echo.
:: ──────────────────────────────────────────────:: STEP 3: Backup the database:: ──────────────────────────────────────────────echo [Step 2/5] Backing up database..."%PYTHON_EXE%" tools\backup_db.pyif %ERRORLEVEL% NEQ 0 ( echo [ERROR] Database backup failed. Update cancelled for safety. pause exit /b 1)echo Done.echo.
:: ──────────────────────────────────────────────:: STEP 4: Copy new code files (PROTECT data files):: ──────────────────────────────────────────────echo [Step 3/5] Updating system files...echo Protected files (will NOT be overwritten):echo - lab_database.db (and WAL/SHM files)echo - .env (server configuration)echo - venv\ (Python environment)echo - backups\ (database backups)echo - uploads\ (patient attachments)echo.
:: Use robocopy to merge new files into the current folder.:: /E = copy subdirectories including empty ones:: /XF = exclude specific files:: /XD = exclude specific directories:: /NFL = no file listing (cleaner output):: /NDL = no directory listing:: /NJH = no job header:: /NJS = no job summary :: /IS = include same files (overwrite even if identical):: /IT = include tweaked filesrobocopy "%UPDATE_FOLDER%" "." /E /IS /IT /XF "lab_database.db" "lab_database.db-wal" "lab_database.db-shm" ".env" /XD "venv" "backups" "uploads" "__pycache__" /NFL /NDL /NJH /NJS
:: Robocopy returns codes 0-7 for success, 8+ for errorsif %ERRORLEVEL% GEQ 8 ( echo [ERROR] File copy failed with error code %ERRORLEVEL%. echo Your database is safe. Check the update folder and try again. pause exit /b 1)echo System files updated successfully.echo.
:: ──────────────────────────────────────────────:: STEP 5: Install any new dependencies:: ──────────────────────────────────────────────echo [Step 4/5] Checking for new dependencies..."%VENV_PATH%\Scripts\pip.exe" install -r requirements.txt --quiet 2>nulecho Dependencies up to date.echo.
:: ──────────────────────────────────────────────:: STEP 6: Run database migrations:: ──────────────────────────────────────────────echo [Step 5/5] Running database migrations..."%PYTHON_EXE%" migrations\run_all.pyif %ERRORLEVEL% NEQ 0 ( echo [WARNING] Some migrations may have had issues. Check output above. echo Your database backup is safe in the 'backups' folder.)echo.
:: ──────────────────────────────────────────────:: DONE — Clean up update folder:: ──────────────────────────────────────────────echo ==========================================echo Update Complete!echo ==========================================echo.echo Your database and patient data are safe.echo A backup was created in the 'backups' folder.echo.
:: Auto-cleanup the update folderecho Cleaning up update folder...rmdir /S /Q "%UPDATE_FOLDER%" 2>nulif not exist "%UPDATE_FOLDER%" ( echo '%UPDATE_FOLDER%' folder removed automatically.) else ( echo Could not remove '%UPDATE_FOLDER%' folder. You can delete it manually.)echo.echo You can now run 'start_nexlab.bat' to start the system.echo.pause
1234567891011121314151617181920212223242526272829303132333435363738394041import osimport google_auth_oauthlib.flowimport google.oauth2.credentials
# ── Configuration ──────────────────────────────────────────────SCOPES = ["https://www.googleapis.com/auth/drive"]
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))CLIENT_SECRETS_FILE = os.path.join(PROJECT_ROOT, "client_secret.json")TOKEN_FILE = os.path.join(PROJECT_ROOT, "token.json")
def main(): if not os.path.exists(CLIENT_SECRETS_FILE): print(f"❌ Error: {CLIENT_SECRETS_FILE} not found!") print("Please download your OAuth 2.0 Client ID JSON from Google Cloud Console and save it as client_secret.json in the project folder.") return
print("Opening browser for Google Login...") flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file( CLIENT_SECRETS_FILE, SCOPES ) # Force consent prompt and offline access to ensure a long-lived refresh token is returned creds = flow.run_local_server(port=0, prompt="consent", access_type="offline")
# Save the credentials (including the refresh token) for the main app to use with open(TOKEN_FILE, "w", encoding="utf-8") as token: token.write(creds.to_json()) print(f"\n✅ Success! token.json has been created at {TOKEN_FILE}.") print("The system will now use this token to upload files directly to your Google Drive and generate QR codes.") print("\n⚠️ IMPORTANT NOTE ABOUT EXPIRATION:") print("If your Google Cloud OAuth Consent Screen is in 'Testing' mode, tokens expire every 7 days.") print("To make this token permanent:") print("1. Open: https://console.cloud.google.com/apis/credentials/consent") print("2. Click 'PUBLISH APP' (نشر التطبيق) to move out of Testing mode.") print("3. Run this script once. Your authorization will never expire!")
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:8d24a37e829f423a2816d4d33775cde56621c0eb7c97f114ddfae22fba88f4f5size 765952123version https://git-lfs.github.com/spec/v1oid sha256:04102c610a2e8d4e1eaec72b4c792b101ed68288b3eb4e5ed29cc025b2d4afe0size 806912
20 unmodified lines2122232425262720 unmodified lines'dashboard': [],'patient_registration': ["save_registration", "discount", "print_barcode", "print_receipt"],'patients': ["edit", "delete", "print_barcode", "result_entry"],'patient_edit': ["save", "print_barcode", "print_receipt", "discount"],'deleted_patients': ["restore", "view"],'deleted_tests': [],'patient_history': [],20 unmodified lines2122232425262720 unmodified lines'dashboard': [],'patient_registration': ["save_registration", "discount", "print_barcode", "print_receipt"],'patients': ["edit", "delete", "print_barcode", "result_entry"],'patient_edit': ["save", "print_barcode", "print_receipt", "discount", "remove", "delete_visit"],'deleted_patients': ["restore", "view"],'deleted_tests': [],'patient_history': [],
123version https://git-lfs.github.com/spec/v1oid sha256:cfccb794268e7d573d857e6d6a67f89cf8a053e8ffd85dfa0c8ec1bb36fc4827size 413480.gitattributes+1
.gitignore+7
System_Update_Guide.md+66-24
app/database.py+25-6
app/main.py+45
app/middleware.py+26-8
app/models/__init__.py+6-4
app/models/ai_agent.pyAdded+20
app/models/finance.py+11
app/models/lab.py+24
app/models/order.py+1-1
app/models/patient.py+3-1
app/services/ai_data_queries.pyAdded+1239
app/services/ai_setup_agent.pyAdded
app/services/barcode_image_service.py+10-12
app/services/gdrive_service.pyAdded+262
app/services/patient_service.py+4-3
app/services/pdf_service.py+5-7
audit_base.pyAdded+12
audit_permissions.pyAdded+256
migrations/migrate_gdrive.pyAdded+59
migrations/migrate_whatsapp.pyAdded+28
package_app.py+4-2
render.yamlAdded+33
requirements.txt+6
routes/ai_agent.pyAdded+195
routes/api.py+1-1
routes/auth.py+1
routes/cal_control.py+3-3
routes/call_centre.py+169-62
routes/discount_rules.pyAdded+110
routes/double_auth.py+22-3
routes/expenses.py+4-4
routes/geography.py+8-4
routes/hr.py+16-14
routes/messages.py+7-7
routes/patient_status.py+4-3
routes/patients.py+284-30
routes/printing.py+356-21
routes/reports.py+95-28
routes/results.py+20-11
routes/tests.py+20-3
routes/users.py+67-2
routes/whatsapp_notifier.pyAdded+266
routes/whatsapp_utils.py+240-157
safe_update.batAdded+166
scripts/gdrive_auth.pyAdded+41
seed_database.sqlite+2-2
set_admin_perm.py+1-1
static/vendor/fonts/Amiri-Bold.ttfAdded+3