Initial commit: ICU Patient Display Management System
@@ -0,0 +1,15 @@
|
||||
# Database Configuration
|
||||
MYSQL_ROOT_PASSWORD=rootpassword
|
||||
MYSQL_DATABASE=icu_db
|
||||
MYSQL_USER=icu_user
|
||||
MYSQL_PASSWORD=icupassword
|
||||
|
||||
# Backend Configuration
|
||||
JWT_SECRET=supersecretkey_change_me_in_production
|
||||
JWT_ALGORITHM=HS256
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=30
|
||||
REFRESH_TOKEN_EXPIRE_DAYS=7
|
||||
API_PORT=8000
|
||||
|
||||
# Frontend Configuration
|
||||
NEXT_PUBLIC_API_URL=http://localhost:8000
|
||||
@@ -0,0 +1,70 @@
|
||||
# Environment variables
|
||||
.env
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
!.env.example
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
venv/
|
||||
ENV/
|
||||
env/
|
||||
backend/venv/
|
||||
*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
# Node / Frontend
|
||||
node_modules/
|
||||
frontend/node_modules/
|
||||
.next/
|
||||
frontend/.next/
|
||||
out/
|
||||
coverage/
|
||||
.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# IDE & OS
|
||||
.vscode/
|
||||
.idea/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,82 @@
|
||||
# ICU Patient Display Management System
|
||||
|
||||
A comprehensive hospital ICU patient display and monitoring management system. This platform manages patient assignments to ICU beds and rooms, and communicates updates in real-time to ESP32-powered e-paper / LCD bedside displays.
|
||||
|
||||
---
|
||||
|
||||
## 🏗 System Architecture
|
||||
|
||||
The project consists of four main components:
|
||||
|
||||
- **Backend (`/backend`)**:
|
||||
- FastAPI / Python asynchronous RESTful API & WebSocket service.
|
||||
- MySQL database with SQLAlchemy / aiomysql ORM.
|
||||
- JWT authentication and role-based access control.
|
||||
- Device hash verification and real-time state synchronization for ESP32 displays.
|
||||
|
||||
- **Frontend (`/frontend`)**:
|
||||
- Next.js (React / TypeScript) web application.
|
||||
- Interactive dashboard for ICU nurses, doctors, and hospital administrators.
|
||||
- Bed & room assignment, patient status updates, and display management.
|
||||
|
||||
- **ESP32 Firmware (`/esp32`)**:
|
||||
- Embedded C++ firmware for ESP32 controllers driving bedside displays.
|
||||
- Real-time display updates via HTTP polling or WebSocket triggers.
|
||||
|
||||
- **Infrastructure (`docker-compose.yml`)**:
|
||||
- Containerized deployment for MySQL 8.0, Backend, Frontend, and Adminer.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Quick Start with Docker
|
||||
|
||||
1. **Clone the repository**:
|
||||
```bash
|
||||
git clone https://gitea.aiindia.ai/Atharv_1705/ICU_Display_Management.git
|
||||
cd ICU_Display_Management
|
||||
```
|
||||
|
||||
2. **Configure environment variables**:
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Edit .env with your specific credentials and network IPs
|
||||
```
|
||||
|
||||
3. **Start all services**:
|
||||
```bash
|
||||
docker-compose up -d --build
|
||||
```
|
||||
|
||||
4. **Access the services**:
|
||||
- **Frontend UI**: [http://localhost:3000](http://localhost:3000)
|
||||
- **Backend API Docs**: [http://localhost:8000/docs](http://localhost:8000/docs)
|
||||
- **Adminer (Database GUI)**: [http://localhost:8080](http://localhost:8080)
|
||||
|
||||
---
|
||||
|
||||
## 🛠 Local Development Setup
|
||||
|
||||
### Backend
|
||||
```bash
|
||||
cd backend
|
||||
python -m venv venv
|
||||
# On Windows:
|
||||
.\venv\Scripts\activate
|
||||
# On Linux/macOS:
|
||||
source venv/bin/activate
|
||||
|
||||
pip install -r requirements.txt
|
||||
uvicorn app.main:app --reload --port 8000
|
||||
```
|
||||
|
||||
### Frontend
|
||||
```bash
|
||||
cd frontend
|
||||
pnpm install # or npm install
|
||||
pnpm dev # or npm run dev
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📄 License
|
||||
Internal project for ICU Patient Display Management.
|
||||
@@ -0,0 +1,18 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y \
|
||||
gcc \
|
||||
default-libmysqlclient-dev \
|
||||
pkg-config \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt .
|
||||
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -0,0 +1,51 @@
|
||||
from datetime import timedelta
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.database import get_db
|
||||
from app.core.security import verify_password, create_access_token
|
||||
from app.schemas.user import Token, UserResponse, UserCreate
|
||||
from app.services.user_service import user_service
|
||||
from app.core.dependencies import get_current_user
|
||||
from app.models.user import User
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
async def login_for_access_token(
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
user = await user_service.get_user_by_email(db, email=form_data.username)
|
||||
if not user or not verify_password(form_data.password, user.hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect email or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
access_token = create_access_token(
|
||||
data={"sub": user.email, "role": user.role.value},
|
||||
expires_delta=access_token_expires
|
||||
)
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
|
||||
@router.post("/register", response_model=UserResponse)
|
||||
async def register(
|
||||
user_in: UserCreate,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
try:
|
||||
from app.models.user import UserRole
|
||||
user_in.role = UserRole.NURSE
|
||||
user = await user_service.create_user(db, user_in=user_in)
|
||||
return user
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
@router.get("/me", response_model=UserResponse)
|
||||
async def get_me(current_user: User = Depends(get_current_user)):
|
||||
return current_user
|
||||
@@ -0,0 +1,110 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from typing import List
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.user import User
|
||||
from app.core.dependencies import get_current_user
|
||||
from app.schemas.display import DisplayCreate, DisplayUpdate, DisplayResponse, ESP32Heartbeat, ESP32HeartbeatResponse, ESP32DisplayData
|
||||
from app.services.display_service import display_service
|
||||
from app.repositories.display_repo import display_repo
|
||||
|
||||
from app.models.room import ICURoom
|
||||
from app.models.patient import Patient
|
||||
from app.models.vitals import Vitals
|
||||
|
||||
router = APIRouter(tags=["displays"])
|
||||
|
||||
@router.get("/api/displays", response_model=List[DisplayResponse])
|
||||
async def read_displays(
|
||||
skip: int = 0, limit: int = 100,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
return await display_repo.get_all(db, skip=skip, limit=limit)
|
||||
|
||||
@router.post("/api/displays", response_model=DisplayResponse)
|
||||
async def register_device(
|
||||
device_in: DisplayCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
return await display_service.register_device(db, obj_in=device_in)
|
||||
|
||||
@router.post("/api/device/heartbeat", response_model=ESP32HeartbeatResponse)
|
||||
async def device_heartbeat(
|
||||
heartbeat: ESP32Heartbeat,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
try:
|
||||
pending_update = await display_service.process_heartbeat(db, heartbeat)
|
||||
return {"pending_update": pending_update}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=401, detail=str(e))
|
||||
|
||||
@router.get("/api/display/{display_id}", response_model=List[ESP32DisplayData])
|
||||
async def get_display_data(
|
||||
display_id: str,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
device = await display_repo.get_by_device_id(db, display_id)
|
||||
if not device:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
|
||||
device.pending_update = False
|
||||
await db.commit()
|
||||
|
||||
# Fetch up to 5 most recently updated patients
|
||||
patient_result = await db.execute(
|
||||
select(Patient).order_by(Patient.last_updated.desc()).limit(5)
|
||||
)
|
||||
patients = patient_result.scalars().all()
|
||||
|
||||
if not patients:
|
||||
return [ESP32DisplayData(
|
||||
patient_name="No Patients Found",
|
||||
status="Empty"
|
||||
)]
|
||||
|
||||
display_data_list = []
|
||||
|
||||
for patient in patients:
|
||||
# Get the Room for this patient
|
||||
room_name = "N/A"
|
||||
if patient.room_id:
|
||||
room_result = await db.execute(select(ICURoom).filter(ICURoom.id == patient.room_id))
|
||||
room = room_result.scalars().first()
|
||||
if room:
|
||||
room_name = room.room_number
|
||||
|
||||
# Get the latest Vitals for this patient
|
||||
vitals_result = await db.execute(
|
||||
select(Vitals).filter(Vitals.patient_id == patient.id).order_by(Vitals.updated_at.desc())
|
||||
)
|
||||
latest_vitals = vitals_result.scalars().first()
|
||||
|
||||
display_data_list.append(
|
||||
ESP32DisplayData(
|
||||
patient_name=patient.patient_name,
|
||||
age=patient.age,
|
||||
gender=patient.gender,
|
||||
blood_group=patient.blood_group,
|
||||
doctor=patient.doctor_name,
|
||||
room=room_name,
|
||||
heart_rate=latest_vitals.heart_rate if latest_vitals else None,
|
||||
spo2=latest_vitals.spo2 if latest_vitals else None,
|
||||
blood_pressure=latest_vitals.blood_pressure if latest_vitals else None,
|
||||
temperature=latest_vitals.temperature if latest_vitals else None,
|
||||
respiration_rate=latest_vitals.respiration_rate if latest_vitals else None,
|
||||
diagnosis=patient.diagnosis,
|
||||
status=patient.status,
|
||||
food_instructions=patient.food_instructions or "No outside food allowed",
|
||||
visiting_rules=patient.visiting_rules or "2 times visits",
|
||||
visiting_hours=patient.visiting_hours or "9 - 11 AM, 4 - 6 PM",
|
||||
restrictions=patient.restrictions or "Dogs are not allowed",
|
||||
last_updated=latest_vitals.updated_at.isoformat() if latest_vitals else patient.last_updated.isoformat() if patient.last_updated else None
|
||||
)
|
||||
)
|
||||
|
||||
return display_data_list
|
||||
@@ -0,0 +1,67 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from typing import List
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.user import User
|
||||
from app.core.dependencies import get_current_user
|
||||
from app.schemas.patient import PatientCreate, PatientUpdate, PatientResponse
|
||||
from app.services.patient_service import patient_service
|
||||
|
||||
router = APIRouter(prefix="/api/patients", tags=["patients"])
|
||||
|
||||
@router.get("", response_model=List[PatientResponse])
|
||||
async def read_patients(
|
||||
skip: int = 0, limit: int = 100,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
return await patient_service.get_patients(db, skip=skip, limit=limit)
|
||||
|
||||
@router.get("/{id}", response_model=PatientResponse)
|
||||
async def read_patient(
|
||||
id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
patient = await patient_service.get_patient(db, id=id)
|
||||
if not patient:
|
||||
raise HTTPException(status_code=404, detail="Patient not found")
|
||||
return patient
|
||||
|
||||
@router.post("", response_model=PatientResponse)
|
||||
async def create_patient(
|
||||
patient_in: PatientCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
try:
|
||||
return await patient_service.create_patient(db, patient_in=patient_in)
|
||||
except IntegrityError:
|
||||
await db.rollback()
|
||||
raise HTTPException(status_code=400, detail="A patient with this MRN already exists.")
|
||||
|
||||
@router.put("/{id}", response_model=PatientResponse)
|
||||
async def update_patient(
|
||||
id: int,
|
||||
patient_in: PatientUpdate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
patient = await patient_service.get_patient(db, id=id)
|
||||
if not patient:
|
||||
raise HTTPException(status_code=404, detail="Patient not found")
|
||||
return await patient_service.update_patient(db, patient=patient, patient_in=patient_in)
|
||||
|
||||
@router.delete("/{id}")
|
||||
async def delete_patient(
|
||||
id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
patient = await patient_service.get_patient(db, id=id)
|
||||
if not patient:
|
||||
raise HTTPException(status_code=404, detail="Patient not found")
|
||||
await patient_service.delete_patient(db, id=id)
|
||||
return {"message": "Patient deleted successfully"}
|
||||
@@ -0,0 +1,38 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from typing import List
|
||||
from sqlalchemy.future import select
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.user import User
|
||||
from app.models.room import ICURoom
|
||||
from app.core.dependencies import get_current_user
|
||||
from pydantic import BaseModel
|
||||
|
||||
router = APIRouter(tags=["rooms"])
|
||||
|
||||
class RoomBase(BaseModel):
|
||||
room_number: str
|
||||
ward: str
|
||||
hospital_id: int | None = None
|
||||
display_id: int | None = None
|
||||
|
||||
class RoomCreate(RoomBase):
|
||||
pass
|
||||
|
||||
class RoomResponse(RoomBase):
|
||||
id: int
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@router.get("/api/rooms", response_model=List[RoomResponse])
|
||||
async def get_rooms(db: AsyncSession = Depends(get_db)):
|
||||
result = await db.execute(select(ICURoom))
|
||||
return result.scalars().all()
|
||||
|
||||
@router.post("/api/rooms", response_model=RoomResponse)
|
||||
async def create_room(room_in: RoomCreate, db: AsyncSession = Depends(get_db)):
|
||||
room = ICURoom(**room_in.model_dump())
|
||||
db.add(room)
|
||||
await db.commit()
|
||||
await db.refresh(room)
|
||||
return room
|
||||
@@ -0,0 +1,44 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from typing import List
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.vitals import Vitals
|
||||
from app.core.dependencies import get_current_user
|
||||
from app.models.user import User
|
||||
|
||||
router = APIRouter(tags=["vitals"])
|
||||
|
||||
class VitalsBase(BaseModel):
|
||||
patient_id: int
|
||||
heart_rate: int | None = None
|
||||
spo2: int | None = None
|
||||
blood_pressure: str | None = None
|
||||
temperature: float | None = None
|
||||
respiration_rate: int | None = None
|
||||
|
||||
class VitalsCreate(VitalsBase):
|
||||
pass
|
||||
|
||||
class VitalsResponse(VitalsBase):
|
||||
id: int
|
||||
updated_at: datetime
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@router.get("/api/vitals/{patient_id}", response_model=List[VitalsResponse])
|
||||
async def get_patient_vitals(patient_id: int, db: AsyncSession = Depends(get_db)):
|
||||
result = await db.execute(
|
||||
select(Vitals).filter(Vitals.patient_id == patient_id).order_by(Vitals.updated_at.desc())
|
||||
)
|
||||
return result.scalars().all()
|
||||
|
||||
@router.post("/api/vitals", response_model=VitalsResponse)
|
||||
async def create_vitals(vitals_in: VitalsCreate, db: AsyncSession = Depends(get_db)):
|
||||
vitals = Vitals(**vitals_in.model_dump())
|
||||
db.add(vitals)
|
||||
await db.commit()
|
||||
await db.refresh(vitals)
|
||||
return vitals
|
||||
@@ -0,0 +1,23 @@
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
class Settings(BaseSettings):
|
||||
MYSQL_USER: str = "icu_user"
|
||||
MYSQL_PASSWORD: str = "icupassword"
|
||||
MYSQL_DATABASE: str = "icu_db"
|
||||
DATABASE_URL: str | None = None
|
||||
|
||||
JWT_SECRET: str = "supersecretkey_change_me_in_production"
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
|
||||
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
|
||||
@property
|
||||
def get_database_url(self) -> str:
|
||||
if self.DATABASE_URL:
|
||||
return self.DATABASE_URL
|
||||
# Fallback to local SQLite so Docker isn't required to run the project
|
||||
return "sqlite+aiosqlite:///./icu_local.db"
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,25 @@
|
||||
from typing import AsyncGenerator
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from app.core.config import settings
|
||||
|
||||
engine = create_async_engine(
|
||||
settings.get_database_url,
|
||||
echo=False,
|
||||
future=True,
|
||||
pool_pre_ping=True
|
||||
)
|
||||
|
||||
AsyncSessionLocal = async_sessionmaker(
|
||||
bind=engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
autocommit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with AsyncSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
await session.close()
|
||||
@@ -0,0 +1,50 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
import jwt
|
||||
from jwt.exceptions import InvalidTokenError
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.database import get_db
|
||||
from app.models.user import User, UserRole
|
||||
from app.services.user_service import user_service
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
|
||||
|
||||
async def get_current_user(
|
||||
token: str = Depends(oauth2_scheme),
|
||||
db: AsyncSession = Depends(get_db)
|
||||
) -> User:
|
||||
credentials_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
if not token:
|
||||
raise credentials_exception
|
||||
|
||||
try:
|
||||
payload = jwt.decode(token, settings.JWT_SECRET, algorithms=[settings.JWT_ALGORITHM])
|
||||
email: str = payload.get("sub")
|
||||
if email is None:
|
||||
raise credentials_exception
|
||||
except InvalidTokenError:
|
||||
raise credentials_exception
|
||||
|
||||
user = await user_service.get_user_by_email(db, email=email)
|
||||
if user is None:
|
||||
raise credentials_exception
|
||||
|
||||
return user
|
||||
|
||||
|
||||
async def get_current_active_admin(current_user: User = Depends(get_current_user)) -> User:
|
||||
if current_user.role != UserRole.ADMIN:
|
||||
raise HTTPException(status_code=403, detail="Not enough privileges")
|
||||
return current_user
|
||||
|
||||
async def get_current_doctor_or_admin(current_user: User = Depends(get_current_user)) -> User:
|
||||
if current_user.role not in [UserRole.ADMIN, UserRole.DOCTOR]:
|
||||
raise HTTPException(status_code=403, detail="Not enough privileges")
|
||||
return current_user
|
||||
@@ -0,0 +1,44 @@
|
||||
from typing import Any, Generic, Type, TypeVar, Optional, List
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from pydantic import BaseModel
|
||||
|
||||
ModelType = TypeVar("ModelType")
|
||||
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
|
||||
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
|
||||
|
||||
class BaseRepository(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
|
||||
def __init__(self, model: Type[ModelType]):
|
||||
self.model = model
|
||||
|
||||
async def get(self, db: AsyncSession, id: Any) -> Optional[ModelType]:
|
||||
result = await db.execute(select(self.model).filter(self.model.id == id))
|
||||
return result.scalars().first()
|
||||
|
||||
async def get_all(self, db: AsyncSession, skip: int = 0, limit: int = 100) -> List[ModelType]:
|
||||
result = await db.execute(select(self.model).offset(skip).limit(limit))
|
||||
return list(result.scalars().all())
|
||||
|
||||
async def create(self, db: AsyncSession, obj_in: CreateSchemaType) -> ModelType:
|
||||
obj_in_data = obj_in.model_dump()
|
||||
db_obj = self.model(**obj_in_data)
|
||||
db.add(db_obj)
|
||||
await db.commit()
|
||||
await db.refresh(db_obj)
|
||||
return db_obj
|
||||
|
||||
async def update(self, db: AsyncSession, db_obj: ModelType, obj_in: UpdateSchemaType) -> ModelType:
|
||||
update_data = obj_in.model_dump(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(db_obj, field, value)
|
||||
db.add(db_obj)
|
||||
await db.commit()
|
||||
await db.refresh(db_obj)
|
||||
return db_obj
|
||||
|
||||
async def remove(self, db: AsyncSession, id: int) -> Optional[ModelType]:
|
||||
obj = await self.get(db=db, id=id)
|
||||
if obj:
|
||||
await db.delete(obj)
|
||||
await db.commit()
|
||||
return obj
|
||||
@@ -0,0 +1,22 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import jwt
|
||||
from passlib.context import CryptContext
|
||||
from app.core.config import settings
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
|
||||
to_encode = data.copy()
|
||||
if expires_delta:
|
||||
expire = datetime.now(timezone.utc) + expires_delta
|
||||
else:
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)
|
||||
return encoded_jwt
|
||||
@@ -0,0 +1,40 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from app.core.config import settings
|
||||
from app.controllers import auth, patient, display, room, vitals
|
||||
from app.core.database import engine
|
||||
from app.models.base import Base
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Create SQLite tables on startup automatically
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
yield
|
||||
|
||||
app = FastAPI(
|
||||
title="ICU Patient Display Management System API",
|
||||
description="Backend API for managing ICU patients and ESP32 displays",
|
||||
version="1.0.0",
|
||||
lifespan=lifespan
|
||||
)
|
||||
|
||||
# CORS Middleware configuration
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(patient.router)
|
||||
app.include_router(display.router)
|
||||
app.include_router(room.router)
|
||||
app.include_router(vitals.router)
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {"message": "Welcome to ICU Patient Display API"}
|
||||
@@ -0,0 +1,8 @@
|
||||
from .base import Base
|
||||
from .user import User
|
||||
from .hospital import Hospital
|
||||
from .room import ICURoom
|
||||
from .display import DisplayDevice
|
||||
from .patient import Patient
|
||||
from .vitals import Vitals
|
||||
from .audit import AuditLog
|
||||
@@ -0,0 +1,12 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime
|
||||
from sqlalchemy.sql import func
|
||||
from .base import Base
|
||||
|
||||
class AuditLog(Base):
|
||||
__tablename__ = "audit_logs"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id"))
|
||||
action = Column(String(255), nullable=False)
|
||||
details = Column(Text)
|
||||
timestamp = Column(DateTime, server_default=func.now())
|
||||
@@ -0,0 +1,3 @@
|
||||
from sqlalchemy.orm import declarative_base
|
||||
|
||||
Base = declarative_base()
|
||||
@@ -0,0 +1,22 @@
|
||||
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey
|
||||
from sqlalchemy.sql import func
|
||||
from .base import Base
|
||||
|
||||
class DisplayDevice(Base):
|
||||
__tablename__ = "display_devices"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
device_id = Column(String(100), unique=True, index=True, nullable=False)
|
||||
device_secret = Column(String(255), nullable=False)
|
||||
name = Column(String(100))
|
||||
firmware_version = Column(String(50))
|
||||
ip_address = Column(String(50))
|
||||
mac_address = Column(String(50))
|
||||
wifi_rssi = Column(Integer)
|
||||
uptime = Column(Integer)
|
||||
battery = Column(Integer)
|
||||
online_status = Column(Boolean, default=False)
|
||||
last_seen = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
||||
pending_update = Column(Boolean, default=False)
|
||||
|
||||
room_id = Column(Integer, ForeignKey("icu_rooms.id"), nullable=True)
|
||||
@@ -0,0 +1,9 @@
|
||||
from sqlalchemy import Column, Integer, String
|
||||
from .base import Base
|
||||
|
||||
class Hospital(Base):
|
||||
__tablename__ = "hospitals"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(255), nullable=False)
|
||||
address = Column(String(500), nullable=True)
|
||||
@@ -0,0 +1,25 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime
|
||||
from sqlalchemy.sql import func
|
||||
from .base import Base
|
||||
|
||||
class Patient(Base):
|
||||
__tablename__ = "patients"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
mrn = Column(String(50), unique=True, index=True, nullable=False)
|
||||
patient_name = Column(String(255), nullable=False)
|
||||
age = Column(Integer)
|
||||
gender = Column(String(50))
|
||||
blood_group = Column(String(10))
|
||||
diagnosis = Column(Text)
|
||||
allergies = Column(Text)
|
||||
doctor_name = Column(String(255))
|
||||
status = Column(String(50), default="Stable")
|
||||
notes = Column(Text)
|
||||
food_instructions = Column(String(255), default="No outside food allowed")
|
||||
visiting_rules = Column(String(255), default="2 times visits")
|
||||
visiting_hours = Column(String(255), default="9 - 11 AM, 4 - 6 PM")
|
||||
restrictions = Column(String(255), default="Dogs are not allowed")
|
||||
last_updated = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
||||
|
||||
room_id = Column(Integer, ForeignKey("icu_rooms.id"))
|
||||
@@ -0,0 +1,13 @@
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
from .base import Base
|
||||
|
||||
class ICURoom(Base):
|
||||
__tablename__ = "icu_rooms"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
room_number = Column(String(50), nullable=False)
|
||||
ward = Column(String(100), nullable=False)
|
||||
|
||||
hospital_id = Column(Integer, ForeignKey("hospitals.id"))
|
||||
display_id = Column(Integer, ForeignKey("display_devices.id"), nullable=True)
|
||||
@@ -0,0 +1,17 @@
|
||||
from sqlalchemy import Column, Integer, String, Enum
|
||||
import enum
|
||||
from .base import Base
|
||||
|
||||
class UserRole(str, enum.Enum):
|
||||
ADMIN = "admin"
|
||||
DOCTOR = "doctor"
|
||||
NURSE = "nurse"
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), nullable=False)
|
||||
email = Column(String(255), unique=True, index=True, nullable=False)
|
||||
hashed_password = Column(String(255), nullable=False)
|
||||
role = Column(Enum(UserRole), default=UserRole.NURSE)
|
||||
@@ -0,0 +1,15 @@
|
||||
from sqlalchemy import Column, Integer, String, Float, ForeignKey, DateTime
|
||||
from sqlalchemy.sql import func
|
||||
from .base import Base
|
||||
|
||||
class Vitals(Base):
|
||||
__tablename__ = "vitals"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
patient_id = Column(Integer, ForeignKey("patients.id"))
|
||||
heart_rate = Column(Integer)
|
||||
spo2 = Column(Integer)
|
||||
blood_pressure = Column(String(20))
|
||||
temperature = Column(Float)
|
||||
respiration_rate = Column(Integer)
|
||||
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
||||
@@ -0,0 +1,13 @@
|
||||
from typing import Optional
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from app.core.repository import BaseRepository
|
||||
from app.models.display import DisplayDevice
|
||||
from app.schemas.display import DisplayCreate, DisplayUpdate
|
||||
|
||||
class DisplayRepository(BaseRepository[DisplayDevice, DisplayCreate, DisplayUpdate]):
|
||||
async def get_by_device_id(self, db: AsyncSession, device_id: str) -> Optional[DisplayDevice]:
|
||||
result = await db.execute(select(DisplayDevice).filter(DisplayDevice.device_id == device_id))
|
||||
return result.scalars().first()
|
||||
|
||||
display_repo = DisplayRepository(DisplayDevice)
|
||||
@@ -0,0 +1,8 @@
|
||||
from app.core.repository import BaseRepository
|
||||
from app.models.patient import Patient
|
||||
from app.schemas.patient import PatientCreate, PatientUpdate
|
||||
|
||||
class PatientRepository(BaseRepository[Patient, PatientCreate, PatientUpdate]):
|
||||
pass
|
||||
|
||||
patient_repo = PatientRepository(Patient)
|
||||
@@ -0,0 +1,13 @@
|
||||
from typing import Optional
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from app.core.repository import BaseRepository
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate, UserBase
|
||||
|
||||
class UserRepository(BaseRepository[User, UserCreate, UserBase]):
|
||||
async def get_by_email(self, db: AsyncSession, email: str) -> Optional[User]:
|
||||
result = await db.execute(select(User).filter(User.email == email))
|
||||
return result.scalars().first()
|
||||
|
||||
user_repo = UserRepository(User)
|
||||
@@ -0,0 +1,61 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
class DisplayBase(BaseModel):
|
||||
name: Optional[str] = None
|
||||
room_id: Optional[int] = None
|
||||
mac_address: Optional[str] = None
|
||||
ip_address: Optional[str] = None
|
||||
|
||||
class DisplayCreate(DisplayBase):
|
||||
device_id: str
|
||||
device_secret: str
|
||||
|
||||
class DisplayUpdate(DisplayBase):
|
||||
pass
|
||||
|
||||
class DisplayResponse(DisplayBase):
|
||||
id: int
|
||||
device_id: str
|
||||
firmware_version: Optional[str] = None
|
||||
wifi_rssi: Optional[int] = None
|
||||
uptime: Optional[int] = None
|
||||
battery: Optional[int] = None
|
||||
online_status: bool
|
||||
last_seen: datetime
|
||||
pending_update: bool
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
class ESP32Heartbeat(BaseModel):
|
||||
device_id: str
|
||||
api_key: str
|
||||
firmware_version: Optional[str] = None
|
||||
ip_address: Optional[str] = None
|
||||
wifi_rssi: Optional[int] = None
|
||||
uptime: Optional[int] = None
|
||||
battery: Optional[int] = None
|
||||
|
||||
class ESP32HeartbeatResponse(BaseModel):
|
||||
pending_update: bool
|
||||
|
||||
class ESP32DisplayData(BaseModel):
|
||||
patient_name: Optional[str] = None
|
||||
age: Optional[int] = None
|
||||
gender: Optional[str] = None
|
||||
blood_group: Optional[str] = None
|
||||
doctor: Optional[str] = None
|
||||
room: Optional[str] = None
|
||||
heart_rate: Optional[int] = None
|
||||
spo2: Optional[int] = None
|
||||
blood_pressure: Optional[str] = None
|
||||
temperature: Optional[float] = None
|
||||
respiration_rate: Optional[int] = None
|
||||
diagnosis: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
food_instructions: Optional[str] = None
|
||||
visiting_rules: Optional[str] = None
|
||||
visiting_hours: Optional[str] = None
|
||||
restrictions: Optional[str] = None
|
||||
last_updated: Optional[str] = None
|
||||
@@ -0,0 +1,45 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
class PatientBase(BaseModel):
|
||||
mrn: str
|
||||
patient_name: str
|
||||
age: Optional[int] = None
|
||||
gender: Optional[str] = None
|
||||
blood_group: Optional[str] = None
|
||||
diagnosis: Optional[str] = None
|
||||
allergies: Optional[str] = None
|
||||
doctor_name: Optional[str] = None
|
||||
status: Optional[str] = "Stable"
|
||||
notes: Optional[str] = None
|
||||
food_instructions: Optional[str] = "No outside food allowed"
|
||||
visiting_rules: Optional[str] = "2 times visits"
|
||||
visiting_hours: Optional[str] = "9 - 11 AM, 4 - 6 PM"
|
||||
restrictions: Optional[str] = "Dogs are not allowed"
|
||||
room_id: Optional[int] = None
|
||||
|
||||
class PatientCreate(PatientBase):
|
||||
pass
|
||||
|
||||
class PatientUpdate(BaseModel):
|
||||
patient_name: Optional[str] = None
|
||||
age: Optional[int] = None
|
||||
gender: Optional[str] = None
|
||||
blood_group: Optional[str] = None
|
||||
diagnosis: Optional[str] = None
|
||||
allergies: Optional[str] = None
|
||||
doctor_name: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
notes: Optional[str] = None
|
||||
food_instructions: Optional[str] = None
|
||||
visiting_rules: Optional[str] = None
|
||||
visiting_hours: Optional[str] = None
|
||||
restrictions: Optional[str] = None
|
||||
room_id: Optional[int] = None
|
||||
|
||||
class PatientResponse(PatientBase):
|
||||
id: int
|
||||
last_updated: datetime
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
@@ -0,0 +1,19 @@
|
||||
from pydantic import BaseModel, EmailStr
|
||||
from app.models.user import UserRole
|
||||
|
||||
class UserBase(BaseModel):
|
||||
name: str
|
||||
email: EmailStr
|
||||
role: UserRole = UserRole.NURSE
|
||||
|
||||
class UserCreate(UserBase):
|
||||
password: str
|
||||
|
||||
class UserResponse(UserBase):
|
||||
id: int
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
class Token(BaseModel):
|
||||
access_token: str
|
||||
token_type: str
|
||||
@@ -0,0 +1,47 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import List
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.repositories.display_repo import display_repo
|
||||
from app.models.display import DisplayDevice
|
||||
from app.schemas.display import DisplayCreate, DisplayUpdate, ESP32Heartbeat
|
||||
from app.core.security import get_password_hash, verify_password
|
||||
|
||||
class DisplayService:
|
||||
async def register_device(self, db: AsyncSession, obj_in: DisplayCreate) -> DisplayDevice:
|
||||
hashed_secret = get_password_hash(obj_in.device_secret)
|
||||
obj_in.device_secret = hashed_secret
|
||||
return await display_repo.create(db, obj_in=obj_in)
|
||||
|
||||
async def process_heartbeat(self, db: AsyncSession, heartbeat: ESP32Heartbeat) -> bool:
|
||||
device = await display_repo.get_by_device_id(db, heartbeat.device_id)
|
||||
print(f"DEBUG heartbeat: device_id={heartbeat.device_id}, api_key={heartbeat.api_key}")
|
||||
if not device:
|
||||
print(f"DEBUG: device not found in db for id {heartbeat.device_id}")
|
||||
raise ValueError("Unauthorized device")
|
||||
|
||||
is_valid = verify_password(heartbeat.api_key, device.device_secret)
|
||||
print(f"DEBUG: verify_password={is_valid}")
|
||||
|
||||
if not is_valid:
|
||||
raise ValueError("Unauthorized device")
|
||||
|
||||
update_data = DisplayUpdate(
|
||||
ip_address=heartbeat.ip_address,
|
||||
firmware_version=heartbeat.firmware_version,
|
||||
wifi_rssi=heartbeat.wifi_rssi,
|
||||
uptime=heartbeat.uptime,
|
||||
battery=heartbeat.battery,
|
||||
)
|
||||
device = await display_repo.update(db, device, update_data)
|
||||
device.online_status = True
|
||||
device.last_seen = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
|
||||
return device.pending_update
|
||||
|
||||
async def trigger_display_update_for_room(self, db: AsyncSession, room_id: int):
|
||||
from sqlalchemy import text
|
||||
await db.execute(text("UPDATE display_devices SET pending_update = 1 WHERE room_id = :room_id"), {"room_id": room_id})
|
||||
await db.commit()
|
||||
|
||||
display_service = DisplayService()
|
||||
@@ -0,0 +1,45 @@
|
||||
from typing import List
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.repositories.patient_repo import patient_repo
|
||||
from app.models.patient import Patient
|
||||
from app.schemas.patient import PatientCreate, PatientUpdate
|
||||
|
||||
class PatientService:
|
||||
async def get_patient(self, db: AsyncSession, id: int) -> Patient:
|
||||
return await patient_repo.get(db, id=id)
|
||||
|
||||
async def get_patients(self, db: AsyncSession, skip: int = 0, limit: int = 100) -> List[Patient]:
|
||||
return await patient_repo.get_all(db, skip=skip, limit=limit)
|
||||
|
||||
async def create_patient(self, db: AsyncSession, patient_in: PatientCreate) -> Patient:
|
||||
patient = await patient_repo.create(db, obj_in=patient_in)
|
||||
if patient.room_id:
|
||||
from app.services.display_service import display_service
|
||||
await display_service.trigger_display_update_for_room(db, patient.room_id)
|
||||
return patient
|
||||
|
||||
async def update_patient(self, db: AsyncSession, patient: Patient, patient_in: PatientUpdate) -> Patient:
|
||||
old_room_id = patient.room_id
|
||||
patient = await patient_repo.update(db, db_obj=patient, obj_in=patient_in)
|
||||
|
||||
from app.services.display_service import display_service
|
||||
if patient.room_id:
|
||||
await display_service.trigger_display_update_for_room(db, patient.room_id)
|
||||
if old_room_id and old_room_id != patient.room_id:
|
||||
await display_service.trigger_display_update_for_room(db, old_room_id)
|
||||
|
||||
return patient
|
||||
|
||||
async def delete_patient(self, db: AsyncSession, id: int) -> Patient:
|
||||
patient = await patient_repo.get(db, id=id)
|
||||
room_id = patient.room_id if patient else None
|
||||
|
||||
deleted_patient = await patient_repo.remove(db, id=id)
|
||||
|
||||
if room_id:
|
||||
from app.services.display_service import display_service
|
||||
await display_service.trigger_display_update_for_room(db, room_id)
|
||||
|
||||
return deleted_patient
|
||||
|
||||
patient_service = PatientService()
|
||||
@@ -0,0 +1,30 @@
|
||||
from typing import Optional
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.repositories.user_repo import user_repo
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate
|
||||
from app.core.security import get_password_hash
|
||||
|
||||
class UserService:
|
||||
async def create_user(self, db: AsyncSession, user_in: UserCreate) -> User:
|
||||
user = await user_repo.get_by_email(db, email=user_in.email)
|
||||
if user:
|
||||
raise ValueError("Email already registered")
|
||||
|
||||
hashed_password = get_password_hash(user_in.password)
|
||||
|
||||
db_obj = User(
|
||||
name=user_in.name,
|
||||
email=user_in.email,
|
||||
role=user_in.role,
|
||||
hashed_password=hashed_password
|
||||
)
|
||||
db.add(db_obj)
|
||||
await db.commit()
|
||||
await db.refresh(db_obj)
|
||||
return db_obj
|
||||
|
||||
async def get_user_by_email(self, db: AsyncSession, email: str) -> Optional[User]:
|
||||
return await user_repo.get_by_email(db, email=email)
|
||||
|
||||
user_service = UserService()
|
||||
@@ -0,0 +1,36 @@
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect("icu_local.db")
|
||||
c = conn.cursor()
|
||||
|
||||
# Check rooms
|
||||
c.execute("SELECT * FROM icu_rooms")
|
||||
rooms = c.fetchall()
|
||||
c.execute("PRAGMA table_info(icu_rooms)")
|
||||
room_cols = [col[1] for col in c.fetchall()]
|
||||
print("=== Rooms ===")
|
||||
for r in rooms:
|
||||
print(dict(zip(room_cols, r)))
|
||||
|
||||
# Check displays
|
||||
c.execute("SELECT * FROM display_devices")
|
||||
devices = c.fetchall()
|
||||
c.execute("PRAGMA table_info(display_devices)")
|
||||
dev_cols = [col[1] for col in c.fetchall()]
|
||||
print("\n=== Displays ===")
|
||||
for d in devices:
|
||||
print(dict(zip(dev_cols, d)))
|
||||
|
||||
# Assign room_id=1 to display id=1 if not already assigned
|
||||
if rooms and devices:
|
||||
room_id = rooms[0][0] # first room's id
|
||||
device_id = devices[0][0] # first device's id
|
||||
c.execute("UPDATE display_devices SET room_id = ? WHERE id = ?", (room_id, device_id))
|
||||
conn.commit()
|
||||
print(f"\nAssigned room id={room_id} to display id={device_id}")
|
||||
|
||||
# Verify
|
||||
c.execute("SELECT id, device_id, room_id FROM display_devices WHERE id = ?", (device_id,))
|
||||
print("Updated display:", c.fetchone())
|
||||
|
||||
conn.close()
|
||||
@@ -0,0 +1,25 @@
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect("icu_local.db")
|
||||
c = conn.cursor()
|
||||
|
||||
# List tables
|
||||
c.execute("SELECT name FROM sqlite_master WHERE type='table'")
|
||||
print("Tables:", [r[0] for r in c.fetchall()])
|
||||
|
||||
# Check display_devices
|
||||
try:
|
||||
c.execute("SELECT * FROM display_devices")
|
||||
rows = c.fetchall()
|
||||
if rows:
|
||||
c.execute("PRAGMA table_info(display_devices)")
|
||||
cols = [col[1] for col in c.fetchall()]
|
||||
print("Columns:", cols)
|
||||
for row in rows:
|
||||
print(dict(zip(cols, row)))
|
||||
else:
|
||||
print("No devices registered yet!")
|
||||
except Exception as e:
|
||||
print("Error:", e)
|
||||
|
||||
conn.close()
|
||||
@@ -0,0 +1,15 @@
|
||||
fastapi
|
||||
uvicorn[standard]
|
||||
sqlalchemy[asyncio]
|
||||
alembic
|
||||
aiomysql
|
||||
aiosqlite
|
||||
pydantic
|
||||
pydantic[email]
|
||||
pydantic-settings
|
||||
pyjwt
|
||||
passlib[bcrypt]
|
||||
bcrypt<4.0.0
|
||||
argon2-cffi
|
||||
python-multipart
|
||||
pytest
|
||||
@@ -0,0 +1,21 @@
|
||||
import asyncio
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
from app.models.user import User, UserRole
|
||||
from app.core.security import get_password_hash
|
||||
|
||||
engine = create_async_engine("sqlite+aiosqlite:///./icu_local.db", echo=False)
|
||||
AsyncSessionLocal = async_sessionmaker(bind=engine, expire_on_commit=False)
|
||||
|
||||
async def seed_user():
|
||||
async with AsyncSessionLocal() as session:
|
||||
user = User(
|
||||
name="Demo Nurse",
|
||||
email="nurse@hospital.com",
|
||||
hashed_password=get_password_hash("password123"),
|
||||
role=UserRole.NURSE
|
||||
)
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
print("Demo user created successfully.")
|
||||
|
||||
asyncio.run(seed_user())
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
Seed script to register the ESP32 display device in the database.
|
||||
Run this once to create the device entry that the ESP32 heartbeat authenticates against.
|
||||
"""
|
||||
import asyncio
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
from app.models.display import DisplayDevice
|
||||
from app.core.security import get_password_hash
|
||||
|
||||
engine = create_async_engine("sqlite+aiosqlite:///./icu_local.db", echo=False)
|
||||
AsyncSessionLocal = async_sessionmaker(bind=engine, expire_on_commit=False)
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# Set your device credentials here.
|
||||
# The DEVICE_SECRET below is what the ESP32
|
||||
# must send as "api_key" in its heartbeat JSON.
|
||||
# ──────────────────────────────────────────────
|
||||
DEVICE_ID = "ESP32_WAVESHARE_1"
|
||||
DEVICE_SECRET = "esp32_secret_key_2024" # <-- Put this in your ESP32 code as api_key
|
||||
DEVICE_NAME = "ICU Bedside Display 1"
|
||||
|
||||
async def seed_device():
|
||||
async with AsyncSessionLocal() as session:
|
||||
# Check if device already exists
|
||||
from sqlalchemy.future import select
|
||||
result = await session.execute(
|
||||
select(DisplayDevice).filter(DisplayDevice.device_id == DEVICE_ID)
|
||||
)
|
||||
existing = result.scalars().first()
|
||||
|
||||
if existing:
|
||||
print(f"Device '{DEVICE_ID}' already exists (id={existing.id}). Skipping.")
|
||||
return
|
||||
|
||||
device = DisplayDevice(
|
||||
device_id=DEVICE_ID,
|
||||
device_secret=get_password_hash(DEVICE_SECRET),
|
||||
name=DEVICE_NAME,
|
||||
online_status=False,
|
||||
pending_update=False,
|
||||
)
|
||||
session.add(device)
|
||||
await session.commit()
|
||||
print(f"✅ Device registered successfully!")
|
||||
print(f" Device ID: {DEVICE_ID}")
|
||||
print(f" API Key: {DEVICE_SECRET}")
|
||||
print(f" Name: {DEVICE_NAME}")
|
||||
print()
|
||||
print(f"Now update your ESP32 code with:")
|
||||
print(f' const char* device_id = "{DEVICE_ID}";')
|
||||
print(f' const char* api_key = "{DEVICE_SECRET}";')
|
||||
|
||||
asyncio.run(seed_device())
|
||||
@@ -0,0 +1,11 @@
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect("icu_local.db")
|
||||
c = conn.cursor()
|
||||
|
||||
# Set pending_update to 1 for all displays to force them to refresh
|
||||
c.execute("UPDATE display_devices SET pending_update = 1")
|
||||
conn.commit()
|
||||
|
||||
print("Set pending_update = 1 for all displays. The ESP32 should pick this up on its next heartbeat!")
|
||||
conn.close()
|
||||
@@ -0,0 +1,7 @@
|
||||
from app.core.security import verify_password
|
||||
|
||||
secret = "esp32_secret_key_2024"
|
||||
stored_hash = "$2b$12$2dm4v2h2GyzL7MrWG9zOWuMmcUoJgkIWZi34xgv3zfTpiGe2ajJEm"
|
||||
|
||||
result = verify_password(secret, stored_hash)
|
||||
print(f"Password verification: {result}")
|
||||
@@ -0,0 +1,68 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
db:
|
||||
image: mysql:8.0
|
||||
container_name: icu_db
|
||||
restart: always
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-rootpassword}
|
||||
MYSQL_DATABASE: ${MYSQL_DATABASE:-icu_db}
|
||||
MYSQL_USER: ${MYSQL_USER:-icu_user}
|
||||
MYSQL_PASSWORD: ${MYSQL_PASSWORD:-icupassword}
|
||||
ports:
|
||||
- "3306:3306"
|
||||
volumes:
|
||||
- db_data:/var/lib/mysql
|
||||
networks:
|
||||
- icu_network
|
||||
|
||||
adminer:
|
||||
image: adminer
|
||||
container_name: icu_adminer
|
||||
restart: always
|
||||
ports:
|
||||
- "8080:8080"
|
||||
depends_on:
|
||||
- db
|
||||
networks:
|
||||
- icu_network
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: icu_backend
|
||||
restart: always
|
||||
ports:
|
||||
- "8000:8000"
|
||||
env_file:
|
||||
- .env
|
||||
environment:
|
||||
- DATABASE_URL=mysql+aiomysql://${MYSQL_USER:-icu_user}:${MYSQL_PASSWORD:-icupassword}@db:3306/${MYSQL_DATABASE:-icu_db}
|
||||
depends_on:
|
||||
- db
|
||||
networks:
|
||||
- icu_network
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
container_name: icu_frontend
|
||||
restart: always
|
||||
ports:
|
||||
- "3000:3000"
|
||||
env_file:
|
||||
- .env
|
||||
depends_on:
|
||||
- backend
|
||||
networks:
|
||||
- icu_network
|
||||
|
||||
volumes:
|
||||
db_data:
|
||||
|
||||
networks:
|
||||
icu_network:
|
||||
driver: bridge
|
||||
@@ -0,0 +1 @@
|
||||
# Keep docs folder tracked in git
|
||||
|
After Width: | Height: | Size: 43 KiB |
@@ -0,0 +1,43 @@
|
||||
// DMH Logo bitmap: 64x66 pixels
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
|
||||
#define LOGO_DMH_WIDTH 64
|
||||
#define LOGO_DMH_HEIGHT 66
|
||||
|
||||
const unsigned char logo_dmh[] PROGMEM = {
|
||||
0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xC0, 0x60, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x18, 0xC0, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0xC0, 0xC0, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x61, 0xC1, 0xC0, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x41, 0xC3, 0xC0, 0x1C, 0x00, 0x00,
|
||||
0x0F, 0xF0, 0x61, 0x66, 0xC0, 0x3F, 0x00, 0x00, 0x18, 0x78, 0x61, 0x65, 0x80, 0x61, 0x80, 0x00,
|
||||
0x30, 0x1C, 0x03, 0x69, 0x80, 0xC3, 0x80, 0x00, 0x20, 0x0C, 0x02, 0x79, 0x80, 0x47, 0x03, 0xE0,
|
||||
0x58, 0x0E, 0x06, 0x71, 0x80, 0x06, 0x07, 0x30, 0x5C, 0x06, 0x04, 0x63, 0x00, 0x0C, 0x0C, 0x00,
|
||||
0xCC, 0x06, 0x0C, 0x63, 0x00, 0x1F, 0x18, 0x00, 0x86, 0x06, 0x78, 0x43, 0x00, 0x31, 0xF8, 0x00,
|
||||
0x87, 0x06, 0xF0, 0x03, 0xC0, 0x70, 0x70, 0x00, 0x83, 0x04, 0x00, 0x00, 0x18, 0xE0, 0x60, 0x00,
|
||||
0xC1, 0x8C, 0x00, 0x00, 0x0D, 0x80, 0xC0, 0x00, 0x41, 0xC8, 0x00, 0x00, 0x07, 0x01, 0x80, 0x00,
|
||||
0x60, 0xD8, 0x00, 0x00, 0x00, 0x03, 0x80, 0x00, 0x3C, 0xE0, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00,
|
||||
0x1C, 0xC0, 0x1F, 0xFF, 0xE0, 0x03, 0x00, 0x00, 0x00, 0x80, 0x3F, 0xFF, 0xE0, 0x00, 0x80, 0x00,
|
||||
0x00, 0x00, 0x3F, 0xFF, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFF, 0xE0, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x3F, 0xFF, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFF, 0xE0, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x3F, 0xFF, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFF, 0xE0, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x3F, 0xFF, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFF, 0xE0, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x3F, 0xFF, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFF, 0xE0, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x3F, 0xFF, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFF, 0xE0, 0x00, 0x00, 0x00,
|
||||
0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
|
||||
0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
|
||||
0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
|
||||
0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
|
||||
0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
|
||||
0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
|
||||
0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
|
||||
0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
|
||||
0x00, 0x00, 0x38, 0x00, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x70, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x38, 0x00, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x70, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x38, 0x00, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x70, 0x00, 0x00, 0x00,
|
||||
0x00, 0x01, 0xB8, 0x02, 0x70, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF8, 0x1F, 0xF0, 0x00, 0x00, 0x00,
|
||||
0x00, 0x1F, 0xF8, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF8, 0x7F, 0xF0, 0x00, 0x00, 0x00,
|
||||
0x00, 0x7F, 0xF8, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xF9, 0xFF, 0xF0, 0x00, 0x00, 0x00,
|
||||
0x00, 0x7F, 0xF1, 0xFF, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xF0, 0xFF, 0xC0, 0x00, 0x00, 0x00,
|
||||
0x00, 0x3F, 0xE0, 0xFF, 0x80, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00,
|
||||
|
||||
};
|
||||
@@ -0,0 +1,381 @@
|
||||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <HTTPClient.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <SPI.h>
|
||||
#include <GxEPD2_BW.h>
|
||||
#include <GxEPD2_3C.h>
|
||||
#include <Fonts/FreeSansBold9pt7b.h>
|
||||
#include <Fonts/FreeSansBold12pt7b.h>
|
||||
#include <Fonts/FreeSansBold18pt7b.h>
|
||||
|
||||
#include "logo_dmh.h"
|
||||
#include "hospital_bg.h"
|
||||
|
||||
// Set to true to display the hospital building photo in the background, or false for clean white
|
||||
#define SHOW_BACKGROUND_IMAGE true
|
||||
const char* ssid = "Prajwal";
|
||||
const char* password = "";
|
||||
|
||||
const char* api_base_url = "http://10.25.4.115:8000";
|
||||
const char* device_id = "ICU_01";
|
||||
const char* api_key = "esp32_secret_key_2024";
|
||||
|
||||
// --- Pin Definitions ---
|
||||
#define PIN_CS 5
|
||||
#define PIN_DC 17
|
||||
#define PIN_RST 16
|
||||
#define PIN_BUSY 4
|
||||
#define PIN_PWR 2
|
||||
|
||||
// ==========================================
|
||||
// DISPLAY DRIVER SETUP
|
||||
// ==========================================
|
||||
// Driver: GxEPD2_750c_Z08 matching the '075RW-Z08-C2' sticker on the panel.
|
||||
// BUSY pin set to -1 to BYPASS the hardware BUSY signal.
|
||||
// GPIO 4 floats HIGH, making the library think the screen is always ready
|
||||
// (completing the refresh in 2ms). With -1, the library uses correct fixed
|
||||
// delays giving the panel the full ~20-second refresh cycle it physically needs.
|
||||
GxEPD2_3C<GxEPD2_750c_Z08, GxEPD2_750c_Z08::HEIGHT / 8> display(GxEPD2_750c_Z08(PIN_CS, PIN_DC, PIN_RST, PIN_BUSY));
|
||||
|
||||
bool displayDrawn = false;
|
||||
unsigned long lastUpdate = 0;
|
||||
const unsigned long updateInterval = 10000; // Poll heartbeat every 10 seconds
|
||||
|
||||
// ==========================================
|
||||
// HELPER FUNCTIONS
|
||||
// ==========================================
|
||||
|
||||
void connectWiFi() {
|
||||
Serial.print("Connecting to WiFi");
|
||||
WiFi.begin(ssid, password);
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(500);
|
||||
Serial.print(".");
|
||||
}
|
||||
Serial.println("\nConnected! IP: " + WiFi.localIP().toString());
|
||||
}
|
||||
|
||||
// Returns "--" for null JSON values, otherwise the string value.
|
||||
String safeStr(JsonVariant v) {
|
||||
if (v.isNull()) return "--";
|
||||
return v.as<String>();
|
||||
}
|
||||
|
||||
// ArduinoJson v7: use JsonDocument (DynamicJsonDocument removed in v7)
|
||||
void drawDisplay(JsonDocument& data) {
|
||||
display.setFullWindow();
|
||||
|
||||
display.firstPage();
|
||||
do {
|
||||
display.fillScreen(GxEPD_WHITE);
|
||||
|
||||
#if SHOW_BACKGROUND_IMAGE
|
||||
// ==========================================
|
||||
// 0. HOSPITAL BUILDING BACKGROUND
|
||||
// ==========================================
|
||||
display.drawBitmap(0, 0, hospital_bg, BG_WIDTH, BG_HEIGHT, GxEPD_BLACK);
|
||||
#endif
|
||||
|
||||
// ==========================================
|
||||
// 1. TOP HEADER BAR (y: 0 to 65)
|
||||
// ==========================================
|
||||
display.fillRect(0, 0, 800, 65, GxEPD_WHITE);
|
||||
display.drawRect(0, 0, 800, 65, GxEPD_BLACK);
|
||||
display.drawRect(0, 0, 800, 64, GxEPD_BLACK);
|
||||
|
||||
// Draw DMH Logo in RED
|
||||
display.drawBitmap(12, 0, logo_dmh, LOGO_DMH_WIDTH, LOGO_DMH_HEIGHT, GxEPD_RED);
|
||||
|
||||
display.setTextColor(GxEPD_BLACK);
|
||||
display.setFont(&FreeSansBold12pt7b);
|
||||
display.setCursor(85, 28);
|
||||
display.print("DEENANATH MANGESHKAR HOSPITAL");
|
||||
|
||||
display.setFont(&FreeSansBold9pt7b);
|
||||
display.setCursor(85, 52);
|
||||
display.print("ICU PATIENT WARD");
|
||||
|
||||
String roomStr = "ROOM: " + safeStr(data[0]["room"]);
|
||||
display.setFont(&FreeSansBold12pt7b);
|
||||
display.setCursor(620, 38);
|
||||
display.print(roomStr);
|
||||
|
||||
// ==========================================
|
||||
// 2. PATIENT DEMOGRAPHICS CARD (y: 75 to 165)
|
||||
// ==========================================
|
||||
display.fillRect(15, 75, 770, 90, GxEPD_WHITE);
|
||||
display.drawRect(15, 75, 770, 90, GxEPD_BLACK);
|
||||
|
||||
// Patient Name
|
||||
display.setTextColor(GxEPD_BLACK);
|
||||
display.setFont(&FreeSansBold18pt7b);
|
||||
display.setCursor(30, 112);
|
||||
display.print(safeStr(data[0]["patient_name"]));
|
||||
|
||||
// Patient Status (KEPT AS IT IS!)
|
||||
String statusStr = data[0]["status"].as<String>();
|
||||
if (statusStr.length() == 0 || statusStr == "null") statusStr = "Stable";
|
||||
uint16_t statusColor = (statusStr.equalsIgnoreCase("Critical")) ? GxEPD_RED : GxEPD_BLACK;
|
||||
display.setFont(&FreeSansBold12pt7b);
|
||||
display.setTextColor(statusColor);
|
||||
display.setCursor(540, 112);
|
||||
display.print("STATUS: " + statusStr);
|
||||
|
||||
// Demographics Sub-Row with Age / Gender, Doctor, Blood (KEPT AS IT IS!)
|
||||
display.setFont(&FreeSansBold9pt7b);
|
||||
display.setTextColor(GxEPD_BLACK);
|
||||
display.setCursor(30, 145);
|
||||
display.print("Age / Gender: " + safeStr(data[0]["age"]) + " / " + safeStr(data[0]["gender"]));
|
||||
|
||||
display.setCursor(320, 145);
|
||||
display.print("Doctor: " + safeStr(data[0]["doctor"]));
|
||||
|
||||
display.setCursor(620, 145);
|
||||
display.print("Blood: " + safeStr(data[0]["blood_group"]));
|
||||
|
||||
// ==========================================
|
||||
// 3. DIETARY / FOOD POLICY (y: 175 to 230)
|
||||
// ==========================================
|
||||
display.fillRect(15, 175, 770, 55, GxEPD_WHITE);
|
||||
display.drawRect(15, 175, 770, 55, GxEPD_BLACK);
|
||||
|
||||
display.setFont(&FreeSansBold9pt7b);
|
||||
display.setTextColor(GxEPD_BLACK);
|
||||
display.setCursor(30, 195);
|
||||
display.print("DIETARY / FOOD POLICY:");
|
||||
|
||||
String foodInstr = safeStr(data[0]["food_instructions"]);
|
||||
if (foodInstr == "--" || foodInstr.length() == 0) foodInstr = "No outside food allowed";
|
||||
display.setFont(&FreeSansBold12pt7b);
|
||||
display.setTextColor(GxEPD_RED);
|
||||
display.setCursor(240, 215);
|
||||
display.print(foodInstr);
|
||||
|
||||
// ==========================================
|
||||
// 4. MIDDLE PANELS: LEFT (Diagnosis & Restrictions) & RIGHT (Visiting Hours)
|
||||
// ==========================================
|
||||
// LEFT COLUMN (x: 15 to 390, width: 375, y: 240 to 395)
|
||||
display.fillRect(15, 240, 375, 155, GxEPD_WHITE);
|
||||
display.drawRect(15, 240, 375, 155, GxEPD_BLACK);
|
||||
|
||||
// Primary Diagnosis
|
||||
display.setFont(&FreeSansBold9pt7b);
|
||||
display.setTextColor(GxEPD_BLACK);
|
||||
display.setCursor(28, 260);
|
||||
display.print("PRIMARY DIAGNOSIS");
|
||||
|
||||
String diagVal = safeStr(data[0]["diagnosis"]);
|
||||
if (diagVal == "--" || diagVal.length() == 0) diagVal = "Fever";
|
||||
display.drawRect(28, 270, 345, 38, GxEPD_BLACK);
|
||||
display.setFont(&FreeSansBold12pt7b);
|
||||
display.setCursor(45, 296);
|
||||
display.print(diagVal);
|
||||
|
||||
// Restrictions (Not Allowed)
|
||||
display.setFont(&FreeSansBold9pt7b);
|
||||
display.setCursor(28, 330);
|
||||
display.print("RESTRICTIONS (NOT ALLOWED)");
|
||||
|
||||
String restrictVal = safeStr(data[0]["restrictions"]);
|
||||
if (restrictVal == "--" || restrictVal.length() == 0) restrictVal = "Dogs are not allowed";
|
||||
display.drawRect(28, 340, 345, 38, GxEPD_RED);
|
||||
display.setFont(&FreeSansBold12pt7b);
|
||||
display.setTextColor(GxEPD_RED);
|
||||
display.setCursor(45, 366);
|
||||
display.print(restrictVal);
|
||||
|
||||
// RIGHT COLUMN (x: 405 to 785, width: 380, y: 240 to 395)
|
||||
display.fillRect(405, 240, 380, 155, GxEPD_WHITE);
|
||||
display.drawRect(405, 240, 380, 155, GxEPD_BLACK);
|
||||
|
||||
display.setFont(&FreeSansBold9pt7b);
|
||||
display.setTextColor(GxEPD_BLACK);
|
||||
display.setCursor(420, 260);
|
||||
display.print("VISITING POLICY & HOURS");
|
||||
|
||||
String visitRules = safeStr(data[0]["visiting_rules"]);
|
||||
if (visitRules == "--" || visitRules.length() == 0) visitRules = "2 times visits";
|
||||
display.drawRect(420, 270, 350, 35, GxEPD_RED);
|
||||
display.setFont(&FreeSansBold12pt7b);
|
||||
display.setTextColor(GxEPD_RED);
|
||||
display.setCursor(440, 295);
|
||||
display.print(visitRules);
|
||||
|
||||
// ==========================================
|
||||
// Dynamic Visiting Hours Parsing
|
||||
// ==========================================
|
||||
String visitHours = safeStr(data[0]["visiting_hours"]);
|
||||
String morningHours = "9:00 - 11:00 AM";
|
||||
String eveningHours = "4:00 - 6:00 PM";
|
||||
|
||||
if (visitHours != "--" && visitHours.length() > 0) {
|
||||
int commaIdx = visitHours.indexOf(',');
|
||||
if (commaIdx < 0) commaIdx = visitHours.indexOf(';');
|
||||
if (commaIdx > 0) {
|
||||
morningHours = visitHours.substring(0, commaIdx);
|
||||
morningHours.trim();
|
||||
eveningHours = visitHours.substring(commaIdx + 1);
|
||||
eveningHours.trim();
|
||||
} else {
|
||||
morningHours = visitHours;
|
||||
eveningHours = "";
|
||||
}
|
||||
}
|
||||
|
||||
display.setTextColor(GxEPD_BLACK);
|
||||
if (morningHours.length() > 22 || eveningHours.length() > 22) {
|
||||
display.setFont(&FreeSansBold9pt7b);
|
||||
} else {
|
||||
display.setFont(&FreeSansBold12pt7b);
|
||||
}
|
||||
|
||||
display.setCursor(425, 335);
|
||||
if (eveningHours.length() > 0) {
|
||||
display.print("Morning : " + morningHours);
|
||||
display.setCursor(425, 370);
|
||||
display.print("Evening : " + eveningHours);
|
||||
} else {
|
||||
display.print("Hours : " + morningHours);
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 5. FOOTER (y: 405 to 450)
|
||||
// ==========================================
|
||||
display.fillRect(15, 405, 770, 45, GxEPD_WHITE);
|
||||
display.drawRect(15, 405, 770, 45, GxEPD_BLACK);
|
||||
|
||||
display.setFont(&FreeSansBold9pt7b);
|
||||
display.setTextColor(GxEPD_BLACK);
|
||||
display.setCursor(30, 432);
|
||||
display.print("Device: " + String(device_id));
|
||||
|
||||
display.setCursor(420, 432);
|
||||
display.print("Last Updated: " + safeStr(data[0]["last_updated"]));
|
||||
|
||||
} while (display.nextPage());
|
||||
|
||||
Serial.println("Display refresh finished.");
|
||||
}
|
||||
|
||||
void fetchDisplayData() {
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
HTTPClient http;
|
||||
String url = String(api_base_url) + "/api/display/" + String(device_id);
|
||||
Serial.println("Fetching data from: " + url);
|
||||
|
||||
http.setTimeout(10000); // 10s timeout to prevent read errors
|
||||
http.begin(url);
|
||||
int httpResponseCode = http.GET();
|
||||
|
||||
if (httpResponseCode == 200) {
|
||||
String payload = http.getString();
|
||||
Serial.println("Received Payload: " + payload);
|
||||
|
||||
JsonDocument doc; // ArduinoJson v7 - no size needed
|
||||
DeserializationError error = deserializeJson(doc, payload);
|
||||
|
||||
if (!error) {
|
||||
Serial.println("Data parsed. Pausing to let voltage stabilize...");
|
||||
delay(1500); // Let USB voltage recover from WiFi spike
|
||||
WiFi.setSleep(true);
|
||||
drawDisplay(doc);
|
||||
displayDrawn = true;
|
||||
WiFi.setSleep(false);
|
||||
} else {
|
||||
Serial.println("Failed to parse JSON!");
|
||||
}
|
||||
} else {
|
||||
Serial.print("Error fetching data, HTTP code: ");
|
||||
Serial.println(httpResponseCode);
|
||||
}
|
||||
http.end();
|
||||
} else {
|
||||
Serial.println("WiFi not connected!");
|
||||
}
|
||||
}
|
||||
|
||||
bool checkHeartbeat() {
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
HTTPClient http;
|
||||
String url = String(api_base_url) + "/api/device/heartbeat";
|
||||
http.setTimeout(10000);
|
||||
http.begin(url);
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
|
||||
JsonDocument doc; // ArduinoJson v7
|
||||
doc["device_id"] = device_id;
|
||||
doc["api_key"] = api_key;
|
||||
doc["firmware_version"] = "1.0.0";
|
||||
doc["ip_address"] = WiFi.localIP().toString();
|
||||
|
||||
String requestBody;
|
||||
serializeJson(doc, requestBody);
|
||||
|
||||
int httpResponseCode = http.POST(requestBody);
|
||||
bool pending_update = false;
|
||||
|
||||
if (httpResponseCode == 200) {
|
||||
String payload = http.getString();
|
||||
JsonDocument respDoc; // ArduinoJson v7
|
||||
deserializeJson(respDoc, payload);
|
||||
pending_update = respDoc["pending_update"] | false;
|
||||
} else {
|
||||
Serial.print("Heartbeat failed, HTTP code: ");
|
||||
Serial.println(httpResponseCode);
|
||||
}
|
||||
http.end();
|
||||
return pending_update;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// MAIN SETUP & LOOP
|
||||
// ==========================================
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
delay(2000);
|
||||
|
||||
// Turn ON power to the e-Paper display HAT via GPIO 2
|
||||
pinMode(PIN_PWR, OUTPUT);
|
||||
digitalWrite(PIN_PWR, HIGH);
|
||||
delay(200); // Allow display power to stabilize
|
||||
|
||||
// BUSY pin is an active output from the Waveshare HAT
|
||||
pinMode(PIN_BUSY, INPUT);
|
||||
|
||||
Serial.println("Initializing Display...");
|
||||
|
||||
// Initialize hardware SPI with explicit pin mapping
|
||||
SPI.begin(18, 19, 23, PIN_CS); // SCK=18, MISO=19, MOSI=23, SS=CS
|
||||
|
||||
// 2MHz SPI - prevents data corruption over jumper wires
|
||||
display.epd2.selectSPI(SPI, SPISettings(2000000, MSBFIRST, SPI_MODE0));
|
||||
|
||||
// 2ms reset pulse - required for Waveshare boards with the reset transistor circuit
|
||||
display.init(115200, true, 2, false);
|
||||
display.epd2.selectFastFullUpdate(false);
|
||||
display.setRotation(0); // 0 = Horizontal Landscape (800x480)
|
||||
|
||||
connectWiFi();
|
||||
|
||||
// Fetch and display patient data immediately on boot
|
||||
fetchDisplayData();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (millis() - lastUpdate > updateInterval) {
|
||||
lastUpdate = millis();
|
||||
|
||||
Serial.println("Sending heartbeat...");
|
||||
if (checkHeartbeat() || !displayDrawn) {
|
||||
Serial.println("Update pending or initial draw needed. Fetching new data...");
|
||||
fetchDisplayData();
|
||||
} else {
|
||||
Serial.println("No update pending.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
@@ -0,0 +1,9 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
|
||||
# This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,13 @@
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN corepack enable pnpm
|
||||
|
||||
COPY package.json pnpm-lock.yaml* ./
|
||||
|
||||
RUN pnpm install
|
||||
|
||||
COPY . .
|
||||
|
||||
CMD ["pnpm", "dev"]
|
||||
@@ -0,0 +1,36 @@
|
||||
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, run the development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
# or
|
||||
pnpm dev
|
||||
# or
|
||||
bun dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||
|
||||
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||
|
||||
## Learn More
|
||||
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "base-nova",
|
||||
"rsc": true,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/app/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"iconLibrary": "lucide",
|
||||
"rtl": false,
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"menuColor": "default",
|
||||
"menuAccent": "subtle",
|
||||
"registries": {}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
// Override default ignores of eslint-config-next.
|
||||
globalIgnores([
|
||||
// Default ignores of eslint-config-next:
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
// Allow other devices on the network to receive live updates
|
||||
allowedDevOrigins: ["192.168.0.31"],
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: '/api/:path*',
|
||||
destination: 'http://127.0.0.1:8000/api/:path*', // Proxy to FastAPI backend
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "frontend_tmp",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.7.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^1.31.0",
|
||||
"next": "16.3.1",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "19.2.8",
|
||||
"react-dom": "19.2.8",
|
||||
"shadcn": "^4.17.0",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tw-animate-css": "^1.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/node": "20.19.43",
|
||||
"@types/react": "19.3.0",
|
||||
"@types/react-dom": "^19",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.3.1",
|
||||
"tailwindcss": "^4",
|
||||
"typescript": "5.9.3"
|
||||
},
|
||||
"packageManager": "pnpm@11.21.0"
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
allowBuilds:
|
||||
sharp: false
|
||||
unrs-resolver: false
|
||||
minimumReleaseAgeExclude:
|
||||
- '@next/env@16.3.1'
|
||||
- '@next/eslint-plugin-next@16.3.1'
|
||||
- '@next/swc-darwin-arm64@16.3.1'
|
||||
- '@next/swc-darwin-x64@16.3.1'
|
||||
- '@next/swc-linux-arm64-gnu@16.3.1'
|
||||
- '@next/swc-linux-arm64-musl@16.3.1'
|
||||
- '@next/swc-linux-x64-gnu@16.3.1'
|
||||
- '@next/swc-linux-x64-musl@16.3.1'
|
||||
- '@next/swc-win32-arm64-msvc@16.3.1'
|
||||
- '@next/swc-win32-x64-msvc@16.3.1'
|
||||
- eslint-config-next@16.3.1
|
||||
- next@16.3.1
|
||||
@@ -0,0 +1,7 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 391 B |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
|
After Width: | Height: | Size: 988 KiB |
|
After Width: | Height: | Size: 2.9 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 128 B |
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
@@ -0,0 +1,111 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { fetchApi } from "@/lib/api";
|
||||
import { ArrowLeft, MonitorPlay } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export default function AddDisplayPage() {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [rooms, setRooms] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchApi('/rooms').then(data => setRooms(data)).catch(() => {});
|
||||
}, []);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
device_id: "",
|
||||
device_secret: "",
|
||||
name: "",
|
||||
room_id: ""
|
||||
});
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
|
||||
setFormData({ ...formData, [e.target.name]: e.target.value });
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
...formData,
|
||||
room_id: formData.room_id ? parseInt(formData.room_id) : null,
|
||||
};
|
||||
|
||||
await fetchApi("/displays", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
router.push("/displays");
|
||||
} catch (err: any) {
|
||||
setError(err?.message || "Failed to register display.");
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-xl mx-auto space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Link href="/displays" className="p-2 text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:text-zinc-100 hover:bg-zinc-100 dark:bg-zinc-800 rounded-lg transition-colors">
|
||||
<ArrowLeft size={20} />
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
|
||||
Register New Display
|
||||
</h1>
|
||||
<p className="text-zinc-600 dark:text-zinc-400 mt-1 text-sm">Add a new ESP32 e-paper display to the system.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-950 border border-red-900 text-red-400 p-3 rounded-lg text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 rounded-xl p-4 sm:p-6 space-y-5 sm:space-y-6 shadow-sm">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Hardware Device ID *</label>
|
||||
<input required type="text" name="device_id" value={formData.device_id} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 font-mono text-sm" placeholder="e.g. ESP32-MAC-123" />
|
||||
<p className="text-[11px] sm:text-xs text-zinc-500 mt-1">This is usually the MAC address or unique ID hardcoded in the ESP32.</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Device Secret Key *</label>
|
||||
<input required type="text" name="device_secret" value={formData.device_secret} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 font-mono text-sm" placeholder="Secret Token for Authentication" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Display Custom Name (Optional)</label>
|
||||
<input type="text" name="name" value={formData.name} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="e.g. Ward A - Main Display" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Assign to Room (Optional)</label>
|
||||
<select name="room_id" value={formData.room_id} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm">
|
||||
<option value="">-- Unassigned --</option>
|
||||
{rooms.map((room: any) => (
|
||||
<option key={room.id} value={room.id}>{room.room_number} ({room.ward})</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-4 border-t border-zinc-200 dark:border-zinc-800 flex flex-col-reverse sm:flex-row justify-end gap-2.5 sm:gap-3">
|
||||
<Link href="/displays" className="w-full sm:w-auto px-4 py-2.5 rounded-lg text-center text-sm text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:text-zinc-100 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors">
|
||||
Cancel
|
||||
</Link>
|
||||
<button type="submit" disabled={loading} className="w-full sm:w-auto bg-red-600 hover:bg-red-500 text-white px-6 py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 text-sm disabled:opacity-50 shadow-sm">
|
||||
{loading ? "Registering..." : <><MonitorPlay size={18} /> Register Device</>}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { fetchApi } from "@/lib/api";
|
||||
import { Monitor, Plus, Wifi, Battery, Search } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
export default function DisplaysPage() {
|
||||
const [displays, setDisplays] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
fetchApi('/displays')
|
||||
.then(data => {
|
||||
setDisplays(data);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch(err => {
|
||||
console.error(err);
|
||||
setLoading(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 sm:gap-4 bg-white/75 dark:bg-zinc-900/75 backdrop-blur-md border border-zinc-200/60 dark:border-zinc-800/60 px-4 sm:px-5 py-3 sm:py-3.5 rounded-xl shadow-xs">
|
||||
<div>
|
||||
<h1 className="text-xl sm:text-2xl font-bold text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
|
||||
<Monitor className="text-red-500" /> Displays
|
||||
</h1>
|
||||
<p className="text-xs sm:text-sm text-zinc-600 dark:text-zinc-400 mt-0.5">Manage ESP32 e-paper displays in the ward.</p>
|
||||
</div>
|
||||
<Link href="/displays/new" className="w-full sm:w-auto bg-red-600 hover:bg-red-500 text-white px-4 py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 text-sm shadow-sm">
|
||||
<Plus size={18} /> Register Display
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4 sm:gap-6">
|
||||
{loading ? (
|
||||
<div className="col-span-full h-40 flex items-center justify-center border border-zinc-200 dark:border-zinc-800 rounded-xl bg-zinc-50/70 dark:bg-zinc-900/30 text-zinc-500 text-sm">
|
||||
Loading displays...
|
||||
</div>
|
||||
) : displays.length === 0 ? (
|
||||
<div className="col-span-full h-40 flex items-center justify-center border border-zinc-200 dark:border-zinc-800 rounded-xl bg-zinc-50/70 dark:bg-zinc-900/30 text-zinc-500 text-sm">
|
||||
No displays registered.
|
||||
</div>
|
||||
) : (
|
||||
displays.map((display: any) => (
|
||||
<div key={display.id} className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 rounded-xl p-4 sm:p-5 hover:border-zinc-700/60 transition-colors shadow-sm">
|
||||
<div className="flex justify-between items-start mb-3 sm:mb-4">
|
||||
<div>
|
||||
<h3 className="font-semibold text-zinc-800 dark:text-zinc-200 text-base sm:text-lg flex items-center gap-2">
|
||||
{display.name || `Display ${display.device_id.substring(0,6)}`}
|
||||
</h3>
|
||||
<p className="text-zinc-500 text-xs font-mono mt-0.5 sm:mt-1">ID: {display.device_id}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className={`w-2.5 h-2.5 rounded-full ${display.online_status ? 'bg-emerald-500 animate-pulse' : 'bg-zinc-500'}`}></span>
|
||||
<span className="text-[10px] text-zinc-500 capitalize">{display.online_status ? 'Online' : 'Offline'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2.5 sm:space-y-3 mb-4 sm:mb-5">
|
||||
<div className="flex justify-between text-xs sm:text-sm">
|
||||
<span className="text-zinc-500">Room Assigned:</span>
|
||||
<span className="text-zinc-700 dark:text-zinc-300 font-medium">{display.room_id || 'None'}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-xs sm:text-sm">
|
||||
<span className="text-zinc-500">IP Address:</span>
|
||||
<span className="text-zinc-700 dark:text-zinc-300 font-mono text-xs">{display.ip_address || 'Offline'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-4 border-t border-zinc-200 dark:border-zinc-800/80 pt-3 sm:pt-4">
|
||||
<div className="flex items-center gap-1.5 text-xs text-zinc-600 dark:text-zinc-400">
|
||||
<Wifi size={14} className={display.wifi_rssi && display.wifi_rssi > -70 ? "text-emerald-500" : "text-amber-500"} />
|
||||
{display.wifi_rssi ? `${display.wifi_rssi} dBm` : 'N/A'}
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 text-xs text-zinc-600 dark:text-zinc-400">
|
||||
<Battery size={14} className={display.battery && display.battery > 20 ? "text-emerald-500" : "text-red-500"} />
|
||||
{display.battery ? `${display.battery}%` : 'N/A'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}␍
|
||||
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,130 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn/tailwind.css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
--font-heading: var(--font-sans);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--radius-sm: calc(var(--radius) * 0.6);
|
||||
--radius-md: calc(var(--radius) * 0.8);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) * 1.4);
|
||||
--radius-2xl: calc(var(--radius) * 1.8);
|
||||
--radius-3xl: calc(var(--radius) * 2.2);
|
||||
--radius-4xl: calc(var(--radius) * 2.6);
|
||||
}
|
||||
|
||||
:root {
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.87 0 0);
|
||||
--chart-2: oklch(0.556 0 0);
|
||||
--chart-3: oklch(0.439 0 0);
|
||||
--chart-4: oklch(0.371 0 0);
|
||||
--chart-5: oklch(0.269 0 0);
|
||||
--radius: 0.625rem;
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.87 0 0);
|
||||
--chart-2: oklch(0.556 0 0);
|
||||
--chart-3: oklch(0.439 0 0);
|
||||
--chart-4: oklch(0.371 0 0);
|
||||
--chart-5: oklch(0.269 0 0);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
html {
|
||||
@apply font-sans;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Inter } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import DashboardLayout from "@/components/DashboardLayout";
|
||||
import { ThemeProvider } from "@/components/ThemeProvider";
|
||||
|
||||
const inter = Inter({ subsets: ["latin"] });
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "ICU Patient Display Management System",
|
||||
description: "Dashboard for managing ICU e-Paper displays",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body
|
||||
className={`${inter.className} h-screen w-screen overflow-hidden text-zinc-900 dark:text-zinc-100 selection:bg-red-900 selection:text-red-100 bg-cover bg-center bg-no-repeat bg-fixed relative`}
|
||||
style={{ backgroundImage: "url('/hospital-bg.png')" }}
|
||||
>
|
||||
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem={false}>
|
||||
<DashboardLayout>
|
||||
{children}
|
||||
</DashboardLayout>
|
||||
</ThemeProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { fetchApi } from "@/lib/api";
|
||||
import { Lock, Mail, ArrowRight } from "lucide-react";
|
||||
|
||||
export default function LoginPage() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const formData = new URLSearchParams();
|
||||
formData.append("username", email);
|
||||
formData.append("password", password);
|
||||
|
||||
const res = await fetchApi("/auth/login", {
|
||||
method: "POST",
|
||||
body: formData, // Passing the URLSearchParams object directly allows fetch to set the correct Content-Type
|
||||
});
|
||||
|
||||
if (res.access_token) {
|
||||
localStorage.setItem("token", res.access_token);
|
||||
// We'd typically redirect to / here, but we are keeping the dashboard open.
|
||||
window.location.href = "/";
|
||||
} else {
|
||||
setError("Invalid response from server.");
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err?.message || "Failed to login. Check credentials.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex min-h-full w-full items-center justify-center bg-transparent p-4 sm:p-6">
|
||||
<div className="relative z-10 w-full max-w-md bg-white/85 dark:bg-zinc-950/85 border border-zinc-200/80 dark:border-zinc-800/80 p-6 sm:p-8 rounded-2xl shadow-2xl backdrop-blur-md my-auto">
|
||||
<div className="text-center mb-6 sm:mb-8">
|
||||
<div className="flex justify-center mb-4 sm:mb-6">
|
||||
<img src="/logo.png" alt="DMH Logo" className="h-12 sm:h-16 w-auto object-contain" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-100 tracking-tight">Staff Login</h1>
|
||||
<p className="text-zinc-600 dark:text-zinc-400 mt-2 text-sm">Sign in to access the ICU management system</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-950 border border-red-900 text-red-400 p-3 rounded-lg text-sm mb-6 text-center">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleLogin} className="space-y-5">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Email Address</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-2.5 text-zinc-500 dark:text-zinc-500" size={18} />
|
||||
<input
|
||||
type="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg pl-10 pr-4 py-2 focus:outline-none focus:border-red-500 transition-colors"
|
||||
placeholder="nurse@hospital.com"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Password</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-2.5 text-zinc-500 dark:text-zinc-500" size={18} />
|
||||
<input
|
||||
type="password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg pl-10 pr-4 py-2 focus:outline-none focus:border-red-500 transition-colors"
|
||||
placeholder="••••••••"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full bg-red-600 hover:bg-red-500 text-white font-medium py-2.5 rounded-lg transition-colors flex items-center justify-center gap-2 mt-2 disabled:opacity-50"
|
||||
>
|
||||
{loading ? "Authenticating..." : "Sign In"}
|
||||
{!loading && <ArrowRight size={18} />}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { fetchApi } from "@/lib/api";
|
||||
import { HeartPulse, Activity, AlertCircle, MonitorPlay } from "lucide-react";
|
||||
|
||||
export default function Dashboard() {
|
||||
const [stats, setStats] = useState({ patients: 0, displays: 0, critical: 0 });
|
||||
const [recentPatients, setRecentPatients] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
// We fetch patients and displays to get basic counts.
|
||||
// Real implementation would have a dedicated /stats endpoint.
|
||||
Promise.all([
|
||||
fetchApi('/patients').catch(() => []),
|
||||
fetchApi('/displays').catch(() => [])
|
||||
]).then(([patients, displays]) => {
|
||||
const pList = patients || [];
|
||||
const dList = displays || [];
|
||||
setStats({
|
||||
patients: pList.length,
|
||||
displays: dList.length,
|
||||
critical: pList.filter((p: any) => p.status === 'Critical').length
|
||||
});
|
||||
|
||||
const sorted = [...pList].sort((a: any, b: any) => {
|
||||
return new Date(b.last_updated).getTime() - new Date(a.last_updated).getTime();
|
||||
});
|
||||
setRecentPatients(sorted.slice(0, 5));
|
||||
setLoading(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-end gap-2 bg-white/75 dark:bg-zinc-900/75 backdrop-blur-md border border-zinc-200/60 dark:border-zinc-800/60 px-4 sm:px-5 py-3 sm:py-3.5 rounded-xl shadow-xs">
|
||||
<div>
|
||||
<h1 className="text-xl sm:text-2xl font-bold text-zinc-900 dark:text-zinc-100 tracking-tight">ICU Overview</h1>
|
||||
<p className="text-xs sm:text-sm text-zinc-600 dark:text-zinc-400 mt-0.5">Live status of patients and monitoring displays.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="h-36 sm:h-40 flex items-center justify-center border border-zinc-200 dark:border-zinc-800 rounded-xl bg-zinc-50/70 dark:bg-zinc-900/30">
|
||||
<Activity className="animate-pulse text-red-500" size={32} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
|
||||
<div className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 p-5 sm:p-6 rounded-xl relative overflow-hidden group shadow-sm">
|
||||
<div className="absolute top-0 right-0 p-4 sm:p-6 opacity-20 group-hover:scale-110 group-hover:opacity-30 transition-all duration-500">
|
||||
<HeartPulse size={64} className="text-red-500 sm:w-20 sm:h-20" />
|
||||
</div>
|
||||
<div className="relative z-10">
|
||||
<h3 className="text-zinc-500 dark:text-zinc-400 font-medium text-xs sm:text-sm">Total Patients</h3>
|
||||
<p className="text-3xl sm:text-4xl font-bold text-zinc-900 dark:text-zinc-100 mt-1.5 sm:mt-2">{stats.patients}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 p-5 sm:p-6 rounded-xl relative overflow-hidden group shadow-sm">
|
||||
<div className="absolute top-0 right-0 p-4 sm:p-6 opacity-20 group-hover:scale-110 group-hover:opacity-30 transition-all duration-500">
|
||||
<MonitorPlay size={64} className="text-emerald-500 sm:w-20 sm:h-20" />
|
||||
</div>
|
||||
<div className="relative z-10">
|
||||
<h3 className="text-zinc-500 dark:text-zinc-400 font-medium text-xs sm:text-sm">Active Displays</h3>
|
||||
<p className="text-3xl sm:text-4xl font-bold text-zinc-900 dark:text-zinc-100 mt-1.5 sm:mt-2">{stats.displays}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 p-5 sm:p-6 rounded-xl relative overflow-hidden group shadow-sm sm:col-span-2 lg:col-span-1">
|
||||
<div className="absolute top-0 right-0 p-4 sm:p-6 opacity-20 group-hover:scale-110 group-hover:opacity-30 transition-all duration-500">
|
||||
<AlertCircle size={64} className="text-amber-500 sm:w-20 sm:h-20" />
|
||||
</div>
|
||||
<div className="relative z-10">
|
||||
<h3 className="text-zinc-500 dark:text-zinc-400 font-medium text-xs sm:text-sm">Critical Patients</h3>
|
||||
<p className="text-3xl sm:text-4xl font-bold text-red-600 dark:text-red-400 mt-1.5 sm:mt-2">{stats.critical}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Recent Updates Table */}
|
||||
<div className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 rounded-xl overflow-hidden shadow-sm mt-6 sm:mt-8">
|
||||
<div className="px-4 sm:px-6 py-3.5 sm:py-4 border-b border-zinc-200 dark:border-zinc-800 flex justify-between items-center">
|
||||
<h2 className="text-base sm:text-lg font-medium text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
|
||||
<Activity className="text-red-500 w-4 h-4 sm:w-5 sm:h-5" />
|
||||
Recent Updates
|
||||
</h2>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-[520px] w-full text-left text-xs sm:text-sm text-zinc-700 dark:text-zinc-300">
|
||||
<thead className="bg-white/80 dark:bg-zinc-950/50 text-zinc-600 dark:text-zinc-400 border-b border-zinc-200 dark:border-zinc-800 uppercase text-[10px] sm:text-xs font-semibold">
|
||||
<tr>
|
||||
<th className="px-4 sm:px-6 py-3">Time</th>
|
||||
<th className="px-4 sm:px-6 py-3">Patient</th>
|
||||
<th className="px-4 sm:px-6 py-3">Room</th>
|
||||
<th className="px-4 sm:px-6 py-3">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{recentPatients.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="px-4 sm:px-6 py-6 text-center text-zinc-500">No recent updates found.</td>
|
||||
</tr>
|
||||
) : (
|
||||
recentPatients.map((patient: any) => (
|
||||
<tr key={patient.id} className="border-b border-zinc-200/50 dark:border-zinc-800/50 hover:bg-zinc-100 dark:hover:bg-zinc-800/20 transition-colors">
|
||||
<td className="px-4 sm:px-6 py-3 text-zinc-500 whitespace-nowrap">{new Date(patient.last_updated).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</td>
|
||||
<td className="px-4 sm:px-6 py-3 font-medium text-zinc-800 dark:text-zinc-200">
|
||||
<span>{patient.patient_name}</span>
|
||||
<span className="text-zinc-500 text-xs ml-1.5 font-normal">({patient.mrn})</span>
|
||||
</td>
|
||||
<td className="px-4 sm:px-6 py-3">{patient.room_id || 'Unassigned'}</td>
|
||||
<td className="px-4 sm:px-6 py-3 whitespace-nowrap">
|
||||
<span className={`px-2 py-0.5 rounded text-xs font-medium ${
|
||||
patient.status === 'Critical' ? 'text-red-500 bg-red-500/10 dark:text-red-400 dark:bg-red-400/10' :
|
||||
patient.status === 'Stable' ? 'text-emerald-600 bg-emerald-500/10 dark:text-emerald-400 dark:bg-emerald-400/10' :
|
||||
'text-zinc-600 dark:text-zinc-400 bg-zinc-400/10'
|
||||
}`}>
|
||||
{patient.status}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { fetchApi } from "@/lib/api";
|
||||
import { ArrowLeft, Save } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter, useParams } from "next/navigation";
|
||||
|
||||
export default function EditPatientPage() {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [rooms, setRooms] = useState<any[]>([]);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
mrn: "",
|
||||
patient_name: "",
|
||||
age: "",
|
||||
gender: "",
|
||||
blood_group: "",
|
||||
diagnosis: "",
|
||||
status: "",
|
||||
doctor_name: "",
|
||||
room_id: "",
|
||||
notes: "",
|
||||
food_instructions: "",
|
||||
visiting_rules: "",
|
||||
visiting_hours: "",
|
||||
restrictions: ""
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchApi('/rooms').then(data => setRooms(data)).catch(() => {});
|
||||
|
||||
if (params.id) {
|
||||
fetchApi(`/patients/${params.id}`)
|
||||
.then(data => {
|
||||
setFormData({
|
||||
mrn: data.mrn || "",
|
||||
patient_name: data.patient_name || "",
|
||||
age: data.age?.toString() || "",
|
||||
gender: data.gender || "",
|
||||
blood_group: data.blood_group || "",
|
||||
diagnosis: data.diagnosis || "",
|
||||
status: data.status || "",
|
||||
doctor_name: data.doctor_name || "",
|
||||
room_id: data.room_id?.toString() || "",
|
||||
notes: data.notes || "",
|
||||
food_instructions: data.food_instructions || "No outside food allowed",
|
||||
visiting_rules: data.visiting_rules || "2 times visits",
|
||||
visiting_hours: data.visiting_hours || "9 - 11 AM, 4 - 6 PM",
|
||||
restrictions: data.restrictions || "Dogs are not allowed"
|
||||
});
|
||||
setLoading(false);
|
||||
})
|
||||
.catch(err => {
|
||||
setError("Failed to load patient data.");
|
||||
setLoading(false);
|
||||
});
|
||||
}
|
||||
}, [params.id]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
|
||||
setFormData({ ...formData, [e.target.name]: e.target.value });
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setSaving(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
...formData,
|
||||
age: parseInt(formData.age),
|
||||
room_id: formData.room_id ? parseInt(formData.room_id) : null,
|
||||
};
|
||||
|
||||
await fetchApi(`/patients/${params.id}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
router.push("/patients");
|
||||
} catch (err: any) {
|
||||
setError(err.message || "Failed to update patient.");
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) return <div className="p-8 text-center text-zinc-500 dark:text-zinc-500">Loading...</div>;
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl mx-auto space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Link href="/patients" className="p-2 text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:text-zinc-100 hover:bg-zinc-100 dark:bg-zinc-800 rounded-lg transition-colors">
|
||||
<ArrowLeft size={20} />
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
|
||||
Edit Patient
|
||||
</h1>
|
||||
<p className="text-zinc-600 dark:text-zinc-400 mt-1 text-sm">Update {formData.patient_name}'s records.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-950 border border-red-900 text-red-400 p-3 rounded-lg text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 rounded-xl p-4 sm:p-6 space-y-5 sm:space-y-6 shadow-sm">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">MRN *</label>
|
||||
<input required type="text" name="mrn" value={formData.mrn} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 font-mono text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Full Name *</label>
|
||||
<input required type="text" name="patient_name" value={formData.patient_name} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Age *</label>
|
||||
<input required type="number" name="age" value={formData.age} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Gender *</label>
|
||||
<select required name="gender" value={formData.gender} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm">
|
||||
<option value="">Select Gender</option>
|
||||
<option value="Male">Male</option>
|
||||
<option value="Female">Female</option>
|
||||
<option value="Other">Other</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Blood Group</label>
|
||||
<input type="text" name="blood_group" value={formData.blood_group} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Primary Diagnosis</label>
|
||||
<input type="text" name="diagnosis" value={formData.diagnosis} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Status *</label>
|
||||
<select required name="status" value={formData.status} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm">
|
||||
<option value="Stable">Stable</option>
|
||||
<option value="Observation">Observation</option>
|
||||
<option value="Critical">Critical</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Attending Doctor</label>
|
||||
<input type="text" name="doctor_name" value={formData.doctor_name} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" />
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Assign to Room (Optional)</label>
|
||||
<select name="room_id" value={formData.room_id} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm">
|
||||
<option value="">-- Unassigned --</option>
|
||||
{rooms.map((room: any) => (
|
||||
<option key={room.id} value={room.id}>{room.room_number} ({room.ward})</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Food / Dietary Instructions</label>
|
||||
<input type="text" name="food_instructions" value={formData.food_instructions} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="e.g. No outside food allowed" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Visiting Policy / Frequency</label>
|
||||
<input type="text" name="visiting_rules" value={formData.visiting_rules} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="e.g. 2 times visits" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Visiting Hours</label>
|
||||
<input type="text" name="visiting_hours" value={formData.visiting_hours} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="e.g. 9 - 11 AM, 4 - 6 PM" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Restrictions & Guidelines</label>
|
||||
<input type="text" name="restrictions" value={formData.restrictions} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="e.g. Dogs are not allowed / Mask required" />
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Additional Description / Notes</label>
|
||||
<textarea name="notes" value={formData.notes} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm min-h-[100px]" placeholder="Enter any additional details, allergies, or notes..."></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-4 border-t border-zinc-200 dark:border-zinc-800 flex flex-col-reverse sm:flex-row justify-end gap-2.5 sm:gap-3">
|
||||
<Link href="/patients" className="w-full sm:w-auto px-4 py-2.5 rounded-lg text-center text-sm text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:text-zinc-100 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors">
|
||||
Cancel
|
||||
</Link>
|
||||
<button type="submit" disabled={saving} className="w-full sm:w-auto bg-red-600 hover:bg-red-500 text-white px-6 py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 text-sm disabled:opacity-50 shadow-sm">
|
||||
{saving ? "Saving..." : <><Save size={18} /> Update Patient</>}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { fetchApi } from "@/lib/api";
|
||||
import { ArrowLeft, UserPlus } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export default function AddPatientPage() {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [rooms, setRooms] = useState<any[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchApi('/rooms').then(data => setRooms(data)).catch(() => {});
|
||||
}, []);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
mrn: "",
|
||||
patient_name: "",
|
||||
age: "",
|
||||
gender: "Male",
|
||||
blood_group: "A+",
|
||||
diagnosis: "",
|
||||
status: "Stable",
|
||||
doctor_name: "",
|
||||
room_id: "",
|
||||
notes: "",
|
||||
food_instructions: "No outside food allowed",
|
||||
visiting_rules: "2 times visits",
|
||||
visiting_hours: "9 - 11 AM, 4 - 6 PM",
|
||||
restrictions: "Dogs are not allowed"
|
||||
});
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
|
||||
setFormData({ ...formData, [e.target.name]: e.target.value });
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
...formData,
|
||||
age: formData.age ? parseInt(formData.age) : null,
|
||||
room_id: formData.room_id ? parseInt(formData.room_id) : null,
|
||||
};
|
||||
|
||||
await fetchApi("/patients", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
router.push("/patients");
|
||||
} catch (err: any) {
|
||||
setError(err?.message || "Failed to add patient.");
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Link href="/patients" className="p-2 text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:text-zinc-100 hover:bg-zinc-100 dark:bg-zinc-800 rounded-lg transition-colors">
|
||||
<ArrowLeft size={20} />
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
|
||||
Add New Patient
|
||||
</h1>
|
||||
<p className="text-zinc-600 dark:text-zinc-400 mt-1 text-sm">Enter the patient's admission details below.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-950 border border-red-900 text-red-400 p-3 rounded-lg text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 rounded-xl p-4 sm:p-6 space-y-5 sm:space-y-6 shadow-sm">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6">
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Medical Record Number (MRN) *</label>
|
||||
<input required type="text" name="mrn" value={formData.mrn} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 font-mono text-sm" placeholder="e.g. MRN-10293" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Full Name *</label>
|
||||
<input required type="text" name="patient_name" value={formData.patient_name} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="John Doe" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Age</label>
|
||||
<input type="number" name="age" value={formData.age} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="45" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Gender</label>
|
||||
<select name="gender" value={formData.gender} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm">
|
||||
<option value="Male">Male</option>
|
||||
<option value="Female">Female</option>
|
||||
<option value="Other">Other</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Blood Group</label>
|
||||
<select name="blood_group" value={formData.blood_group} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm">
|
||||
<option value="A+">A+</option>
|
||||
<option value="A-">A-</option>
|
||||
<option value="B+">B+</option>
|
||||
<option value="B-">B-</option>
|
||||
<option value="O+">O+</option>
|
||||
<option value="O-">O-</option>
|
||||
<option value="AB+">AB+</option>
|
||||
<option value="AB-">AB-</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Current Status</label>
|
||||
<select name="status" value={formData.status} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm">
|
||||
<option value="Stable">Stable</option>
|
||||
<option value="Critical">Critical</option>
|
||||
<option value="Observation">Observation</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Diagnosis / Reason for Admission</label>
|
||||
<input type="text" name="diagnosis" value={formData.diagnosis} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="e.g. Post-operative care" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Attending Doctor</label>
|
||||
<input type="text" name="doctor_name" value={formData.doctor_name} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="Dr. Smith" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Assign to Room (Optional)</label>
|
||||
<select name="room_id" value={formData.room_id} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm">
|
||||
<option value="">-- Unassigned --</option>
|
||||
{rooms.map((room: any) => (
|
||||
<option key={room.id} value={room.id}>{room.room_number} ({room.ward})</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Food / Dietary Instructions</label>
|
||||
<input type="text" name="food_instructions" value={formData.food_instructions} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="e.g. No outside food allowed" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Visiting Policy / Frequency</label>
|
||||
<input type="text" name="visiting_rules" value={formData.visiting_rules} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="e.g. 2 times visits" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Visiting Hours</label>
|
||||
<input type="text" name="visiting_hours" value={formData.visiting_hours} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="e.g. 9 - 11 AM, 4 - 6 PM" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Restrictions & Guidelines</label>
|
||||
<input type="text" name="restrictions" value={formData.restrictions} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="e.g. Dogs are not allowed / Mask required" />
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Additional Description / Notes</label>
|
||||
<textarea name="notes" value={formData.notes} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm min-h-[100px]" placeholder="Enter any additional details, allergies, or notes..."></textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-4 border-t border-zinc-200 dark:border-zinc-800 flex flex-col-reverse sm:flex-row justify-end gap-2.5 sm:gap-3">
|
||||
<Link href="/patients" className="w-full sm:w-auto px-4 py-2.5 rounded-lg text-center text-sm text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:text-zinc-100 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors">
|
||||
Cancel
|
||||
</Link>
|
||||
<button type="submit" disabled={loading} className="w-full sm:w-auto bg-red-600 hover:bg-red-500 text-white px-6 py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 text-sm disabled:opacity-50 shadow-sm">
|
||||
{loading ? "Saving..." : <><UserPlus size={18} /> Save Patient</>}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { fetchApi } from "@/lib/api";
|
||||
import { Users, Plus, Edit2, Search, Trash2 } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
export default function PatientsPage() {
|
||||
const [patients, setPatients] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
fetchApi('/patients')
|
||||
.then(data => {
|
||||
setPatients(data || []);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch(err => {
|
||||
console.error(err);
|
||||
setLoading(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
if (!confirm("Are you sure you want to delete this patient?")) return;
|
||||
try {
|
||||
await fetchApi(`/patients/${id}`, { method: 'DELETE' });
|
||||
setPatients(patients.filter((p: any) => p.id !== id));
|
||||
} catch (err) {
|
||||
alert("Failed to delete patient");
|
||||
}
|
||||
};
|
||||
|
||||
const filtered = patients.filter((p: any) =>
|
||||
p.patient_name?.toLowerCase().includes(search.toLowerCase()) ||
|
||||
p.mrn?.toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 sm:gap-4 bg-white/75 dark:bg-zinc-900/75 backdrop-blur-md border border-zinc-200/60 dark:border-zinc-800/60 px-4 sm:px-5 py-3 sm:py-3.5 rounded-xl shadow-xs">
|
||||
<div>
|
||||
<h1 className="text-xl sm:text-2xl font-bold text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
|
||||
<Users className="text-red-500" /> Patients
|
||||
</h1>
|
||||
<p className="text-xs sm:text-sm text-zinc-600 dark:text-zinc-400 mt-0.5">Manage ICU patients, vitals, and records.</p>
|
||||
</div>
|
||||
<Link href="/patients/new" className="w-full sm:w-auto bg-red-600 hover:bg-red-500 text-white px-4 py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 text-sm shadow-sm">
|
||||
<Plus size={18} /> Add Patient
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 rounded-xl overflow-hidden shadow-sm">
|
||||
<div className="p-3 sm:p-4 border-b border-zinc-200 dark:border-zinc-800 flex justify-between items-center bg-zinc-100/50 dark:bg-zinc-900/50">
|
||||
<div className="flex items-center bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 rounded-lg px-3 py-2 w-full sm:w-72">
|
||||
<Search className="text-zinc-400 mr-2 shrink-0" size={16} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search MRN or Name..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="bg-transparent border-none outline-none text-zinc-700 dark:text-zinc-300 placeholder-zinc-500 text-xs sm:text-sm w-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-[640px] w-full text-left text-xs sm:text-sm text-zinc-700 dark:text-zinc-300">
|
||||
<thead className="bg-white/80 dark:bg-zinc-950/50 text-zinc-600 dark:text-zinc-400 border-b border-zinc-200 dark:border-zinc-800 uppercase text-[10px] sm:text-xs font-semibold">
|
||||
<tr>
|
||||
<th className="px-4 sm:px-6 py-3.5">MRN</th>
|
||||
<th className="px-4 sm:px-6 py-3.5">Name</th>
|
||||
<th className="px-4 sm:px-6 py-3.5">Room</th>
|
||||
<th className="px-4 sm:px-6 py-3.5">Status</th>
|
||||
<th className="px-4 sm:px-6 py-3.5">Doctor</th>
|
||||
<th className="px-4 sm:px-6 py-3.5 text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-4 sm:px-6 py-8 text-center text-zinc-500">Loading patients...</td>
|
||||
</tr>
|
||||
) : filtered.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={6} className="px-4 sm:px-6 py-8 text-center text-zinc-500">No patients found.</td>
|
||||
</tr>
|
||||
) : (
|
||||
filtered.map((patient: any) => (
|
||||
<tr key={patient.id} className="border-b border-zinc-200/50 dark:border-zinc-800/50 hover:bg-zinc-100 dark:hover:bg-zinc-800/20 transition-colors">
|
||||
<td className="px-4 sm:px-6 py-3.5 font-mono text-zinc-500 whitespace-nowrap">{patient.mrn}</td>
|
||||
<td className="px-4 sm:px-6 py-3.5 font-medium text-zinc-800 dark:text-zinc-200">
|
||||
<div>{patient.patient_name}</div>
|
||||
<div className="text-xs text-zinc-500 font-normal mt-0.5">
|
||||
{patient.food_instructions && <span className="mr-2 text-amber-600 dark:text-amber-400 font-medium">{patient.food_instructions}</span>}
|
||||
{patient.visiting_rules && <span className="text-zinc-400">Visits: {patient.visiting_rules}</span>}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 sm:px-6 py-3.5 whitespace-nowrap">{patient.room_id || 'Unassigned'}</td>
|
||||
<td className="px-4 sm:px-6 py-3.5 whitespace-nowrap">
|
||||
<span className={`px-2 py-0.5 rounded text-xs font-medium ${
|
||||
patient.status === 'Critical' ? 'text-red-500 bg-red-500/10 dark:text-red-400 dark:bg-red-400/10' :
|
||||
patient.status === 'Stable' ? 'text-emerald-600 bg-emerald-500/10 dark:text-emerald-400 dark:bg-emerald-400/10' :
|
||||
'text-zinc-600 dark:text-zinc-400 bg-zinc-400/10'
|
||||
}`}>
|
||||
{patient.status || 'Unknown'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 sm:px-6 py-3.5 whitespace-nowrap">{patient.doctor_name || 'N/A'}</td>
|
||||
<td className="px-4 sm:px-6 py-3.5 text-right whitespace-nowrap">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Link href={`/patients/${patient.id}`} className="text-zinc-400 hover:text-emerald-500 transition-colors p-1" title="Edit Patient">
|
||||
<Edit2 size={16} />
|
||||
</Link>
|
||||
<button onClick={() => handleDelete(patient.id)} className="text-zinc-400 hover:text-red-500 transition-colors p-1" title="Delete Patient">
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { fetchApi } from "@/lib/api";
|
||||
import { ArrowLeft, Save } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export default function AddRoomPage() {
|
||||
const router = useRouter();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
room_number: "",
|
||||
ward: "",
|
||||
display_id: ""
|
||||
});
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setFormData({ ...formData, [e.target.name]: e.target.value });
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
...formData,
|
||||
display_id: formData.display_id ? parseInt(formData.display_id) : null,
|
||||
};
|
||||
|
||||
await fetchApi("/rooms", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
router.push("/rooms");
|
||||
} catch (err: any) {
|
||||
setError(err?.message || "Failed to add room.");
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-xl mx-auto space-y-6">
|
||||
<div className="flex items-center gap-4">
|
||||
<Link href="/rooms" className="p-2 text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:text-zinc-100 hover:bg-zinc-100 dark:bg-zinc-800 rounded-lg transition-colors">
|
||||
<ArrowLeft size={20} />
|
||||
</Link>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
|
||||
Add New Room
|
||||
</h1>
|
||||
<p className="text-zinc-600 dark:text-zinc-400 mt-1 text-sm">Register a new ICU room to the system.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-950 border border-red-900 text-red-400 p-3 rounded-lg text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 rounded-xl p-4 sm:p-6 space-y-5 sm:space-y-6 shadow-sm">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Room Number *</label>
|
||||
<input required type="text" name="room_number" value={formData.room_number} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 font-mono text-sm" placeholder="e.g. ICU-01" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Ward *</label>
|
||||
<input required type="text" name="ward" value={formData.ward} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 font-mono text-sm" placeholder="e.g. Ward A" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-xs sm:text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-1.5">Assign Display ID (Optional)</label>
|
||||
<input type="number" name="display_id" value={formData.display_id} onChange={handleChange} className="w-full bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 text-zinc-900 dark:text-zinc-100 rounded-lg px-3.5 sm:px-4 py-2 focus:outline-none focus:border-red-500 text-sm" placeholder="e.g. 1" />
|
||||
<p className="text-[11px] sm:text-xs text-zinc-500 mt-1">ID of the registered DisplayDevice assigned to this room.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-4 border-t border-zinc-200 dark:border-zinc-800 flex flex-col-reverse sm:flex-row justify-end gap-2.5 sm:gap-3">
|
||||
<Link href="/rooms" className="w-full sm:w-auto px-4 py-2.5 rounded-lg text-center text-sm text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:text-zinc-100 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors">
|
||||
Cancel
|
||||
</Link>
|
||||
<button type="submit" disabled={loading} className="w-full sm:w-auto bg-red-600 hover:bg-red-500 text-white px-6 py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 text-sm disabled:opacity-50 shadow-sm">
|
||||
{loading ? "Adding..." : <><Save size={18} /> Add Room</>}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { fetchApi } from "@/lib/api";
|
||||
import { Plus, Search } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
export default function RoomsPage() {
|
||||
const [rooms, setRooms] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
fetchApi('/rooms')
|
||||
.then(data => {
|
||||
setRooms(data);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch(err => {
|
||||
console.error(err);
|
||||
setLoading(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const filtered = rooms.filter((r: any) =>
|
||||
r.room_number?.toLowerCase().includes(search.toLowerCase()) ||
|
||||
r.ward?.toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 sm:gap-4 bg-white/75 dark:bg-zinc-900/75 backdrop-blur-md border border-zinc-200/60 dark:border-zinc-800/60 px-4 sm:px-5 py-3 sm:py-3.5 rounded-xl shadow-xs">
|
||||
<div>
|
||||
<h1 className="text-xl sm:text-2xl font-bold text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
|
||||
<svg className="text-red-500 w-5 h-5 sm:w-6 sm:h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" /></svg>
|
||||
ICU Rooms
|
||||
</h1>
|
||||
<p className="text-xs sm:text-sm text-zinc-600 dark:text-zinc-400 mt-0.5">Manage hospital rooms and ward assignments.</p>
|
||||
</div>
|
||||
<Link href="/rooms/new" className="w-full sm:w-auto bg-red-600 hover:bg-red-500 text-white px-4 py-2.5 rounded-lg font-medium transition-colors flex items-center justify-center gap-2 text-sm shadow-sm">
|
||||
<Plus size={18} /> Add Room
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 rounded-xl overflow-hidden shadow-sm">
|
||||
<div className="p-3 sm:p-4 border-b border-zinc-200 dark:border-zinc-800 flex justify-between items-center bg-zinc-100/50 dark:bg-zinc-900/50">
|
||||
<div className="flex items-center bg-white dark:bg-zinc-950 border border-zinc-200 dark:border-zinc-800 rounded-lg px-3 py-2 w-full sm:w-72">
|
||||
<Search className="text-zinc-400 mr-2 shrink-0" size={16} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search Room Number or Ward..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="bg-transparent border-none outline-none text-zinc-700 dark:text-zinc-300 placeholder-zinc-500 text-xs sm:text-sm w-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-[500px] w-full text-left text-xs sm:text-sm text-zinc-700 dark:text-zinc-300">
|
||||
<thead className="bg-white/80 dark:bg-zinc-950/50 text-zinc-600 dark:text-zinc-400 border-b border-zinc-200 dark:border-zinc-800 uppercase text-[10px] sm:text-xs font-semibold">
|
||||
<tr>
|
||||
<th className="px-4 sm:px-6 py-3.5">Room ID</th>
|
||||
<th className="px-4 sm:px-6 py-3.5">Room Number</th>
|
||||
<th className="px-4 sm:px-6 py-3.5">Ward</th>
|
||||
<th className="px-4 sm:px-6 py-3.5">Assigned Display ID</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="px-4 sm:px-6 py-8 text-center text-zinc-500">Loading rooms...</td>
|
||||
</tr>
|
||||
) : filtered.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={4} className="px-4 sm:px-6 py-8 text-center text-zinc-500">No rooms found.</td>
|
||||
</tr>
|
||||
) : (
|
||||
filtered.map((room: any) => (
|
||||
<tr key={room.id} className="border-b border-zinc-200/50 dark:border-zinc-800/50 hover:bg-zinc-100 dark:hover:bg-zinc-800/20 transition-colors">
|
||||
<td className="px-4 sm:px-6 py-3.5 font-mono text-zinc-500 whitespace-nowrap">{room.id}</td>
|
||||
<td className="px-4 sm:px-6 py-3.5 font-medium text-zinc-800 dark:text-zinc-200 whitespace-nowrap">{room.room_number}</td>
|
||||
<td className="px-4 sm:px-6 py-3.5 whitespace-nowrap">{room.ward}</td>
|
||||
<td className="px-4 sm:px-6 py-3.5 font-mono whitespace-nowrap">{room.display_id || 'None'}</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { fetchApi } from "@/lib/api";
|
||||
import { User, LogOut, Moon, BellRing } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTheme } from "next-themes";
|
||||
|
||||
export default function SettingsPage() {
|
||||
const router = useRouter();
|
||||
const { theme, setTheme } = useTheme();
|
||||
const [user, setUser] = useState<{name: string, email: string, role: string} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUser = async () => {
|
||||
try {
|
||||
const data = await fetchApi("/auth/me");
|
||||
setUser(data);
|
||||
} catch (e) {
|
||||
// Ignore
|
||||
}
|
||||
};
|
||||
fetchUser();
|
||||
}, []);
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem("token");
|
||||
window.location.href = "/login"; // Force full reload to clear states
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto space-y-6">
|
||||
<div className="bg-white/75 dark:bg-zinc-900/75 backdrop-blur-md border border-zinc-200/60 dark:border-zinc-800/60 px-4 sm:px-5 py-3 sm:py-3.5 rounded-xl shadow-xs">
|
||||
<h1 className="text-xl sm:text-2xl font-bold text-zinc-900 dark:text-zinc-100 flex items-center gap-2">
|
||||
Settings
|
||||
</h1>
|
||||
<p className="text-xs sm:text-sm text-zinc-600 dark:text-zinc-400 mt-0.5">Manage your account and system preferences.</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4 sm:gap-6">
|
||||
<div className="col-span-1 lg:col-span-2 space-y-4 sm:space-y-6">
|
||||
<div className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 rounded-xl p-4 sm:p-6 shadow-sm">
|
||||
<h2 className="text-base sm:text-lg font-bold text-zinc-900 dark:text-zinc-100 mb-4 flex items-center gap-2">
|
||||
<User size={20} className="text-red-500" />
|
||||
Profile Information
|
||||
</h2>
|
||||
{user ? (
|
||||
<div className="space-y-3 sm:space-y-4">
|
||||
<div>
|
||||
<p className="text-xs text-zinc-500">Full Name</p>
|
||||
<p className="text-sm sm:text-base text-zinc-900 dark:text-zinc-100 font-medium">{user.name}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs text-zinc-500">Email Address</p>
|
||||
<p className="text-sm sm:text-base text-zinc-900 dark:text-zinc-100 font-medium break-all">{user.email}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs text-zinc-500">Role</p>
|
||||
<p className="text-sm sm:text-base text-zinc-900 dark:text-zinc-100 font-medium capitalize">{user.role}</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-xs sm:text-sm text-zinc-500">
|
||||
You are currently browsing as a Guest.
|
||||
<button onClick={() => router.push('/login')} className="text-red-500 ml-2 hover:underline">Log In</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 rounded-xl p-4 sm:p-6 shadow-sm">
|
||||
<h2 className="text-base sm:text-lg font-bold text-zinc-900 dark:text-zinc-100 mb-4 flex items-center gap-2">
|
||||
<Moon size={20} className="text-red-500" />
|
||||
Appearance
|
||||
</h2>
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-sm sm:text-base text-zinc-900 dark:text-zinc-100 font-medium">Dark Mode</p>
|
||||
<p className="text-xs sm:text-sm text-zinc-500 mt-0.5">Toggle between light and dark theme across the dashboard.</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
|
||||
className={`w-12 h-6 rounded-full relative transition-colors shrink-0 ${theme === "dark" ? "bg-red-600" : "bg-zinc-300"}`}
|
||||
aria-label="Toggle theme"
|
||||
>
|
||||
<div className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-all ${theme === "dark" ? "right-1" : "left-1"}`}></div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-span-1 space-y-4 sm:space-y-6">
|
||||
<div className="bg-zinc-50/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 rounded-xl p-4 sm:p-6 shadow-sm">
|
||||
<h2 className="text-base sm:text-lg font-bold text-zinc-900 dark:text-zinc-100 mb-4 flex items-center gap-2">
|
||||
<BellRing size={20} className="text-red-500" />
|
||||
Quick Actions
|
||||
</h2>
|
||||
<div className="space-y-3">
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="w-full flex items-center justify-center gap-2 bg-red-950/40 hover:bg-red-900/60 text-red-500 border border-red-900/60 py-2.5 rounded-lg transition-colors text-sm font-medium"
|
||||
>
|
||||
<LogOut size={18} />
|
||||
Sign Out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Sidebar from "./Sidebar";
|
||||
import TopNav from "./TopNav";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
export default function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname();
|
||||
const isLogin = pathname === "/login";
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
||||
|
||||
// Auto-close mobile drawer on route transition
|
||||
useEffect(() => {
|
||||
setSidebarOpen(false);
|
||||
}, [pathname]);
|
||||
|
||||
if (isLogin) {
|
||||
return (
|
||||
<main className="h-full w-full overflow-y-auto bg-transparent flex items-center justify-center p-4">
|
||||
{children}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-full w-full overflow-hidden relative">
|
||||
<Sidebar isOpen={sidebarOpen} onClose={() => setSidebarOpen(false)} />
|
||||
<div className="flex-1 flex flex-col min-w-0 min-h-0 w-full overflow-hidden">
|
||||
<TopNav onOpenSidebar={() => setSidebarOpen(true)} />
|
||||
<main className="flex-1 overflow-y-auto min-h-0 bg-transparent p-4 sm:p-6 md:p-8">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Activity, Users, Monitor, Settings, X, DoorOpen } from "lucide-react";
|
||||
|
||||
interface SidebarProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export default function Sidebar({ isOpen, onClose }: SidebarProps) {
|
||||
const pathname = usePathname();
|
||||
|
||||
const navItems = [
|
||||
{ href: "/", label: "Dashboard", icon: Activity },
|
||||
{ href: "/patients", label: "Patients", icon: Users },
|
||||
{ href: "/displays", label: "Displays", icon: Monitor },
|
||||
{ href: "/rooms", label: "Rooms", icon: DoorOpen },
|
||||
];
|
||||
|
||||
const isLinkActive = (href: string) => {
|
||||
if (href === "/") return pathname === "/";
|
||||
return pathname.startsWith(href);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Mobile Backdrop Overlay */}
|
||||
{isOpen && (
|
||||
<div
|
||||
onClick={onClose}
|
||||
className="fixed inset-0 bg-black/60 backdrop-blur-sm z-40 md:hidden transition-opacity duration-300"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Sidebar Navigation */}
|
||||
<aside
|
||||
className={`
|
||||
fixed inset-y-0 left-0 z-50 w-64 bg-white/95 dark:bg-zinc-950/95 backdrop-blur-md border-r border-zinc-200 dark:border-zinc-800
|
||||
flex flex-col h-full transition-transform duration-300 ease-in-out shrink-0 select-none shadow-2xl md:shadow-none
|
||||
md:static md:translate-x-0
|
||||
${isOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0"}
|
||||
`}
|
||||
>
|
||||
{/* Header / Brand Logo */}
|
||||
<div className="h-16 flex items-center justify-between px-6 border-b border-zinc-200 dark:border-zinc-800 shrink-0">
|
||||
<Link href="/" onClick={onClose} className="flex items-center gap-3">
|
||||
<img src="/logo.png" alt="DMH Logo" className="h-9 w-auto object-contain" />
|
||||
<span className="text-zinc-900 dark:text-zinc-100 font-bold text-lg tracking-wide">
|
||||
ICU Display
|
||||
</span>
|
||||
</Link>
|
||||
|
||||
{/* Close button for mobile */}
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="md:hidden p-1.5 text-zinc-400 hover:text-zinc-900 dark:hover:text-zinc-100 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-lg transition-colors"
|
||||
aria-label="Close Sidebar"
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Navigation Links */}
|
||||
<nav className="flex-1 py-6 px-4 space-y-1.5 overflow-y-auto">
|
||||
{navItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const active = isLinkActive(item.href);
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
onClick={onClose}
|
||||
className={`
|
||||
flex items-center px-4 py-3 rounded-lg text-sm font-medium transition-all group
|
||||
${active
|
||||
? "text-red-500 bg-red-500/10 dark:bg-red-950/40 font-semibold"
|
||||
: "text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-zinc-100 hover:bg-zinc-100/80 dark:hover:bg-zinc-900/60"
|
||||
}
|
||||
`}
|
||||
>
|
||||
<Icon
|
||||
size={20}
|
||||
className={`mr-3 transition-colors ${
|
||||
active ? "text-red-500" : "text-zinc-400 dark:text-zinc-500 group-hover:text-red-400"
|
||||
}`}
|
||||
/>
|
||||
<span>{item.label}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* Bottom Settings Link */}
|
||||
<div className="p-4 border-t border-zinc-200 dark:border-zinc-800 shrink-0">
|
||||
<Link
|
||||
href="/settings"
|
||||
onClick={onClose}
|
||||
className={`
|
||||
flex items-center px-4 py-3 w-full rounded-lg text-sm font-medium transition-all group
|
||||
${isLinkActive("/settings")
|
||||
? "text-red-500 bg-red-500/10 dark:bg-red-950/40 font-semibold"
|
||||
: "text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-zinc-100 hover:bg-zinc-100/80 dark:hover:bg-zinc-900/60"
|
||||
}
|
||||
`}
|
||||
>
|
||||
<Settings
|
||||
size={20}
|
||||
className={`mr-3 transition-colors ${
|
||||
isLinkActive("/settings")
|
||||
? "text-red-500"
|
||||
: "text-zinc-400 dark:text-zinc-500 group-hover:text-red-400"
|
||||
}`}
|
||||
/>
|
||||
<span>Settings</span>
|
||||
</Link>
|
||||
</div>
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { ThemeProvider as NextThemesProvider } from "next-themes";
|
||||
|
||||
export function ThemeProvider({
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof NextThemesProvider>) {
|
||||
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
"use client";
|
||||
|
||||
import { Bell, Search, User, Menu, Moon, Sun } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
interface TopNavProps {
|
||||
onOpenSidebar: () => void;
|
||||
}
|
||||
|
||||
export default function TopNav({ onOpenSidebar }: TopNavProps) {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<header className="h-16 bg-white/70 dark:bg-zinc-950/70 backdrop-blur-md border-b border-zinc-200/60 dark:border-zinc-800/60 flex items-center justify-between px-3 sm:px-6 shrink-0 z-20 transition-colors">
|
||||
{/* Left: Mobile Menu & Search */}
|
||||
<div className="flex items-center gap-2 sm:gap-3 flex-1 min-w-0 mr-2 sm:mr-4">
|
||||
{/* Mobile Hamburger Menu Button */}
|
||||
<button
|
||||
onClick={onOpenSidebar}
|
||||
className="md:hidden p-2 -ml-1 text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-zinc-100 hover:bg-zinc-100 dark:hover:bg-zinc-800/60 rounded-lg transition-colors shrink-0"
|
||||
aria-label="Open Navigation Menu"
|
||||
>
|
||||
<Menu size={22} />
|
||||
</button>
|
||||
|
||||
{/* Mobile brand icon when sidebar is collapsed */}
|
||||
<Link href="/" className="flex items-center md:hidden shrink-0">
|
||||
<img src="/logo.png" alt="DMH Logo" className="h-7 w-auto object-contain" />
|
||||
</Link>
|
||||
|
||||
{/* Search Bar - Responsive */}
|
||||
<div className="flex items-center bg-zinc-100/90 dark:bg-zinc-900/90 border border-zinc-200 dark:border-zinc-800 rounded-lg px-2.5 sm:px-3 py-1.5 w-full max-w-[170px] sm:max-w-xs md:max-w-sm">
|
||||
<Search className="text-zinc-400 dark:text-zinc-500 mr-2 shrink-0" size={15} />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search..."
|
||||
className="bg-transparent border-none outline-none text-zinc-800 dark:text-zinc-200 placeholder-zinc-400 dark:placeholder-zinc-500 text-xs sm:text-sm w-full min-w-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Actions & User Info */}
|
||||
<div className="flex items-center space-x-1.5 sm:space-x-3 shrink-0">
|
||||
{/* Theme Toggle */}
|
||||
{mounted && (
|
||||
<button
|
||||
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
|
||||
className="p-2 text-zinc-500 hover:text-zinc-900 dark:hover:text-zinc-100 hover:bg-zinc-100 dark:hover:bg-zinc-800/60 rounded-lg transition-colors"
|
||||
aria-label="Toggle Theme"
|
||||
>
|
||||
{theme === "dark" ? <Sun size={18} /> : <Moon size={18} />}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Notifications */}
|
||||
<button
|
||||
className="relative p-2 text-zinc-500 hover:text-zinc-900 dark:hover:text-zinc-100 hover:bg-zinc-100 dark:hover:bg-zinc-800/60 rounded-lg transition-colors"
|
||||
aria-label="Notifications"
|
||||
>
|
||||
<Bell size={18} />
|
||||
<span className="absolute top-1.5 right-1.5 w-2 h-2 bg-red-500 rounded-full"></span>
|
||||
</button>
|
||||
|
||||
{/* User Profile */}
|
||||
<div className="flex items-center space-x-2.5 border-l border-zinc-200 dark:border-zinc-800 pl-2 sm:pl-3">
|
||||
<div className="text-right hidden sm:block">
|
||||
<p className="text-xs sm:text-sm font-medium text-zinc-800 dark:text-zinc-200 leading-tight">Admin User</p>
|
||||
<p className="text-[10px] sm:text-xs text-zinc-500">ICU Ward A</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/settings"
|
||||
className="w-8 h-8 sm:w-9 sm:h-9 rounded-full bg-red-900/80 hover:bg-red-800 flex items-center justify-center border border-red-700/60 shrink-0 transition-colors"
|
||||
title="Profile & Settings"
|
||||
>
|
||||
<User className="text-red-300" size={16} />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-red-600 text-white hover:bg-red-500",
|
||||
destructive: "bg-red-700 text-white hover:bg-red-600",
|
||||
outline: "border border-zinc-200 dark:border-zinc-800 bg-transparent hover:bg-zinc-100 dark:hover:bg-zinc-800",
|
||||
secondary: "bg-zinc-100 dark:bg-zinc-800 text-zinc-900 dark:text-zinc-100 hover:bg-zinc-200 dark:hover:bg-zinc-700",
|
||||
ghost: "hover:bg-zinc-100 dark:hover:bg-zinc-800",
|
||||
link: "text-red-500 underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-8",
|
||||
icon: "h-10 w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
VariantProps<typeof buttonVariants> {}
|
||||
|
||||
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
({ className, variant, size, ...props }, ref) => {
|
||||
return (
|
||||
<button
|
||||
className={buttonVariants({ variant, size, className })}
|
||||
ref={ref}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
Button.displayName = "Button"
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
|
||||
async function testLogin() {
|
||||
const res = await fetch("http://127.0.0.1:8000/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body: "username=nurse%40hospital.com&password=password123",
|
||||
});
|
||||
|
||||
console.log(res.status);
|
||||
console.log(await res.text());
|
||||
}
|
||||
|
||||
testLogin();
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||