Compare commits
19
Commits
1cf218ca00
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
221cc8918f | ||
|
|
51e4b39c33 | ||
|
|
9276064d18 | ||
|
|
b8639bc52a | ||
|
|
cb47017eac | ||
|
|
5f649e3e4c | ||
|
|
c086833163 | ||
|
|
026da64e71 | ||
|
|
041a4075dd | ||
|
|
b6465708f0 | ||
|
|
f356442900 | ||
|
|
ee9390a2a0 | ||
|
|
13fd84a53c | ||
|
|
5d98aa57cb | ||
|
|
8ebdd0142c | ||
|
|
640ae9c1b4 | ||
|
|
d9ca4bbb02 | ||
|
|
cd9eb27a98 | ||
|
|
594407d404 |
@@ -0,0 +1 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
+24
-2
@@ -1,10 +1,19 @@
|
|||||||
backend/data/ams.db
|
# SQLite databases
|
||||||
backend/data/test.db
|
backend/data/*.db
|
||||||
|
*.sqlite
|
||||||
|
*.sqlite3
|
||||||
|
*.db
|
||||||
|
|
||||||
|
# Data directories
|
||||||
|
backend/data/backups/
|
||||||
backend/data/uploads/*
|
backend/data/uploads/*
|
||||||
!backend/data/uploads/.gitkeep
|
!backend/data/uploads/.gitkeep
|
||||||
backend/data/*
|
backend/data/*
|
||||||
!backend/data/.gitkeep
|
!backend/data/.gitkeep
|
||||||
!backend/data/uploads/
|
!backend/data/uploads/
|
||||||
|
!backend/data/backups/
|
||||||
|
|
||||||
|
# Python
|
||||||
.venv/
|
.venv/
|
||||||
backend/.venv/
|
backend/.venv/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
@@ -13,8 +22,21 @@ __pycache__/
|
|||||||
**/__pycache__/
|
**/__pycache__/
|
||||||
**/*.pyc
|
**/*.pyc
|
||||||
*.pyc
|
*.pyc
|
||||||
|
|
||||||
|
# Frontend
|
||||||
frontend/node_modules/
|
frontend/node_modules/
|
||||||
frontend/dist/
|
frontend/dist/
|
||||||
|
frontend/*.tsbuildinfo
|
||||||
|
*.tsbuildinfo
|
||||||
|
**/*.tsbuildinfo
|
||||||
|
|
||||||
|
# Archives
|
||||||
|
*.zip
|
||||||
|
*.tar.gz
|
||||||
|
*.tgz
|
||||||
|
|
||||||
|
# Environment & OS
|
||||||
.env
|
.env
|
||||||
*.env.local
|
*.env.local
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
.PHONY: dev backend frontend test seed install
|
.PHONY: dev backend frontend test seed install package
|
||||||
|
|
||||||
ifeq ($(OS),Windows_NT)
|
ifeq ($(OS),Windows_NT)
|
||||||
VENV_BIN := .venv/Scripts
|
VENV_BIN := .venv/Scripts
|
||||||
@@ -27,3 +27,6 @@ install:
|
|||||||
$(PYTHON_SYS) -m venv backend/.venv
|
$(PYTHON_SYS) -m venv backend/.venv
|
||||||
"backend/$(VENV_BIN)/pip" install -r backend/requirements.txt
|
"backend/$(VENV_BIN)/pip" install -r backend/requirements.txt
|
||||||
cd frontend && npm install
|
cd frontend && npm install
|
||||||
|
|
||||||
|
package:
|
||||||
|
git archive --format=zip --output=../poona-ams-delivery.zip HEAD
|
||||||
|
|||||||
@@ -71,7 +71,51 @@ docker compose up --build
|
|||||||
|
|
||||||
## Documentation & Walkthroughs
|
## Documentation & Walkthroughs
|
||||||
- [10-Minute Demo Script](docs/DEMO_SCRIPT.md)
|
- [10-Minute Demo Script](docs/DEMO_SCRIPT.md)
|
||||||
- [Acceptance Checklist (Proposal §10)](docs/ACCEPTANCE_CHECKLIST.md)
|
- [Acceptance Checklist & UAT Sign-off Matrix](docs/ACCEPTANCE_CHECKLIST.md)
|
||||||
|
- [Role-Based User Guide](docs/USER_GUIDE.md)
|
||||||
|
- [Assumptions, Retention & Governance Policies](docs/ASSUMPTIONS.md)
|
||||||
|
|
||||||
|
## Database Backup & Disaster Recovery
|
||||||
|
|
||||||
|
The application includes an automated, online backup utility in `backend/scripts/backup.py` that utilizes SQLite's safe online backup API (`sqlite3.Connection.backup`) to capture a transactionally consistent snapshot of the database alongside all uploaded attachment files without requiring downtime.
|
||||||
|
|
||||||
|
### Running a Manual Backup
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
# Windows:
|
||||||
|
.venv\Scripts\python.exe scripts/backup.py backup
|
||||||
|
# macOS/Linux:
|
||||||
|
python scripts/backup.py backup
|
||||||
|
```
|
||||||
|
- Creates a timestamped archive: `backend/data/backups/ams_backup_YYYYMMDD_HHMMSS.zip` containing `ams.db` and the `uploads/` folder.
|
||||||
|
- Runs `PRAGMA integrity_check` automatically before bundling.
|
||||||
|
- Retains the latest 7 backups by default (`--keep N` flag configurable).
|
||||||
|
|
||||||
|
### Verifying Backup Integrity
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
python scripts/backup.py verify data/backups/ams_backup_20261113_174700.zip
|
||||||
|
```
|
||||||
|
|
||||||
|
### Restoring from a Backup
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
python scripts/backup.py restore data/backups/ams_backup_YYYYMMDD_HHMMSS.zip
|
||||||
|
```
|
||||||
|
- Validates SQLite integrity before restoring.
|
||||||
|
- Automatically saves a `.safety_pre_restore_<timestamp>.bak` of the active database before overwriting.
|
||||||
|
- Unpacks attachments directly into `backend/data/uploads/`.
|
||||||
|
|
||||||
|
### Automated Nightly Backups
|
||||||
|
To schedule automatic nightly backups at 01:00 AM:
|
||||||
|
- **Linux / Docker (cron):**
|
||||||
|
```cron
|
||||||
|
0 1 * * * cd /path/to/poona-ams/backend && /path/to/poona-ams/backend/.venv/bin/python scripts/backup.py backup >> /var/log/ams_backup.log 2>&1
|
||||||
|
```
|
||||||
|
- **Windows (Task Scheduler / PowerShell):**
|
||||||
|
```powershell
|
||||||
|
schtasks /create /tn "PoonaAMS_NightlyBackup" /tr "powershell -ExecutionPolicy Bypass -Command 'cd C:\path\to\poona-ams\backend; .\.venv\Scripts\python.exe scripts\backup.py backup'" /sc daily /st 01:00
|
||||||
|
```
|
||||||
|
|
||||||
## Demo Accounts
|
## Demo Accounts
|
||||||
| Email | Password | Role |
|
| Email | Password | Role |
|
||||||
|
|||||||
@@ -31,6 +31,15 @@ def get_current_user(
|
|||||||
user = db.query(User).filter(User.id == user_id).first()
|
user = db.query(User).filter(User.id == user_id).first()
|
||||||
if user is None or not user.is_active:
|
if user is None or not user.is_active:
|
||||||
raise credentials_exception
|
raise credentials_exception
|
||||||
|
|
||||||
|
token_tv = payload.get("tv", 0)
|
||||||
|
user_tv = getattr(user, "token_version", 0)
|
||||||
|
if token_tv != user_tv:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Token has been invalidated. Please log in again.",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import logging
|
||||||
|
from sqlalchemy.engine import Engine
|
||||||
|
from ..models import Base
|
||||||
|
|
||||||
|
logger = logging.getLogger("poona_ams")
|
||||||
|
|
||||||
|
|
||||||
|
def run_sqlite_migrations(engine: Engine) -> None:
|
||||||
|
"""
|
||||||
|
Auto-migrate SQLite database schema additions for existing databases.
|
||||||
|
SQLite create_all() creates missing tables but does not alter existing
|
||||||
|
tables to add newly defined columns. This reconciles table columns
|
||||||
|
safely on startup without losing existing data.
|
||||||
|
"""
|
||||||
|
if engine.dialect.name != "sqlite":
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
with engine.begin() as conn:
|
||||||
|
existing_tables = {
|
||||||
|
row[0]
|
||||||
|
for row in conn.exec_driver_sql(
|
||||||
|
"SELECT name FROM sqlite_master WHERE type='table'"
|
||||||
|
).fetchall()
|
||||||
|
}
|
||||||
|
|
||||||
|
for table_name, table in Base.metadata.tables.items():
|
||||||
|
if table_name not in existing_tables:
|
||||||
|
continue
|
||||||
|
|
||||||
|
existing_cols = {
|
||||||
|
row[1]
|
||||||
|
for row in conn.exec_driver_sql(
|
||||||
|
f"PRAGMA table_info({table_name})"
|
||||||
|
).fetchall()
|
||||||
|
}
|
||||||
|
|
||||||
|
for col in table.columns:
|
||||||
|
if col.name not in existing_cols:
|
||||||
|
col_type = col.type.compile(engine.dialect)
|
||||||
|
if col.name == "token_version":
|
||||||
|
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} INTEGER DEFAULT 0 NOT NULL"
|
||||||
|
else:
|
||||||
|
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} {col_type}"
|
||||||
|
logger.info("Auto-migrating SQLite: %s", sql)
|
||||||
|
conn.exec_driver_sql(sql)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Failed running SQLite auto-migrations.")
|
||||||
|
raise
|
||||||
@@ -1,9 +1,77 @@
|
|||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
import bcrypt
|
import bcrypt
|
||||||
|
from fastapi import HTTPException, status
|
||||||
from jose import JWTError, jwt
|
from jose import JWTError, jwt
|
||||||
from .config import settings
|
from .config import settings
|
||||||
from .time_utils import utc_now
|
from .time_utils import utc_now
|
||||||
|
|
||||||
|
BLOCKLIST_PASSWORDS = {
|
||||||
|
"123456",
|
||||||
|
"12345678",
|
||||||
|
"password",
|
||||||
|
"password1",
|
||||||
|
"qwerty123",
|
||||||
|
"admin123",
|
||||||
|
"welcome1",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_password(password: str, email: str | None = None) -> None:
|
||||||
|
"""Validate password rules:
|
||||||
|
- Length: at least 8, at most 128 characters.
|
||||||
|
- Characters: at least one letter and at least one digit. (Special characters allowed, not required. Case insensitive.)
|
||||||
|
- Must NOT start or end with a space (reject with a clear message, do not silently strip).
|
||||||
|
- Blocklist (case-insensitive): '123456', '12345678', 'password', 'password1', 'qwerty123', 'admin123', 'welcome1'.
|
||||||
|
(NOTE: demo password 'demo@123' must remain allowed)
|
||||||
|
- Must not contain the user's username/email local-part if length >= 4 (case-insensitive).
|
||||||
|
"""
|
||||||
|
if not isinstance(password, str):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="Password must be a string.",
|
||||||
|
)
|
||||||
|
|
||||||
|
if password.startswith(" ") or password.endswith(" "):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="Password must not start or end with a space.",
|
||||||
|
)
|
||||||
|
|
||||||
|
if len(password) < 8:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="Password must be at least 8 characters long.",
|
||||||
|
)
|
||||||
|
|
||||||
|
if len(password) > 128:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="Password must be at most 128 characters long.",
|
||||||
|
)
|
||||||
|
|
||||||
|
has_letter = any(c.isalpha() for c in password)
|
||||||
|
has_digit = any(c.isdigit() for c in password)
|
||||||
|
if not has_letter or not has_digit:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="Password must contain at least one letter and at least one digit.",
|
||||||
|
)
|
||||||
|
|
||||||
|
lower_pass = password.lower()
|
||||||
|
if lower_pass in BLOCKLIST_PASSWORDS:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="Password is too common or easily guessable.",
|
||||||
|
)
|
||||||
|
|
||||||
|
if email:
|
||||||
|
local_part = email.split("@")[0].strip().lower()
|
||||||
|
if len(local_part) >= 4 and local_part in lower_pass:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="Password must not contain your email username.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def verify_password(plain: str, hashed: str) -> bool:
|
def verify_password(plain: str, hashed: str) -> bool:
|
||||||
if not plain or not hashed:
|
if not plain or not hashed:
|
||||||
@@ -24,6 +92,8 @@ def hash_password(plain: str) -> str:
|
|||||||
|
|
||||||
def create_access_token(data: dict, expires_minutes: int | None = None) -> str:
|
def create_access_token(data: dict, expires_minutes: int | None = None) -> str:
|
||||||
to_encode = data.copy()
|
to_encode = data.copy()
|
||||||
|
if "tv" not in to_encode:
|
||||||
|
to_encode["tv"] = 0
|
||||||
expire = utc_now() + timedelta(minutes=expires_minutes or settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
expire = utc_now() + timedelta(minutes=expires_minutes or settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||||
to_encode["exp"] = expire
|
to_encode["exp"] = expire
|
||||||
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from fastapi.responses import JSONResponse
|
|||||||
from .core.config import settings as app_settings
|
from .core.config import settings as app_settings
|
||||||
from .core.db import SessionLocal, engine, get_scheduler_db
|
from .core.db import SessionLocal, engine, get_scheduler_db
|
||||||
from .core.exceptions import CodedHTTPException, coded_http_exception_handler
|
from .core.exceptions import CodedHTTPException, coded_http_exception_handler
|
||||||
|
from .core.migrations import run_sqlite_migrations
|
||||||
from .models import Base
|
from .models import Base
|
||||||
from .routers import (
|
from .routers import (
|
||||||
assets,
|
assets,
|
||||||
@@ -56,6 +57,7 @@ def _scheduled_alert_job() -> None:
|
|||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
Base.metadata.create_all(bind=engine)
|
Base.metadata.create_all(bind=engine)
|
||||||
|
run_sqlite_migrations(engine)
|
||||||
with SessionLocal() as db:
|
with SessionLocal() as db:
|
||||||
ensure_default_settings(db)
|
ensure_default_settings(db)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ class Complaint(Base):
|
|||||||
received_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
received_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||||
received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), index=True, nullable=True)
|
assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), index=True, nullable=True)
|
||||||
|
assigned_team: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||||
assigned_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
assigned_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
attended_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
attended_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||||
attended_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
attended_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ class User(Base):
|
|||||||
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
role: Mapped[str] = mapped_column(String(50), nullable=False)
|
role: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||||
department_id: Mapped[Optional[int]] = mapped_column(ForeignKey("departments.id"), nullable=True)
|
department_id: Mapped[Optional[int]] = mapped_column(ForeignKey("departments.id"), nullable=True)
|
||||||
|
token_version: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
||||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
|
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ class DemoEquipment(Base):
|
|||||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
equipment_type: Mapped[str] = mapped_column(String(100), nullable=False)
|
equipment_type: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||||
|
serial_no: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||||
supplier_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
|
supplier_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
|
||||||
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
|
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
|
||||||
location_id: Mapped[Optional[int]] = mapped_column(ForeignKey("locations.id"), nullable=True)
|
location_id: Mapped[Optional[int]] = mapped_column(ForeignKey("locations.id"), nullable=True)
|
||||||
@@ -52,6 +53,7 @@ class DepartmentVisit(Base):
|
|||||||
visited_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
visited_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||||
visit_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
|
visit_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
|
||||||
observations: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
observations: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
|
new_requirements: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
|
||||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
|
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, onupdate=utc_now, nullable=False)
|
||||||
|
|||||||
@@ -371,6 +371,8 @@ def list_assets(
|
|||||||
supplier_id: Optional[int] = None,
|
supplier_id: Optional[int] = None,
|
||||||
status_filter: Optional[str] = Query(None, alias="status"),
|
status_filter: Optional[str] = Query(None, alias="status"),
|
||||||
criticality: Optional[str] = None,
|
criticality: Optional[str] = None,
|
||||||
|
requires_calibration: Optional[bool] = None,
|
||||||
|
insurance_applicable: Optional[bool] = None,
|
||||||
warranty_status: Optional[str] = None,
|
warranty_status: Optional[str] = None,
|
||||||
contract_status: Optional[str] = None,
|
contract_status: Optional[str] = None,
|
||||||
page: int = Query(1, ge=1),
|
page: int = Query(1, ge=1),
|
||||||
@@ -401,6 +403,10 @@ def list_assets(
|
|||||||
query = query.filter(Asset.status == status_filter)
|
query = query.filter(Asset.status == status_filter)
|
||||||
if criticality:
|
if criticality:
|
||||||
query = query.filter(Asset.criticality == criticality)
|
query = query.filter(Asset.criticality == criticality)
|
||||||
|
if requires_calibration is not None:
|
||||||
|
query = query.filter(Asset.requires_calibration.is_(requires_calibration))
|
||||||
|
if insurance_applicable is not None:
|
||||||
|
query = query.filter(Asset.insurance_applicable.is_(insurance_applicable))
|
||||||
|
|
||||||
if q and q.strip():
|
if q and q.strip():
|
||||||
like = f"%{q.strip()}%"
|
like = f"%{q.strip()}%"
|
||||||
|
|||||||
@@ -6,13 +6,19 @@ from sqlalchemy.orm import Session, joinedload
|
|||||||
from ..core.db import get_db
|
from ..core.db import get_db
|
||||||
from ..core.deps import get_current_user
|
from ..core.deps import get_current_user
|
||||||
from ..core.exceptions import CodedHTTPException
|
from ..core.exceptions import CodedHTTPException
|
||||||
from ..core.security import create_access_token, verify_password
|
from ..core.security import create_access_token, hash_password, validate_password, verify_password
|
||||||
from ..models.masters import User
|
from ..models.masters import User
|
||||||
from ..schemas.auth import LoginRequest, TokenResponse, UserOut
|
from ..schemas.auth import LoginRequest, TokenResponse, UserOut
|
||||||
from ..services.settings_service import get_demo_as_of_date
|
from ..services.settings_service import get_demo_as_of_date
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||||
|
|
||||||
|
|
||||||
|
class ChangePasswordRequest(BaseModel):
|
||||||
|
current_password: str
|
||||||
|
new_password: str = Field(..., max_length=128)
|
||||||
|
|
||||||
MAX_LOGIN_ATTEMPTS = 15
|
MAX_LOGIN_ATTEMPTS = 15
|
||||||
LOGIN_WINDOW_SECONDS = 60.0
|
LOGIN_WINDOW_SECONDS = 60.0
|
||||||
_login_attempts: dict[str, deque[float]] = defaultdict(deque)
|
_login_attempts: dict[str, deque[float]] = defaultdict(deque)
|
||||||
@@ -77,7 +83,11 @@ def login(payload: LoginRequest, request: Request, db: Session = Depends(get_db)
|
|||||||
detail="User account is inactive.",
|
detail="User account is inactive.",
|
||||||
)
|
)
|
||||||
|
|
||||||
token = create_access_token({"sub": str(user.id), "role": user.role})
|
token = create_access_token({
|
||||||
|
"sub": str(user.id),
|
||||||
|
"role": user.role,
|
||||||
|
"tv": user.token_version,
|
||||||
|
})
|
||||||
return TokenResponse(
|
return TokenResponse(
|
||||||
access_token=token,
|
access_token=token,
|
||||||
token_type="bearer",
|
token_type="bearer",
|
||||||
@@ -91,3 +101,37 @@ def get_me(
|
|||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
):
|
):
|
||||||
return _build_user_out(current_user, db)
|
return _build_user_out(current_user, db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/change-password")
|
||||||
|
def change_password(
|
||||||
|
payload: ChangePasswordRequest,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
if not verify_password(payload.current_password, current_user.password_hash):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Current password is incorrect.",
|
||||||
|
)
|
||||||
|
if payload.new_password == payload.current_password:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="New password must be different.",
|
||||||
|
)
|
||||||
|
validate_password(payload.new_password, email=current_user.email)
|
||||||
|
current_user.password_hash = hash_password(payload.new_password)
|
||||||
|
current_user.token_version = (current_user.token_version or 0) + 1
|
||||||
|
db.commit()
|
||||||
|
db.refresh(current_user)
|
||||||
|
|
||||||
|
new_token = create_access_token({
|
||||||
|
"sub": str(current_user.id),
|
||||||
|
"role": current_user.role,
|
||||||
|
"tv": current_user.token_version,
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
"message": "Password changed successfully.",
|
||||||
|
"access_token": new_token,
|
||||||
|
"token_type": "bearer",
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
|
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, UploadFile, status
|
||||||
|
from fastapi.responses import StreamingResponse
|
||||||
from sqlalchemy import or_
|
from sqlalchemy import or_
|
||||||
from sqlalchemy.orm import Session, joinedload
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
@@ -25,6 +26,7 @@ from ..schemas.calibration import (
|
|||||||
CalibrationStatusFilter,
|
CalibrationStatusFilter,
|
||||||
)
|
)
|
||||||
from ..services.audit import log_audit
|
from ..services.audit import log_audit
|
||||||
|
from ..services.bulk_templates import build_calibration_template_xlsx, process_calibration_import
|
||||||
from ..services.calculations import compute_schedule_status
|
from ..services.calculations import compute_schedule_status
|
||||||
from ..services.permissions import Role
|
from ..services.permissions import Role
|
||||||
from ..services.settings_service import get_setting_value
|
from ..services.settings_service import get_setting_value
|
||||||
@@ -196,6 +198,40 @@ def _create_plan_and_initial_record(
|
|||||||
return plan
|
return plan
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/import-template")
|
||||||
|
def download_calibration_import_template(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||||
|
):
|
||||||
|
buf = build_calibration_template_xlsx(db)
|
||||||
|
return StreamingResponse(
|
||||||
|
buf,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": 'attachment; filename="calibration_import_template.xlsx"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/bulk-import")
|
||||||
|
def bulk_import_calibration(
|
||||||
|
file: UploadFile = File(...),
|
||||||
|
dry_run: bool = Query(False),
|
||||||
|
skip_invalid: bool = Query(False),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(
|
||||||
|
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
|
||||||
|
),
|
||||||
|
):
|
||||||
|
content = file.file.read()
|
||||||
|
return process_calibration_import(
|
||||||
|
db=db,
|
||||||
|
filename=file.filename or "calibration.xlsx",
|
||||||
|
content=content,
|
||||||
|
user_id=current_user.id,
|
||||||
|
dry_run=dry_run,
|
||||||
|
skip_invalid=skip_invalid,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/plans", response_model=CalibrationPlanListOut)
|
@router.get("/plans", response_model=CalibrationPlanListOut)
|
||||||
def list_calibration_plans(
|
def list_calibration_plans(
|
||||||
q: str = "",
|
q: str = "",
|
||||||
|
|||||||
@@ -144,6 +144,7 @@ def _to_complaint_out(
|
|||||||
received_at=recv_at,
|
received_at=recv_at,
|
||||||
assigned_to_id=c.assigned_to_id,
|
assigned_to_id=c.assigned_to_id,
|
||||||
assigned_to_name=user_names.get(c.assigned_to_id) if c.assigned_to_id else None,
|
assigned_to_name=user_names.get(c.assigned_to_id) if c.assigned_to_id else None,
|
||||||
|
assigned_team=c.assigned_team,
|
||||||
assigned_at=asg_at,
|
assigned_at=asg_at,
|
||||||
attended_by_id=c.attended_by_id,
|
attended_by_id=c.attended_by_id,
|
||||||
attended_by_name=user_names.get(c.attended_by_id) if c.attended_by_id else None,
|
attended_by_name=user_names.get(c.attended_by_id) if c.attended_by_id else None,
|
||||||
@@ -233,6 +234,7 @@ def _sync_asset_status(db: Session, asset: Asset, exclude_complaint_id: int, req
|
|||||||
def list_complaints(
|
def list_complaints(
|
||||||
q: Optional[str] = None,
|
q: Optional[str] = None,
|
||||||
department_id: Optional[int] = None,
|
department_id: Optional[int] = None,
|
||||||
|
location_id: Optional[int] = None,
|
||||||
asset_id: Optional[int] = None,
|
asset_id: Optional[int] = None,
|
||||||
call_status: Optional[str] = None,
|
call_status: Optional[str] = None,
|
||||||
priority: Optional[str] = None,
|
priority: Optional[str] = None,
|
||||||
@@ -260,6 +262,9 @@ def list_complaints(
|
|||||||
elif department_id is not None:
|
elif department_id is not None:
|
||||||
query = query.filter(Asset.department_id == department_id)
|
query = query.filter(Asset.department_id == department_id)
|
||||||
|
|
||||||
|
if location_id is not None:
|
||||||
|
query = query.filter(Asset.location_id == location_id)
|
||||||
|
|
||||||
if asset_id is not None:
|
if asset_id is not None:
|
||||||
query = query.filter(Complaint.asset_id == asset_id)
|
query = query.filter(Complaint.asset_id == asset_id)
|
||||||
if call_status:
|
if call_status:
|
||||||
@@ -372,6 +377,7 @@ def create_complaint(
|
|||||||
breakdown_details=payload.breakdown_details,
|
breakdown_details=payload.breakdown_details,
|
||||||
priority=payload.priority,
|
priority=payload.priority,
|
||||||
notes=payload.notes,
|
notes=payload.notes,
|
||||||
|
assigned_team=payload.assigned_team,
|
||||||
registered_at=reg_at,
|
registered_at=reg_at,
|
||||||
registered_by_id=current_user.id,
|
registered_by_id=current_user.id,
|
||||||
received_by_id=recv_by_id,
|
received_by_id=recv_by_id,
|
||||||
@@ -555,19 +561,34 @@ def assign_complaint(
|
|||||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||||
):
|
):
|
||||||
comp = _load_complaint_or_404(db, complaint_id)
|
comp = _load_complaint_or_404(db, complaint_id)
|
||||||
assignee = db.query(User).filter(User.id == payload.assigned_to_id, User.is_active.is_(True)).first()
|
if payload.assigned_to_id is None and not payload.assigned_team:
|
||||||
if assignee is None:
|
raise HTTPException(status_code=422, detail="Either assigned_to_id or assigned_team must be provided.")
|
||||||
raise HTTPException(status_code=404, detail="Assigned user not found or inactive.")
|
|
||||||
|
assignee: Optional[User] = None
|
||||||
|
target_name = payload.assigned_team or ""
|
||||||
|
if payload.assigned_to_id is not None:
|
||||||
|
assignee = db.query(User).filter(User.id == payload.assigned_to_id, User.is_active.is_(True)).first()
|
||||||
|
if assignee is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Assigned user not found or inactive.")
|
||||||
|
target_name = assignee.name
|
||||||
|
if payload.assigned_team:
|
||||||
|
target_name = f"{assignee.name} ({payload.assigned_team})"
|
||||||
|
|
||||||
old_name: Optional[str] = None
|
old_name: Optional[str] = None
|
||||||
event_type = "assigned"
|
event_type = "assigned"
|
||||||
if comp.assigned_to_id is not None:
|
if comp.assigned_to_id is not None or comp.assigned_team:
|
||||||
event_type = "reassigned"
|
event_type = "reassigned"
|
||||||
old_user = db.query(User.name).filter(User.id == comp.assigned_to_id).first()
|
if comp.assigned_to_id is not None:
|
||||||
old_name = old_user[0] if old_user else str(comp.assigned_to_id)
|
old_user = db.query(User.name).filter(User.id == comp.assigned_to_id).first()
|
||||||
|
old_name = old_user[0] if old_user else str(comp.assigned_to_id)
|
||||||
|
if comp.assigned_team:
|
||||||
|
old_name = f"{old_name} ({comp.assigned_team})" if old_name else comp.assigned_team
|
||||||
|
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
comp.assigned_to_id = assignee.id
|
if assignee:
|
||||||
|
comp.assigned_to_id = assignee.id
|
||||||
|
if payload.assigned_team is not None:
|
||||||
|
comp.assigned_team = payload.assigned_team.strip() or None
|
||||||
comp.assigned_at = now
|
comp.assigned_at = now
|
||||||
if comp.call_status == "open":
|
if comp.call_status == "open":
|
||||||
comp.call_status = "in_progress"
|
comp.call_status = "in_progress"
|
||||||
@@ -578,7 +599,7 @@ def assign_complaint(
|
|||||||
complaint_id=comp.id,
|
complaint_id=comp.id,
|
||||||
event_type=event_type,
|
event_type=event_type,
|
||||||
from_value=old_name,
|
from_value=old_name,
|
||||||
to_value=assignee.name,
|
to_value=target_name,
|
||||||
by_user_id=current_user.id,
|
by_user_id=current_user.id,
|
||||||
at=now,
|
at=now,
|
||||||
note=payload.note,
|
note=payload.note,
|
||||||
@@ -589,7 +610,11 @@ def assign_complaint(
|
|||||||
entity_type="complaint",
|
entity_type="complaint",
|
||||||
entity_id=comp.id,
|
entity_id=comp.id,
|
||||||
action=event_type,
|
action=event_type,
|
||||||
changes={"assigned_to_id": assignee.id, "note": payload.note},
|
changes={
|
||||||
|
"assigned_to_id": comp.assigned_to_id,
|
||||||
|
"assigned_team": comp.assigned_team,
|
||||||
|
"note": payload.note,
|
||||||
|
},
|
||||||
user_id=current_user.id,
|
user_id=current_user.id,
|
||||||
)
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile, status
|
||||||
|
from fastapi.responses import StreamingResponse
|
||||||
from sqlalchemy import or_
|
from sqlalchemy import or_
|
||||||
from sqlalchemy.orm import Session, joinedload
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
@@ -21,6 +22,7 @@ from ..schemas.contracts import (
|
|||||||
)
|
)
|
||||||
from ..services.attachment_service import get_attachment_counts
|
from ..services.attachment_service import get_attachment_counts
|
||||||
from ..services.audit import log_audit
|
from ..services.audit import log_audit
|
||||||
|
from ..services.bulk_templates import build_contracts_template_xlsx, process_contracts_import
|
||||||
from ..services.calculations import coverage_status
|
from ..services.calculations import coverage_status
|
||||||
from ..services.permissions import Role
|
from ..services.permissions import Role
|
||||||
from ..services.settings_service import get_setting_value
|
from ..services.settings_service import get_setting_value
|
||||||
@@ -102,6 +104,8 @@ def list_contracts(
|
|||||||
provider_id: Optional[int] = None,
|
provider_id: Optional[int] = None,
|
||||||
contract_type: Optional[ContractType] = None,
|
contract_type: Optional[ContractType] = None,
|
||||||
status_filter: Optional[ContractStatusFilter] = Query(None, alias="status"),
|
status_filter: Optional[ContractStatusFilter] = Query(None, alias="status"),
|
||||||
|
expiry_from: Optional[date] = None,
|
||||||
|
expiry_to: Optional[date] = None,
|
||||||
include_superseded: bool = True,
|
include_superseded: bool = True,
|
||||||
page: int = Query(1, ge=1),
|
page: int = Query(1, ge=1),
|
||||||
page_size: int = Query(200, ge=1, le=500),
|
page_size: int = Query(200, ge=1, le=500),
|
||||||
@@ -133,6 +137,10 @@ def list_contracts(
|
|||||||
query = query.filter(Contract.contract_type == contract_type)
|
query = query.filter(Contract.contract_type == contract_type)
|
||||||
if not include_superseded:
|
if not include_superseded:
|
||||||
query = query.filter(Contract.is_superseded.is_(False))
|
query = query.filter(Contract.is_superseded.is_(False))
|
||||||
|
if expiry_from is not None:
|
||||||
|
query = query.filter(Contract.end_date >= expiry_from)
|
||||||
|
if expiry_to is not None:
|
||||||
|
query = query.filter(Contract.end_date <= expiry_to)
|
||||||
if q and q.strip():
|
if q and q.strip():
|
||||||
like = f"%{q.strip()}%"
|
like = f"%{q.strip()}%"
|
||||||
query = query.filter(
|
query = query.filter(
|
||||||
@@ -187,6 +195,38 @@ def get_contract_history(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/import-template")
|
||||||
|
def download_contracts_import_template(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||||
|
):
|
||||||
|
buf = build_contracts_template_xlsx(db)
|
||||||
|
return StreamingResponse(
|
||||||
|
buf,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": 'attachment; filename="contracts_import_template.xlsx"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/bulk-import")
|
||||||
|
def bulk_import_contracts(
|
||||||
|
file: UploadFile = File(...),
|
||||||
|
dry_run: bool = Query(False),
|
||||||
|
skip_invalid: bool = Query(False),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||||
|
):
|
||||||
|
content = file.file.read()
|
||||||
|
return process_contracts_import(
|
||||||
|
db=db,
|
||||||
|
filename=file.filename or "contracts.xlsx",
|
||||||
|
content=content,
|
||||||
|
user_id=current_user.id,
|
||||||
|
dry_run=dry_run,
|
||||||
|
skip_invalid=skip_invalid,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post("", response_model=ContractOut, status_code=status.HTTP_201_CREATED)
|
@router.post("", response_model=ContractOut, status_code=status.HTTP_201_CREATED)
|
||||||
def create_contract(
|
def create_contract(
|
||||||
payload: ContractCreate,
|
payload: ContractCreate,
|
||||||
@@ -203,6 +243,22 @@ def create_contract(
|
|||||||
if not db.query(Vendor.id).filter(Vendor.id == payload.provider_id).first():
|
if not db.query(Vendor.id).filter(Vendor.id == payload.provider_id).first():
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
||||||
|
|
||||||
|
existing_contract = (
|
||||||
|
db.query(Contract.id)
|
||||||
|
.filter(
|
||||||
|
Contract.asset_id == payload.asset_id,
|
||||||
|
Contract.contract_type == payload.contract_type,
|
||||||
|
Contract.start_date == payload.start_date,
|
||||||
|
Contract.end_date == payload.end_date,
|
||||||
|
)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if existing_contract:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail="A contract with the same asset, type and dates already exists.",
|
||||||
|
)
|
||||||
|
|
||||||
contract = Contract(
|
contract = Contract(
|
||||||
asset_id=payload.asset_id,
|
asset_id=payload.asset_id,
|
||||||
contract_type=payload.contract_type,
|
contract_type=payload.contract_type,
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ from ..services.calculations import (
|
|||||||
coverage_status,
|
coverage_status,
|
||||||
)
|
)
|
||||||
from ..services.permissions import Role
|
from ..services.permissions import Role
|
||||||
|
from ..services.scoping import resolve_department_scope
|
||||||
from ..services.settings_service import get_setting_value
|
from ..services.settings_service import get_setting_value
|
||||||
|
|
||||||
router = APIRouter(prefix="/dashboard", tags=["dashboard"])
|
router = APIRouter(prefix="/dashboard", tags=["dashboard"])
|
||||||
@@ -46,10 +47,53 @@ def get_dashboard_summary(
|
|||||||
today = effective_today(db)
|
today = effective_today(db)
|
||||||
eff_now = effective_now_utc(db)
|
eff_now = effective_now_utc(db)
|
||||||
|
|
||||||
scoped_dept_id: int | None = None
|
scope = resolve_department_scope(current_user)
|
||||||
|
if scope.is_empty:
|
||||||
|
cur_month_start = date(today.year, today.month, 1)
|
||||||
|
months_seq = [add_months(cur_month_start, offset) for offset in range(-5, 1)]
|
||||||
|
return DashboardSummaryOut(
|
||||||
|
department_scope="Unassigned Department",
|
||||||
|
effective_today=today,
|
||||||
|
kpis=DashboardKPIs(
|
||||||
|
total_assets=0,
|
||||||
|
assets_under_repair=0,
|
||||||
|
open_complaints=0,
|
||||||
|
pm_due_this_month=0,
|
||||||
|
calibrations_due=0,
|
||||||
|
contracts_expiring=0,
|
||||||
|
equipment_on_demo=0,
|
||||||
|
),
|
||||||
|
complaints_by_status=[
|
||||||
|
ComplaintsByStatusItem(status="open", count=0),
|
||||||
|
ComplaintsByStatusItem(status="in_progress", count=0),
|
||||||
|
ComplaintsByStatusItem(status="closed", count=0),
|
||||||
|
],
|
||||||
|
complaints_by_department=[],
|
||||||
|
monthly_downtime_trend=[
|
||||||
|
MonthlyDowntimeItem(
|
||||||
|
month=f"{m.year:04d}-{m.month:02d}",
|
||||||
|
label=m.strftime("%b %Y"),
|
||||||
|
downtime_minutes=0,
|
||||||
|
downtime_hours=0.0,
|
||||||
|
)
|
||||||
|
for m in months_seq
|
||||||
|
],
|
||||||
|
pm_planned_vs_completed=[
|
||||||
|
MonthlyPMComparisonItem(
|
||||||
|
month=f"{m.year:04d}-{m.month:02d}",
|
||||||
|
label=m.strftime("%b %Y"),
|
||||||
|
planned=0,
|
||||||
|
completed=0,
|
||||||
|
)
|
||||||
|
for m in months_seq
|
||||||
|
],
|
||||||
|
needs_attention=[],
|
||||||
|
recent_complaints=[],
|
||||||
|
)
|
||||||
|
|
||||||
|
scoped_dept_id: int | None = scope.department_id
|
||||||
dept_scope_name: str | None = None
|
dept_scope_name: str | None = None
|
||||||
if current_user.role == Role.department_user.value:
|
if scoped_dept_id is not None:
|
||||||
scoped_dept_id = current_user.department_id
|
|
||||||
dept_obj = db.query(Department).filter(Department.id == scoped_dept_id).first()
|
dept_obj = db.query(Department).filter(Department.id == scoped_dept_id).first()
|
||||||
dept_scope_name = dept_obj.name if dept_obj else None
|
dept_scope_name = dept_obj.name if dept_obj else None
|
||||||
|
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ def _to_demo_out(
|
|||||||
id=item.id,
|
id=item.id,
|
||||||
name=item.name,
|
name=item.name,
|
||||||
equipment_type=item.equipment_type,
|
equipment_type=item.equipment_type,
|
||||||
|
serial_no=item.serial_no,
|
||||||
supplier_id=item.supplier_id,
|
supplier_id=item.supplier_id,
|
||||||
supplier_name=item.supplier.name if item.supplier else None,
|
supplier_name=item.supplier.name if item.supplier else None,
|
||||||
department_id=item.department_id,
|
department_id=item.department_id,
|
||||||
@@ -160,6 +161,7 @@ def create_demo_equipment(
|
|||||||
item = DemoEquipment(
|
item = DemoEquipment(
|
||||||
name=payload.name.strip(),
|
name=payload.name.strip(),
|
||||||
equipment_type=payload.equipment_type.strip(),
|
equipment_type=payload.equipment_type.strip(),
|
||||||
|
serial_no=payload.serial_no.strip() if payload.serial_no else None,
|
||||||
supplier_id=payload.supplier_id,
|
supplier_id=payload.supplier_id,
|
||||||
department_id=payload.department_id,
|
department_id=payload.department_id,
|
||||||
location_id=payload.location_id,
|
location_id=payload.location_id,
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile, status
|
||||||
from sqlalchemy import or_
|
from fastapi.responses import StreamingResponse
|
||||||
|
from sqlalchemy import func, or_
|
||||||
from sqlalchemy.orm import Session, joinedload
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
from ..core.db import get_db
|
from ..core.db import get_db
|
||||||
@@ -17,6 +18,7 @@ from ..schemas.insurance import (
|
|||||||
)
|
)
|
||||||
from ..services.attachment_service import get_attachment_counts
|
from ..services.attachment_service import get_attachment_counts
|
||||||
from ..services.audit import log_audit
|
from ..services.audit import log_audit
|
||||||
|
from ..services.bulk_templates import build_insurance_template_xlsx, process_insurance_import
|
||||||
from ..services.calculations import coverage_status
|
from ..services.calculations import coverage_status
|
||||||
from ..services.permissions import Role
|
from ..services.permissions import Role
|
||||||
from ..services.settings_service import get_setting_value
|
from ..services.settings_service import get_setting_value
|
||||||
@@ -86,6 +88,8 @@ def list_insurance_policies(
|
|||||||
asset_id: Optional[int] = None,
|
asset_id: Optional[int] = None,
|
||||||
insurer_id: Optional[int] = None,
|
insurer_id: Optional[int] = None,
|
||||||
status_filter: Optional[InsuranceStatusFilter] = Query(None, alias="status"),
|
status_filter: Optional[InsuranceStatusFilter] = Query(None, alias="status"),
|
||||||
|
expiry_from: Optional[date] = None,
|
||||||
|
expiry_to: Optional[date] = None,
|
||||||
page: int = Query(1, ge=1),
|
page: int = Query(1, ge=1),
|
||||||
page_size: int = Query(200, ge=1, le=500),
|
page_size: int = Query(200, ge=1, le=500),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
@@ -112,6 +116,10 @@ def list_insurance_policies(
|
|||||||
query = query.filter(InsurancePolicy.asset_id == asset_id)
|
query = query.filter(InsurancePolicy.asset_id == asset_id)
|
||||||
if insurer_id is not None:
|
if insurer_id is not None:
|
||||||
query = query.filter(InsurancePolicy.insurer_id == insurer_id)
|
query = query.filter(InsurancePolicy.insurer_id == insurer_id)
|
||||||
|
if expiry_from is not None:
|
||||||
|
query = query.filter(InsurancePolicy.end_date >= expiry_from)
|
||||||
|
if expiry_to is not None:
|
||||||
|
query = query.filter(InsurancePolicy.end_date <= expiry_to)
|
||||||
if q and q.strip():
|
if q and q.strip():
|
||||||
like = f"%{q.strip()}%"
|
like = f"%{q.strip()}%"
|
||||||
query = query.filter(
|
query = query.filter(
|
||||||
@@ -136,6 +144,38 @@ def list_insurance_policies(
|
|||||||
return InsuranceListOut(items=items_all[start : start + page_size], total=total)
|
return InsuranceListOut(items=items_all[start : start + page_size], total=total)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/import-template")
|
||||||
|
def download_insurance_import_template(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||||
|
):
|
||||||
|
buf = build_insurance_template_xlsx(db)
|
||||||
|
return StreamingResponse(
|
||||||
|
buf,
|
||||||
|
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
headers={"Content-Disposition": 'attachment; filename="insurance_import_template.xlsx"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/bulk-import")
|
||||||
|
def bulk_import_insurance(
|
||||||
|
file: UploadFile = File(...),
|
||||||
|
dry_run: bool = Query(False),
|
||||||
|
skip_invalid: bool = Query(False),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||||
|
):
|
||||||
|
content = file.file.read()
|
||||||
|
return process_insurance_import(
|
||||||
|
db=db,
|
||||||
|
filename=file.filename or "insurance.xlsx",
|
||||||
|
content=content,
|
||||||
|
user_id=current_user.id,
|
||||||
|
dry_run=dry_run,
|
||||||
|
skip_invalid=skip_invalid,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@router.post("", response_model=InsuranceOut, status_code=status.HTTP_201_CREATED)
|
@router.post("", response_model=InsuranceOut, status_code=status.HTTP_201_CREATED)
|
||||||
def create_insurance_policy(
|
def create_insurance_policy(
|
||||||
payload: InsuranceCreate,
|
payload: InsuranceCreate,
|
||||||
@@ -160,6 +200,17 @@ def create_insurance_policy(
|
|||||||
detail="policy_no cannot be blank.",
|
detail="policy_no cannot be blank.",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
existing_policy = (
|
||||||
|
db.query(InsurancePolicy.id)
|
||||||
|
.filter(func.lower(func.trim(InsurancePolicy.policy_no)) == clean_policy_no.lower())
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if existing_policy:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail="Policy number already exists.",
|
||||||
|
)
|
||||||
|
|
||||||
asset.insurance_applicable = True
|
asset.insurance_applicable = True
|
||||||
pol = InsurancePolicy(
|
pol = InsurancePolicy(
|
||||||
asset_id=payload.asset_id,
|
asset_id=payload.asset_id,
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ from ..core.db import get_db
|
|||||||
from ..core.deps import get_current_user
|
from ..core.deps import get_current_user
|
||||||
from ..models import Asset, Complaint, User
|
from ..models import Asset, Complaint, User
|
||||||
from ..services.permissions import Role
|
from ..services.permissions import Role
|
||||||
|
from ..services.scoping import resolve_department_scope
|
||||||
|
|
||||||
router = APIRouter(prefix="/search", tags=["search"])
|
router = APIRouter(prefix="/search", tags=["search"])
|
||||||
|
|
||||||
@@ -20,8 +21,11 @@ def global_search(
|
|||||||
if not term:
|
if not term:
|
||||||
return {"assets": [], "complaints": []}
|
return {"assets": [], "complaints": []}
|
||||||
|
|
||||||
|
scope = resolve_department_scope(current_user)
|
||||||
|
if scope.is_empty:
|
||||||
|
return {"assets": [], "complaints": []}
|
||||||
|
|
||||||
pattern = f"%{term}%"
|
pattern = f"%{term}%"
|
||||||
is_dept_scoped = current_user.role == Role.department_user.value
|
|
||||||
|
|
||||||
asset_q = db.query(Asset).options(joinedload(Asset.department)).filter(
|
asset_q = db.query(Asset).options(joinedload(Asset.department)).filter(
|
||||||
or_(
|
or_(
|
||||||
@@ -30,8 +34,8 @@ def global_search(
|
|||||||
Asset.serial_no.ilike(pattern),
|
Asset.serial_no.ilike(pattern),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if is_dept_scoped:
|
if scope.department_id is not None:
|
||||||
asset_q = asset_q.filter(Asset.department_id == current_user.department_id)
|
asset_q = asset_q.filter(Asset.department_id == scope.department_id)
|
||||||
assets = asset_q.order_by(Asset.asset_code.asc()).limit(8).all()
|
assets = asset_q.order_by(Asset.asset_code.asc()).limit(8).all()
|
||||||
|
|
||||||
complaint_q = (
|
complaint_q = (
|
||||||
@@ -47,8 +51,8 @@ def global_search(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if is_dept_scoped:
|
if scope.department_id is not None:
|
||||||
complaint_q = complaint_q.filter(Asset.department_id == current_user.department_id)
|
complaint_q = complaint_q.filter(Asset.department_id == scope.department_id)
|
||||||
complaints = (
|
complaints = (
|
||||||
complaint_q.order_by(Complaint.registered_at.desc(), Complaint.id.desc())
|
complaint_q.order_by(Complaint.registered_at.desc(), Complaint.id.desc())
|
||||||
.limit(8)
|
.limit(8)
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
from typing import Optional
|
from typing import Optional
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
from sqlalchemy import or_
|
from sqlalchemy import or_
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
from sqlalchemy.orm import Session, joinedload
|
from sqlalchemy.orm import Session, joinedload
|
||||||
from ..core.db import get_db
|
from ..core.db import get_db
|
||||||
from ..core.deps import get_current_user, require_roles
|
from ..core.deps import get_current_user, require_roles
|
||||||
from ..core.security import hash_password
|
from ..core.security import hash_password, validate_password
|
||||||
from ..models.masters import Department, User
|
from ..models.masters import Department, User
|
||||||
from ..schemas.masters import (
|
from ..schemas.masters import (
|
||||||
PaginatedOut,
|
PaginatedOut,
|
||||||
@@ -19,6 +20,10 @@ from ..services.permissions import Role
|
|||||||
router = APIRouter(prefix="/users", tags=["users"])
|
router = APIRouter(prefix="/users", tags=["users"])
|
||||||
|
|
||||||
|
|
||||||
|
class ResetPasswordRequest(BaseModel):
|
||||||
|
new_password: str = Field(..., max_length=128)
|
||||||
|
|
||||||
|
|
||||||
def _user_list_out(user: User) -> UserListOut:
|
def _user_list_out(user: User) -> UserListOut:
|
||||||
return UserListOut(
|
return UserListOut(
|
||||||
id=user.id,
|
id=user.id,
|
||||||
@@ -77,11 +82,19 @@ def create_user(
|
|||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
_: User = Depends(require_roles(Role.system_admin)),
|
_: User = Depends(require_roles(Role.system_admin)),
|
||||||
):
|
):
|
||||||
|
if payload.role == "department_user" and payload.department_id is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="Department is required for department_user role.",
|
||||||
|
)
|
||||||
|
|
||||||
if payload.department_id is not None:
|
if payload.department_id is not None:
|
||||||
dept = db.query(Department).filter(Department.id == payload.department_id).first()
|
dept = db.query(Department).filter(Department.id == payload.department_id).first()
|
||||||
if dept is None:
|
if dept is None:
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||||
|
|
||||||
|
validate_password(payload.password, email=payload.email)
|
||||||
|
|
||||||
user = User(
|
user = User(
|
||||||
name=payload.name.strip(),
|
name=payload.name.strip(),
|
||||||
email=payload.email.strip().lower(),
|
email=payload.email.strip().lower(),
|
||||||
@@ -108,13 +121,52 @@ def update_user(
|
|||||||
user_id: int,
|
user_id: int,
|
||||||
payload: UserUpdate,
|
payload: UserUpdate,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
_: User = Depends(require_roles(Role.system_admin)),
|
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||||
):
|
):
|
||||||
user = db.query(User).options(joinedload(User.department)).filter(User.id == user_id).first()
|
user = db.query(User).options(joinedload(User.department)).filter(User.id == user_id).first()
|
||||||
if user is None:
|
if user is None:
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||||
|
|
||||||
data = payload.model_dump(exclude_unset=True)
|
data = payload.model_dump(exclude_unset=True)
|
||||||
|
|
||||||
|
# Department user validation
|
||||||
|
target_role = data.get("role", user.role)
|
||||||
|
target_dept = data.get("department_id", user.department_id)
|
||||||
|
if target_role == "department_user" and target_dept is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||||
|
detail="Department is required for department_user role.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Prevent self-deactivation or changing own admin role
|
||||||
|
if user.id == current_user.id:
|
||||||
|
if "is_active" in data and not data["is_active"]:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Cannot deactivate your own administrator account.",
|
||||||
|
)
|
||||||
|
if "role" in data and data["role"] != "system_admin":
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Cannot change the role of your own administrator account.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Prevent deactivating or demoting the last active system admin
|
||||||
|
if user.role == "system_admin" and (
|
||||||
|
("is_active" in data and not data["is_active"])
|
||||||
|
or ("role" in data and data["role"] != "system_admin")
|
||||||
|
):
|
||||||
|
active_admins = (
|
||||||
|
db.query(User)
|
||||||
|
.filter(User.role == "system_admin", User.is_active.is_(True), User.id != user.id)
|
||||||
|
.count()
|
||||||
|
)
|
||||||
|
if active_admins == 0:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Cannot deactivate or change role: system must have at least one active system administrator.",
|
||||||
|
)
|
||||||
|
|
||||||
if "department_id" in data and data["department_id"] is not None:
|
if "department_id" in data and data["department_id"] is not None:
|
||||||
dept = db.query(Department).filter(Department.id == data["department_id"]).first()
|
dept = db.query(Department).filter(Department.id == data["department_id"]).first()
|
||||||
if dept is None:
|
if dept is None:
|
||||||
@@ -125,13 +177,10 @@ def update_user(
|
|||||||
data["email"] = data["email"].strip().lower()
|
data["email"] = data["email"].strip().lower()
|
||||||
|
|
||||||
password = data.pop("password", None)
|
password = data.pop("password", None)
|
||||||
if password is not None and password.strip():
|
if password is not None and password != "":
|
||||||
if len(password) < 4:
|
validate_password(password, email=data.get("email", user.email))
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
||||||
detail="Password must be at least 4 characters.",
|
|
||||||
)
|
|
||||||
user.password_hash = hash_password(password)
|
user.password_hash = hash_password(password)
|
||||||
|
user.token_version = (user.token_version or 0) + 1
|
||||||
|
|
||||||
for k, v in data.items():
|
for k, v in data.items():
|
||||||
setattr(user, k, v)
|
setattr(user, k, v)
|
||||||
@@ -153,12 +202,48 @@ def update_user(
|
|||||||
def delete_user(
|
def delete_user(
|
||||||
user_id: int,
|
user_id: int,
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
_: User = Depends(require_roles(Role.system_admin)),
|
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||||
):
|
):
|
||||||
|
if user_id == current_user.id:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Cannot delete your own administrator account.",
|
||||||
|
)
|
||||||
|
|
||||||
user = db.query(User).options(joinedload(User.department)).filter(User.id == user_id).first()
|
user = db.query(User).options(joinedload(User.department)).filter(User.id == user_id).first()
|
||||||
if user is None:
|
if user is None:
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||||
|
|
||||||
|
if user.role == "system_admin":
|
||||||
|
active_admins = (
|
||||||
|
db.query(User)
|
||||||
|
.filter(User.role == "system_admin", User.is_active.is_(True), User.id != user.id)
|
||||||
|
.count()
|
||||||
|
)
|
||||||
|
if active_admins == 0:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail="Cannot delete the only active system administrator account.",
|
||||||
|
)
|
||||||
|
|
||||||
user.is_active = False
|
user.is_active = False
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(user)
|
db.refresh(user)
|
||||||
return _user_list_out(user)
|
return _user_list_out(user)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{user_id}/reset-password")
|
||||||
|
def reset_user_password(
|
||||||
|
user_id: int,
|
||||||
|
payload: ResetPasswordRequest,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
_: User = Depends(require_roles(Role.system_admin)),
|
||||||
|
):
|
||||||
|
user = db.query(User).filter(User.id == user_id).first()
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||||
|
validate_password(payload.new_password, email=user.email)
|
||||||
|
user.password_hash = hash_password(payload.new_password)
|
||||||
|
user.token_version = (user.token_version or 0) + 1
|
||||||
|
db.commit()
|
||||||
|
return {"message": f"Password for {user.name} has been reset successfully."}
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ def _to_visit_out(v: DepartmentVisit) -> VisitOut:
|
|||||||
visited_by_name=v.visited_by.name if v.visited_by else None,
|
visited_by_name=v.visited_by.name if v.visited_by else None,
|
||||||
visit_date=v.visit_date,
|
visit_date=v.visit_date,
|
||||||
observations=v.observations,
|
observations=v.observations,
|
||||||
|
new_requirements=v.new_requirements,
|
||||||
assets=[
|
assets=[
|
||||||
VisitAssetSummary(id=a.id, asset_code=a.asset_code, name=a.name)
|
VisitAssetSummary(id=a.id, asset_code=a.asset_code, name=a.name)
|
||||||
for a in v.assets
|
for a in v.assets
|
||||||
@@ -198,6 +199,7 @@ def create_visit(
|
|||||||
visited_by_id=visited_by_id,
|
visited_by_id=visited_by_id,
|
||||||
visit_date=payload.visit_date,
|
visit_date=payload.visit_date,
|
||||||
observations=clean_obs,
|
observations=clean_obs,
|
||||||
|
new_requirements=payload.new_requirements.strip() if payload.new_requirements else None,
|
||||||
created_by_id=current_user.id,
|
created_by_id=current_user.id,
|
||||||
updated_by_id=current_user.id,
|
updated_by_id=current_user.id,
|
||||||
)
|
)
|
||||||
@@ -254,6 +256,9 @@ def update_visit(
|
|||||||
detail="observations cannot be blank.",
|
detail="observations cannot be blank.",
|
||||||
)
|
)
|
||||||
visit.observations = clean_obs
|
visit.observations = clean_obs
|
||||||
|
if "new_requirements" in data:
|
||||||
|
req = data["new_requirements"]
|
||||||
|
visit.new_requirements = req.strip() if isinstance(req, str) and req.strip() else None
|
||||||
|
|
||||||
assets_list, complaints_list = _resolve_assets_and_complaints(
|
assets_list, complaints_list = _resolve_assets_and_complaints(
|
||||||
db,
|
db,
|
||||||
|
|||||||
@@ -84,6 +84,8 @@ def list_warranties(
|
|||||||
department_id: Optional[int] = None,
|
department_id: Optional[int] = None,
|
||||||
asset_id: Optional[int] = None,
|
asset_id: Optional[int] = None,
|
||||||
status_filter: Optional[CoverageStatusFilter] = Query(None, alias="status"),
|
status_filter: Optional[CoverageStatusFilter] = Query(None, alias="status"),
|
||||||
|
expiry_from: Optional[date] = None,
|
||||||
|
expiry_to: Optional[date] = None,
|
||||||
page: int = Query(1, ge=1),
|
page: int = Query(1, ge=1),
|
||||||
page_size: int = Query(200, ge=1, le=500),
|
page_size: int = Query(200, ge=1, le=500),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
@@ -108,6 +110,10 @@ def list_warranties(
|
|||||||
|
|
||||||
if asset_id is not None:
|
if asset_id is not None:
|
||||||
query = query.filter(Warranty.asset_id == asset_id)
|
query = query.filter(Warranty.asset_id == asset_id)
|
||||||
|
if expiry_from is not None:
|
||||||
|
query = query.filter(Warranty.end_date >= expiry_from)
|
||||||
|
if expiry_to is not None:
|
||||||
|
query = query.filter(Warranty.end_date <= expiry_to)
|
||||||
if q and q.strip():
|
if q and q.strip():
|
||||||
like = f"%{q.strip()}%"
|
like = f"%{q.strip()}%"
|
||||||
query = query.filter(
|
query = query.filter(
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ class ComplaintCreate(BaseModel):
|
|||||||
breakdown_details: Optional[str] = None
|
breakdown_details: Optional[str] = None
|
||||||
priority: ComplaintPriority = "non_critical"
|
priority: ComplaintPriority = "non_critical"
|
||||||
notes: Optional[str] = None
|
notes: Optional[str] = None
|
||||||
|
assigned_team: Optional[str] = None
|
||||||
received_by_id: Optional[int] = None
|
received_by_id: Optional[int] = None
|
||||||
received_at: Optional[datetime] = None
|
received_at: Optional[datetime] = None
|
||||||
|
|
||||||
@@ -28,6 +29,7 @@ class ComplaintUpdate(BaseModel):
|
|||||||
breakdown_details: Optional[str] = None
|
breakdown_details: Optional[str] = None
|
||||||
priority: Optional[ComplaintPriority] = None
|
priority: Optional[ComplaintPriority] = None
|
||||||
notes: Optional[str] = None
|
notes: Optional[str] = None
|
||||||
|
assigned_team: Optional[str] = None
|
||||||
closure_remarks: Optional[str] = None
|
closure_remarks: Optional[str] = None
|
||||||
# Restricted technical fields (system_admin / biomedical only)
|
# Restricted technical fields (system_admin / biomedical only)
|
||||||
action_taken: Optional[str] = None
|
action_taken: Optional[str] = None
|
||||||
@@ -43,7 +45,8 @@ class ComplaintUpdate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class ComplaintAssignIn(BaseModel):
|
class ComplaintAssignIn(BaseModel):
|
||||||
assigned_to_id: int
|
assigned_to_id: Optional[int] = None
|
||||||
|
assigned_team: Optional[str] = None
|
||||||
note: Optional[str] = None
|
note: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
@@ -94,6 +97,7 @@ class ComplaintOut(BaseModel):
|
|||||||
received_at: Optional[datetime] = None
|
received_at: Optional[datetime] = None
|
||||||
assigned_to_id: Optional[int] = None
|
assigned_to_id: Optional[int] = None
|
||||||
assigned_to_name: Optional[str] = None
|
assigned_to_name: Optional[str] = None
|
||||||
|
assigned_team: Optional[str] = None
|
||||||
assigned_at: Optional[datetime] = None
|
assigned_at: Optional[datetime] = None
|
||||||
attended_by_id: Optional[int] = None
|
attended_by_id: Optional[int] = None
|
||||||
attended_by_name: Optional[str] = None
|
attended_by_name: Optional[str] = None
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ DemoStatusFilter = Literal["on_demo", "overdue_return", "returned"]
|
|||||||
class DemoEquipmentCreate(BaseModel):
|
class DemoEquipmentCreate(BaseModel):
|
||||||
name: str = Field(..., min_length=1)
|
name: str = Field(..., min_length=1)
|
||||||
equipment_type: str = Field(..., min_length=1)
|
equipment_type: str = Field(..., min_length=1)
|
||||||
|
serial_no: Optional[str] = None
|
||||||
supplier_id: int
|
supplier_id: int
|
||||||
department_id: int
|
department_id: int
|
||||||
location_id: Optional[int] = None
|
location_id: Optional[int] = None
|
||||||
@@ -19,6 +20,7 @@ class DemoEquipmentCreate(BaseModel):
|
|||||||
class DemoEquipmentUpdate(BaseModel):
|
class DemoEquipmentUpdate(BaseModel):
|
||||||
name: Optional[str] = Field(None, min_length=1)
|
name: Optional[str] = Field(None, min_length=1)
|
||||||
equipment_type: Optional[str] = Field(None, min_length=1)
|
equipment_type: Optional[str] = Field(None, min_length=1)
|
||||||
|
serial_no: Optional[str] = None
|
||||||
supplier_id: Optional[int] = None
|
supplier_id: Optional[int] = None
|
||||||
department_id: Optional[int] = None
|
department_id: Optional[int] = None
|
||||||
location_id: Optional[int] = None
|
location_id: Optional[int] = None
|
||||||
@@ -39,6 +41,7 @@ class DemoEquipmentOut(BaseModel):
|
|||||||
id: int
|
id: int
|
||||||
name: str
|
name: str
|
||||||
equipment_type: str
|
equipment_type: str
|
||||||
|
serial_no: Optional[str] = None
|
||||||
supplier_id: int
|
supplier_id: int
|
||||||
supplier_name: Optional[str] = None
|
supplier_name: Optional[str] = None
|
||||||
department_id: int
|
department_id: int
|
||||||
|
|||||||
@@ -123,7 +123,7 @@ class VendorOut(BaseModel):
|
|||||||
class UserCreate(BaseModel):
|
class UserCreate(BaseModel):
|
||||||
name: str = Field(..., min_length=1, max_length=150)
|
name: str = Field(..., min_length=1, max_length=150)
|
||||||
email: str = Field(..., min_length=3, max_length=200)
|
email: str = Field(..., min_length=3, max_length=200)
|
||||||
password: str = Field(..., min_length=4, max_length=128)
|
password: str = Field(..., max_length=128)
|
||||||
role: UserRole
|
role: UserRole
|
||||||
department_id: Optional[int] = None
|
department_id: Optional[int] = None
|
||||||
is_active: bool = True
|
is_active: bool = True
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ class VisitCreate(BaseModel):
|
|||||||
department_id: int
|
department_id: int
|
||||||
visit_date: date
|
visit_date: date
|
||||||
observations: str = Field(..., min_length=1)
|
observations: str = Field(..., min_length=1)
|
||||||
|
new_requirements: Optional[str] = None
|
||||||
asset_ids: list[int] = Field(default_factory=list)
|
asset_ids: list[int] = Field(default_factory=list)
|
||||||
complaint_ids: list[int] = Field(default_factory=list)
|
complaint_ids: list[int] = Field(default_factory=list)
|
||||||
visited_by_id: Optional[int] = None
|
visited_by_id: Optional[int] = None
|
||||||
@@ -30,6 +31,7 @@ class VisitUpdate(BaseModel):
|
|||||||
department_id: Optional[int] = None
|
department_id: Optional[int] = None
|
||||||
visit_date: Optional[date] = None
|
visit_date: Optional[date] = None
|
||||||
observations: Optional[str] = Field(None, min_length=1)
|
observations: Optional[str] = Field(None, min_length=1)
|
||||||
|
new_requirements: Optional[str] = None
|
||||||
asset_ids: Optional[list[int]] = None
|
asset_ids: Optional[list[int]] = None
|
||||||
complaint_ids: Optional[list[int]] = None
|
complaint_ids: Optional[list[int]] = None
|
||||||
|
|
||||||
@@ -48,6 +50,7 @@ class VisitOut(BaseModel):
|
|||||||
visited_by_name: Optional[str] = None
|
visited_by_name: Optional[str] = None
|
||||||
visit_date: date
|
visit_date: date
|
||||||
observations: Optional[str] = None
|
observations: Optional[str] = None
|
||||||
|
new_requirements: Optional[str] = None
|
||||||
assets: list[VisitAssetSummary] = Field(default_factory=list)
|
assets: list[VisitAssetSummary] = Field(default_factory=list)
|
||||||
complaints: list[VisitComplaintSummary] = Field(default_factory=list)
|
complaints: list[VisitComplaintSummary] = Field(default_factory=list)
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
|
|||||||
@@ -278,11 +278,15 @@ def run_alert_check(db: Session) -> dict[str, object]:
|
|||||||
created_at=eff_now,
|
created_at=eff_now,
|
||||||
)
|
)
|
||||||
|
|
||||||
# 7. Critical complaints open >= escalation_open_complaint_hours
|
# 7. Critical complaints open >= escalation_open_complaint_hours (and not yet restored)
|
||||||
crit_complaints = (
|
crit_complaints = (
|
||||||
db.query(Complaint)
|
db.query(Complaint)
|
||||||
.options(joinedload(Complaint.asset))
|
.options(joinedload(Complaint.asset))
|
||||||
.filter(Complaint.call_status != "closed", Complaint.priority == "critical")
|
.filter(
|
||||||
|
Complaint.call_status != "closed",
|
||||||
|
Complaint.priority == "critical",
|
||||||
|
Complaint.restored_at.is_(None),
|
||||||
|
)
|
||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
threshold_secs = cfg["critical_hours"] * 3600
|
threshold_secs = cfg["critical_hours"] * 3600
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import csv
|
import csv
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime, timedelta
|
||||||
from io import BytesIO, StringIO
|
from io import BytesIO, StringIO
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import openpyxl
|
import openpyxl
|
||||||
from openpyxl.styles import Font, PatternFill
|
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||||
from openpyxl.utils import get_column_letter
|
from openpyxl.utils import get_column_letter
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
@@ -36,7 +37,13 @@ VALID_STATUSES = ("in_service", "under_repair", "out_of_service", "condemned")
|
|||||||
VALID_CRITICALITIES = ("critical", "non_critical")
|
VALID_CRITICALITIES = ("critical", "non_critical")
|
||||||
|
|
||||||
_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||||
_HEADER_FONT = Font(color="FFFFFF", bold=True)
|
_HEADER_FONT = Font(name="Calibri", size=11, color="FFFFFF", bold=True)
|
||||||
|
_HEADER_BORDER = Border(
|
||||||
|
left=Side(style="thin", color="334155"),
|
||||||
|
right=Side(style="thin", color="334155"),
|
||||||
|
top=Side(style="thin", color="334155"),
|
||||||
|
bottom=Side(style="medium", color="0F172A"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _auto_fit_columns(ws, max_width: int = 42) -> None:
|
def _auto_fit_columns(ws, max_width: int = 42) -> None:
|
||||||
@@ -58,6 +65,11 @@ def build_import_template_xlsx(db: Session) -> BytesIO:
|
|||||||
cell = ws.cell(row=1, column=col_idx, value=col_name)
|
cell = ws.cell(row=1, column=col_idx, value=col_name)
|
||||||
cell.fill = _HEADER_FILL
|
cell.fill = _HEADER_FILL
|
||||||
cell.font = _HEADER_FONT
|
cell.font = _HEADER_FONT
|
||||||
|
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||||
|
cell.border = _HEADER_BORDER
|
||||||
|
ws.row_dimensions[1].height = 26
|
||||||
|
ws.views.sheetView[0].showGridLines = True
|
||||||
|
ws.auto_filter.ref = f"A1:{get_column_letter(len(IMPORT_COLUMNS))}1"
|
||||||
ws.freeze_panes = "A2"
|
ws.freeze_panes = "A2"
|
||||||
|
|
||||||
departments = (
|
departments = (
|
||||||
@@ -113,12 +125,20 @@ def build_import_template_xlsx(db: Session) -> BytesIO:
|
|||||||
"false",
|
"false",
|
||||||
"Sample row - replace or remove before import",
|
"Sample row - replace or remove before import",
|
||||||
]
|
]
|
||||||
for col_idx, val in enumerate(sample_row, start=1):
|
|
||||||
ws.cell(row=2, column=col_idx, value=val)
|
|
||||||
_auto_fit_columns(ws)
|
_auto_fit_columns(ws)
|
||||||
|
|
||||||
# Sheet 2: Master Reference
|
# Sheet 2: Example
|
||||||
|
ws_ex = wb.create_sheet(title="Example")
|
||||||
|
ws_ex.views.sheetView[0].showGridLines = True
|
||||||
|
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||||
|
for col_idx, val in enumerate(sample_row, start=1):
|
||||||
|
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||||
|
_auto_fit_columns(ws_ex)
|
||||||
|
|
||||||
|
# Sheet 3: Master Reference
|
||||||
ref = wb.create_sheet(title="Master Reference")
|
ref = wb.create_sheet(title="Master Reference")
|
||||||
|
ref.row_dimensions[1].height = 26
|
||||||
|
ref.views.sheetView[0].showGridLines = True
|
||||||
headers_map = [
|
headers_map = [
|
||||||
(1, "Department Code"),
|
(1, "Department Code"),
|
||||||
(2, "Department Name"),
|
(2, "Department Name"),
|
||||||
@@ -133,6 +153,8 @@ def build_import_template_xlsx(db: Session) -> BytesIO:
|
|||||||
c = ref.cell(row=1, column=col_idx, value=label)
|
c = ref.cell(row=1, column=col_idx, value=label)
|
||||||
c.fill = _HEADER_FILL
|
c.fill = _HEADER_FILL
|
||||||
c.font = _HEADER_FONT
|
c.font = _HEADER_FONT
|
||||||
|
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||||
|
c.border = _HEADER_BORDER
|
||||||
ref.freeze_panes = "A2"
|
ref.freeze_panes = "A2"
|
||||||
|
|
||||||
dept_by_id = {d.id: d for d in departments}
|
dept_by_id = {d.id: d for d in departments}
|
||||||
@@ -168,6 +190,8 @@ def build_import_template_xlsx(db: Session) -> BytesIO:
|
|||||||
def _clean_str(val: Any) -> str:
|
def _clean_str(val: Any) -> str:
|
||||||
if val is None:
|
if val is None:
|
||||||
return ""
|
return ""
|
||||||
|
if isinstance(val, float) and val.is_integer():
|
||||||
|
return str(int(val))
|
||||||
return str(val).strip()
|
return str(val).strip()
|
||||||
|
|
||||||
|
|
||||||
@@ -178,8 +202,22 @@ def _parse_optional_date(val: Any, field_name: str) -> tuple[date | None, str |
|
|||||||
return val.date(), None
|
return val.date(), None
|
||||||
if isinstance(val, date):
|
if isinstance(val, date):
|
||||||
return val, None
|
return val, None
|
||||||
|
if isinstance(val, (int, float)) and 20000 <= val <= 80000:
|
||||||
|
try:
|
||||||
|
return (datetime(1899, 12, 30) + timedelta(days=int(val))).date(), None
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
text = str(val).strip()
|
text = str(val).strip()
|
||||||
for fmt in ("%Y-%m-%d", "%d-%b-%Y"):
|
for fmt in (
|
||||||
|
"%Y-%m-%d",
|
||||||
|
"%d-%b-%Y",
|
||||||
|
"%d/%m/%Y",
|
||||||
|
"%m/%d/%Y",
|
||||||
|
"%Y/%m/%d",
|
||||||
|
"%d-%m-%Y",
|
||||||
|
"%d.%m.%Y",
|
||||||
|
"%d %b %Y",
|
||||||
|
):
|
||||||
try:
|
try:
|
||||||
return datetime.strptime(text, fmt).date(), None
|
return datetime.strptime(text, fmt).date(), None
|
||||||
except ValueError:
|
except ValueError:
|
||||||
@@ -205,8 +243,15 @@ def _parse_bool(val: Any, field_name: str) -> tuple[bool, str | None]:
|
|||||||
def _parse_optional_float(val: Any, field_name: str) -> tuple[float | None, str | None]:
|
def _parse_optional_float(val: Any, field_name: str) -> tuple[float | None, str | None]:
|
||||||
if val is None or (isinstance(val, str) and not val.strip()):
|
if val is None or (isinstance(val, str) and not val.strip()):
|
||||||
return None, None
|
return None, None
|
||||||
|
if isinstance(val, (int, float)):
|
||||||
|
if val < 0:
|
||||||
|
return None, f"{field_name} cannot be negative"
|
||||||
|
return float(val), None
|
||||||
|
cleaned = re.sub(r"[₹$,\s]|(?i:rs\.?|inr)", "", str(val).strip())
|
||||||
|
if not cleaned:
|
||||||
|
return None, None
|
||||||
try:
|
try:
|
||||||
parsed = float(val)
|
parsed = float(cleaned)
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
return None, f"Invalid {field_name} '{val}' (must be a number)"
|
return None, f"Invalid {field_name} '{val}' (must be a number)"
|
||||||
if parsed < 0:
|
if parsed < 0:
|
||||||
@@ -233,7 +278,7 @@ def _extract_rows(filename: str, content: bytes) -> list[tuple[int, dict[str, An
|
|||||||
detail="Invalid Excel file. Please download and use the import template.",
|
detail="Invalid Excel file. Please download and use the import template.",
|
||||||
code="INVALID_FILE_TYPE",
|
code="INVALID_FILE_TYPE",
|
||||||
) from exc
|
) from exc
|
||||||
ws = wb["Assets"] if "Assets" in wb.sheetnames else wb.active
|
ws = wb.worksheets[0]
|
||||||
header_cells = next(ws.iter_rows(min_row=1, max_row=1, values_only=True), None)
|
header_cells = next(ws.iter_rows(min_row=1, max_row=1, values_only=True), None)
|
||||||
if not header_cells:
|
if not header_cells:
|
||||||
return []
|
return []
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ from ..models import (
|
|||||||
Contract,
|
Contract,
|
||||||
DemoEquipment,
|
DemoEquipment,
|
||||||
InsurancePolicy,
|
InsurancePolicy,
|
||||||
|
PMRecord,
|
||||||
|
PMSchedule,
|
||||||
User,
|
User,
|
||||||
Warranty,
|
Warranty,
|
||||||
)
|
)
|
||||||
@@ -29,6 +31,7 @@ ALLOWED_ENTITY_TYPES: set[str] = {
|
|||||||
"demo_equipment",
|
"demo_equipment",
|
||||||
"asset",
|
"asset",
|
||||||
"warranty",
|
"warranty",
|
||||||
|
"pm_record",
|
||||||
}
|
}
|
||||||
|
|
||||||
EXT_TO_MIME: dict[str, str] = {
|
EXT_TO_MIME: dict[str, str] = {
|
||||||
@@ -50,6 +53,7 @@ COORDINATOR_UPLOAD_ENTITIES: set[str] = {
|
|||||||
"insurance",
|
"insurance",
|
||||||
"warranty",
|
"warranty",
|
||||||
"demo_equipment",
|
"demo_equipment",
|
||||||
|
"pm_record",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -128,6 +132,17 @@ def resolve_entity_department_id(db: Session, entity_type: str, entity_id: int)
|
|||||||
raise CodedHTTPException(status_code=404, detail="Calibration record not found.", code="NOT_FOUND")
|
raise CodedHTTPException(status_code=404, detail="Calibration record not found.", code="NOT_FOUND")
|
||||||
return obj.asset.department_id
|
return obj.asset.department_id
|
||||||
|
|
||||||
|
if entity_type == "pm_record":
|
||||||
|
obj = (
|
||||||
|
db.query(PMRecord)
|
||||||
|
.options(joinedload(PMRecord.schedule).joinedload(PMSchedule.asset))
|
||||||
|
.filter(PMRecord.id == entity_id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if obj is None:
|
||||||
|
raise CodedHTTPException(status_code=404, detail="PM record not found.", code="NOT_FOUND")
|
||||||
|
return obj.schedule.asset.department_id
|
||||||
|
|
||||||
raise CodedHTTPException(status_code=400, detail="Unsupported entity_type.", code="INVALID_ENTITY_TYPE")
|
raise CodedHTTPException(status_code=400, detail="Unsupported entity_type.", code="INVALID_ENTITY_TYPE")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,986 @@
|
|||||||
|
"""
|
||||||
|
Poona Hospital Asset Management System
|
||||||
|
Bulk Import Template Builders for Contracts, Calibration Plans, and Insurance Policies.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import csv
|
||||||
|
from datetime import date, datetime, timedelta
|
||||||
|
from io import BytesIO, StringIO
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||||
|
from openpyxl.utils import get_column_letter
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..core.exceptions import CodedHTTPException
|
||||||
|
from ..core.time_utils import add_months, effective_today
|
||||||
|
from ..models import (
|
||||||
|
Asset,
|
||||||
|
CalibrationPlan,
|
||||||
|
CalibrationRecord,
|
||||||
|
Contract,
|
||||||
|
Department,
|
||||||
|
InsurancePolicy,
|
||||||
|
Vendor,
|
||||||
|
)
|
||||||
|
from .audit import log_audit
|
||||||
|
from .settings_service import get_setting_value
|
||||||
|
|
||||||
|
_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||||
|
_HEADER_FONT = Font(name="Calibri", size=11, color="FFFFFF", bold=True)
|
||||||
|
_REF_HEADER_FILL = PatternFill(start_color="334155", end_color="334155", fill_type="solid")
|
||||||
|
_HEADER_BORDER = Border(
|
||||||
|
left=Side(style="thin", color="334155"),
|
||||||
|
right=Side(style="thin", color="334155"),
|
||||||
|
top=Side(style="thin", color="334155"),
|
||||||
|
bottom=Side(style="medium", color="0F172A"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _auto_fit_columns(ws, max_width: int = 42) -> None:
|
||||||
|
for col_idx in range(1, ws.max_column + 1):
|
||||||
|
max_len = 0
|
||||||
|
for row_idx in range(1, ws.max_row + 1):
|
||||||
|
val = ws.cell(row=row_idx, column=col_idx).value
|
||||||
|
if val is not None:
|
||||||
|
max_len = max(max_len, len(str(val)))
|
||||||
|
ws.column_dimensions[get_column_letter(col_idx)].width = min(max(max_len + 4, 14), max_width)
|
||||||
|
|
||||||
|
|
||||||
|
def build_contracts_template_xlsx(db: Session) -> BytesIO:
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "Contracts"
|
||||||
|
|
||||||
|
cols = [
|
||||||
|
"asset_code",
|
||||||
|
"provider_name",
|
||||||
|
"contract_type",
|
||||||
|
"start_date",
|
||||||
|
"end_date",
|
||||||
|
"cost",
|
||||||
|
"coverage_details",
|
||||||
|
"remarks",
|
||||||
|
]
|
||||||
|
for col_idx, col_name in enumerate(cols, start=1):
|
||||||
|
c = ws.cell(row=1, column=col_idx, value=col_name)
|
||||||
|
c.fill = _HEADER_FILL
|
||||||
|
c.font = _HEADER_FONT
|
||||||
|
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||||
|
c.border = _HEADER_BORDER
|
||||||
|
ws.row_dimensions[1].height = 26
|
||||||
|
ws.views.sheetView[0].showGridLines = True
|
||||||
|
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||||
|
ws.freeze_panes = "A2"
|
||||||
|
|
||||||
|
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||||
|
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).order_by(Vendor.name).all()
|
||||||
|
|
||||||
|
sample_asset = assets[0] if assets else None
|
||||||
|
sample_vendor = vendors[0] if vendors else None
|
||||||
|
sample_row = [
|
||||||
|
sample_asset.asset_code if sample_asset else "PHRC-ICU-0001",
|
||||||
|
sample_vendor.name if sample_vendor else "Wipro GE Healthcare Pvt Ltd",
|
||||||
|
"CMC",
|
||||||
|
"2026-01-01",
|
||||||
|
"2026-12-31",
|
||||||
|
75000,
|
||||||
|
"Comprehensive maintenance with all spare parts included",
|
||||||
|
"Annual contract renewal",
|
||||||
|
]
|
||||||
|
_auto_fit_columns(ws)
|
||||||
|
|
||||||
|
# Sheet 2: Example
|
||||||
|
ws_ex = wb.create_sheet(title="Example")
|
||||||
|
ws_ex.views.sheetView[0].showGridLines = True
|
||||||
|
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||||
|
for col_idx, val in enumerate(sample_row, start=1):
|
||||||
|
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||||
|
_auto_fit_columns(ws_ex)
|
||||||
|
|
||||||
|
# Sheet 3: Master Reference
|
||||||
|
ws_ref = wb.create_sheet(title="Master Reference")
|
||||||
|
ws_ref.row_dimensions[1].height = 26
|
||||||
|
ws_ref.views.sheetView[0].showGridLines = True
|
||||||
|
ws_ref.cell(row=1, column=1, value="Asset Code").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=1).font = _HEADER_FONT
|
||||||
|
ws_ref.cell(row=1, column=2, value="Asset Name").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=2).font = _HEADER_FONT
|
||||||
|
ws_ref.cell(row=1, column=3, value="Department").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=3).font = _HEADER_FONT
|
||||||
|
|
||||||
|
ws_ref.cell(row=1, column=5, value="Vendor / Provider").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=5).font = _HEADER_FONT
|
||||||
|
|
||||||
|
ws_ref.cell(row=1, column=7, value="Valid Contract Types").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=7).font = _HEADER_FONT
|
||||||
|
|
||||||
|
for r_idx, a in enumerate(assets[:100], start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=1, value=a.asset_code)
|
||||||
|
ws_ref.cell(row=r_idx, column=2, value=a.name)
|
||||||
|
ws_ref.cell(row=r_idx, column=3, value=a.department.name if a.department else "")
|
||||||
|
|
||||||
|
for r_idx, v in enumerate(vendors, start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=5, value=v.name)
|
||||||
|
|
||||||
|
for r_idx, ct in enumerate(["AMC", "CMC", "OTHER"], start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=7, value=ct)
|
||||||
|
|
||||||
|
_auto_fit_columns(ws_ref)
|
||||||
|
buf = BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf
|
||||||
|
|
||||||
|
|
||||||
|
def build_calibration_template_xlsx(db: Session) -> BytesIO:
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "Calibration Plans"
|
||||||
|
|
||||||
|
cols = [
|
||||||
|
"asset_code",
|
||||||
|
"frequency_months",
|
||||||
|
"agency_name",
|
||||||
|
"scope",
|
||||||
|
"standards",
|
||||||
|
"remarks",
|
||||||
|
]
|
||||||
|
for col_idx, col_name in enumerate(cols, start=1):
|
||||||
|
c = ws.cell(row=1, column=col_idx, value=col_name)
|
||||||
|
c.fill = _HEADER_FILL
|
||||||
|
c.font = _HEADER_FONT
|
||||||
|
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||||
|
c.border = _HEADER_BORDER
|
||||||
|
ws.row_dimensions[1].height = 26
|
||||||
|
ws.views.sheetView[0].showGridLines = True
|
||||||
|
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||||
|
ws.freeze_panes = "A2"
|
||||||
|
|
||||||
|
assets = (
|
||||||
|
db.query(Asset)
|
||||||
|
.join(Department)
|
||||||
|
.filter(Asset.status != "condemned", Asset.requires_calibration.is_(True))
|
||||||
|
.order_by(Asset.asset_code)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
if not assets:
|
||||||
|
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||||
|
|
||||||
|
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).order_by(Vendor.name).all()
|
||||||
|
sample_asset = assets[0] if assets else None
|
||||||
|
sample_vendor = vendors[0] if vendors else None
|
||||||
|
|
||||||
|
sample_row = [
|
||||||
|
sample_asset.asset_code if sample_asset else "PHRC-ICU-0001",
|
||||||
|
12,
|
||||||
|
sample_vendor.name if sample_vendor else "National Calibration Laboratory",
|
||||||
|
"Pressure and Flow accuracy verification",
|
||||||
|
"ISO/IEC 17025 accredited",
|
||||||
|
"Annual calibration plan",
|
||||||
|
]
|
||||||
|
_auto_fit_columns(ws)
|
||||||
|
|
||||||
|
# Sheet 2: Example
|
||||||
|
ws_ex = wb.create_sheet(title="Example")
|
||||||
|
ws_ex.views.sheetView[0].showGridLines = True
|
||||||
|
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||||
|
for col_idx, val in enumerate(sample_row, start=1):
|
||||||
|
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||||
|
_auto_fit_columns(ws_ex)
|
||||||
|
|
||||||
|
# Sheet 3: Master Reference
|
||||||
|
ws_ref = wb.create_sheet(title="Master Reference")
|
||||||
|
ws_ref.row_dimensions[1].height = 26
|
||||||
|
ws_ref.views.sheetView[0].showGridLines = True
|
||||||
|
ws_ref.cell(row=1, column=1, value="Asset Code").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=1).font = _HEADER_FONT
|
||||||
|
ws_ref.cell(row=1, column=2, value="Asset Name").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=2).font = _HEADER_FONT
|
||||||
|
ws_ref.cell(row=1, column=3, value="Department").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=3).font = _HEADER_FONT
|
||||||
|
|
||||||
|
ws_ref.cell(row=1, column=5, value="Calibration Agencies").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=5).font = _HEADER_FONT
|
||||||
|
|
||||||
|
ws_ref.cell(row=1, column=7, value="Recommended Frequencies").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=7).font = _HEADER_FONT
|
||||||
|
|
||||||
|
for r_idx, a in enumerate(assets[:100], start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=1, value=a.asset_code)
|
||||||
|
ws_ref.cell(row=r_idx, column=2, value=a.name)
|
||||||
|
ws_ref.cell(row=r_idx, column=3, value=a.department.name if a.department else "")
|
||||||
|
|
||||||
|
for r_idx, v in enumerate(vendors, start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=5, value=v.name)
|
||||||
|
|
||||||
|
for r_idx, freq in enumerate(["3 (Quarterly)", "6 (Semi-Annual)", "12 (Annual)", "24 (Biennial)"], start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=7, value=freq)
|
||||||
|
|
||||||
|
_auto_fit_columns(ws_ref)
|
||||||
|
buf = BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf
|
||||||
|
|
||||||
|
|
||||||
|
def build_insurance_template_xlsx(db: Session) -> BytesIO:
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "Insurance Policies"
|
||||||
|
|
||||||
|
cols = [
|
||||||
|
"asset_code",
|
||||||
|
"insurer_name",
|
||||||
|
"policy_number",
|
||||||
|
"start_date",
|
||||||
|
"end_date",
|
||||||
|
"insured_value",
|
||||||
|
"premium",
|
||||||
|
"remarks",
|
||||||
|
]
|
||||||
|
for col_idx, col_name in enumerate(cols, start=1):
|
||||||
|
c = ws.cell(row=1, column=col_idx, value=col_name)
|
||||||
|
c.fill = _HEADER_FILL
|
||||||
|
c.font = _HEADER_FONT
|
||||||
|
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||||
|
c.border = _HEADER_BORDER
|
||||||
|
ws.row_dimensions[1].height = 26
|
||||||
|
ws.views.sheetView[0].showGridLines = True
|
||||||
|
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||||
|
ws.freeze_panes = "A2"
|
||||||
|
|
||||||
|
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||||
|
sample_asset = assets[0] if assets else None
|
||||||
|
|
||||||
|
sample_row = [
|
||||||
|
sample_asset.asset_code if sample_asset else "PHRC-ICU-0001",
|
||||||
|
"New India Assurance Co. Ltd",
|
||||||
|
"NIA-MH-2026-MED-4412",
|
||||||
|
"2026-04-01",
|
||||||
|
"2027-03-31",
|
||||||
|
1500000,
|
||||||
|
18500,
|
||||||
|
"Annual hospital equipment comprehensive policy",
|
||||||
|
]
|
||||||
|
_auto_fit_columns(ws)
|
||||||
|
|
||||||
|
# Sheet 2: Example
|
||||||
|
ws_ex = wb.create_sheet(title="Example")
|
||||||
|
ws_ex.views.sheetView[0].showGridLines = True
|
||||||
|
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||||
|
for col_idx, val in enumerate(sample_row, start=1):
|
||||||
|
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||||
|
_auto_fit_columns(ws_ex)
|
||||||
|
|
||||||
|
# Sheet 3: Master Reference
|
||||||
|
ws_ref = wb.create_sheet(title="Master Reference")
|
||||||
|
ws_ref.row_dimensions[1].height = 26
|
||||||
|
ws_ref.views.sheetView[0].showGridLines = True
|
||||||
|
ws_ref.cell(row=1, column=1, value="Asset Code").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=1).font = _HEADER_FONT
|
||||||
|
ws_ref.cell(row=1, column=2, value="Asset Name").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=2).font = _HEADER_FONT
|
||||||
|
ws_ref.cell(row=1, column=3, value="Department").fill = _REF_HEADER_FILL
|
||||||
|
ws_ref.cell(row=1, column=3).font = _HEADER_FONT
|
||||||
|
|
||||||
|
for r_idx, a in enumerate(assets[:100], start=2):
|
||||||
|
ws_ref.cell(row=r_idx, column=1, value=a.asset_code)
|
||||||
|
ws_ref.cell(row=r_idx, column=2, value=a.name)
|
||||||
|
ws_ref.cell(row=r_idx, column=3, value=a.department.name if a.department else "")
|
||||||
|
|
||||||
|
_auto_fit_columns(ws_ref)
|
||||||
|
buf = BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_str(val: Any) -> str:
|
||||||
|
if val is None:
|
||||||
|
return ""
|
||||||
|
if isinstance(val, float) and val.is_integer():
|
||||||
|
return str(int(val))
|
||||||
|
return str(val).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_date(val: Any, field_name: str) -> tuple[date | None, str | None]:
|
||||||
|
if val is None or (isinstance(val, str) and not val.strip()):
|
||||||
|
return None, f"Missing required field '{field_name}'"
|
||||||
|
if isinstance(val, datetime):
|
||||||
|
return val.date(), None
|
||||||
|
if isinstance(val, date):
|
||||||
|
return val, None
|
||||||
|
if isinstance(val, (int, float)) and 20000 <= val <= 80000:
|
||||||
|
try:
|
||||||
|
return (datetime(1899, 12, 30) + timedelta(days=int(val))).date(), None
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
text = str(val).strip()
|
||||||
|
for fmt in (
|
||||||
|
"%Y-%m-%d",
|
||||||
|
"%d-%b-%Y",
|
||||||
|
"%d/%m/%Y",
|
||||||
|
"%m/%d/%Y",
|
||||||
|
"%Y/%m/%d",
|
||||||
|
"%d-%m-%Y",
|
||||||
|
"%d.%m.%Y",
|
||||||
|
"%d %b %Y",
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
return datetime.strptime(text, fmt).date(), None
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return None, f"Invalid {field_name} '{text}' (expected YYYY-MM-DD or DD-MMM-YYYY)"
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_optional_float(val: Any, field_name: str) -> tuple[float | None, str | None]:
|
||||||
|
if val is None or (isinstance(val, str) and not val.strip()):
|
||||||
|
return None, None
|
||||||
|
if isinstance(val, (int, float)):
|
||||||
|
if val < 0:
|
||||||
|
return None, f"{field_name} cannot be negative"
|
||||||
|
return float(val), None
|
||||||
|
cleaned = re.sub(r"[₹$,\s]|(?i:rs\.?|inr)", "", str(val).strip())
|
||||||
|
if not cleaned:
|
||||||
|
return None, None
|
||||||
|
try:
|
||||||
|
parsed = float(cleaned)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None, f"Invalid {field_name} '{val}' (must be a number)"
|
||||||
|
if parsed < 0:
|
||||||
|
return None, f"{field_name} cannot be negative"
|
||||||
|
return parsed, None
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_positive_int(val: Any, field_name: str) -> tuple[int | None, str | None]:
|
||||||
|
if val is None or (isinstance(val, str) and not val.strip()):
|
||||||
|
return None, f"Missing required field '{field_name}'"
|
||||||
|
if isinstance(val, (int, float)):
|
||||||
|
parsed = int(val)
|
||||||
|
if parsed <= 0:
|
||||||
|
return None, f"{field_name} must be greater than 0"
|
||||||
|
return parsed, None
|
||||||
|
cleaned = re.sub(r"[,\s]|(?i:months?|yrs?|years?)", "", str(val).strip())
|
||||||
|
try:
|
||||||
|
parsed = int(float(cleaned))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None, f"Invalid {field_name} '{val}' (must be an integer)"
|
||||||
|
if parsed <= 0:
|
||||||
|
return None, f"{field_name} must be greater than 0"
|
||||||
|
return parsed, None
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_rows(filename: str, content: bytes, sheet_name: str | None = None) -> list[tuple[int, dict[str, Any]]]:
|
||||||
|
ext = Path(filename or "").suffix.lower()
|
||||||
|
if ext not in (".xlsx", ".csv", ".xls"):
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Unsupported file type. Please upload an .xlsx or .csv file.",
|
||||||
|
code="INVALID_FILE_TYPE",
|
||||||
|
)
|
||||||
|
|
||||||
|
rows_out: list[tuple[int, dict[str, Any]]] = []
|
||||||
|
if ext in (".xlsx", ".xls"):
|
||||||
|
try:
|
||||||
|
wb = openpyxl.load_workbook(BytesIO(content), data_only=True)
|
||||||
|
except Exception as exc:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Invalid Excel file. Please download and use the import template.",
|
||||||
|
code="INVALID_FILE_TYPE",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
ws = wb.worksheets[0]
|
||||||
|
header_cells = next(ws.iter_rows(min_row=1, max_row=1, values_only=True), None)
|
||||||
|
if not header_cells:
|
||||||
|
return []
|
||||||
|
headers = [_clean_str(h).lower().replace(" ", "_").replace("-", "_") for h in header_cells]
|
||||||
|
for row_idx, row_vals in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2):
|
||||||
|
if all(v is None or _clean_str(v) == "" for v in row_vals):
|
||||||
|
continue
|
||||||
|
row_dict = {
|
||||||
|
headers[i]: (row_vals[i] if i < len(row_vals) else None)
|
||||||
|
for i in range(len(headers))
|
||||||
|
if headers[i]
|
||||||
|
}
|
||||||
|
rows_out.append((row_idx, row_dict))
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
decoded = content.decode("utf-8-sig")
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
decoded = content.decode("latin-1")
|
||||||
|
reader = csv.reader(StringIO(decoded))
|
||||||
|
header_row = next(reader, None)
|
||||||
|
if not header_row:
|
||||||
|
return []
|
||||||
|
headers = [_clean_str(h).lower().replace(" ", "_").replace("-", "_") for h in header_row]
|
||||||
|
for row_idx, row_vals in enumerate(reader, start=2):
|
||||||
|
if all(_clean_str(v) == "" for v in row_vals):
|
||||||
|
continue
|
||||||
|
row_dict = {
|
||||||
|
headers[i]: (row_vals[i] if i < len(row_vals) else None)
|
||||||
|
for i in range(len(headers))
|
||||||
|
if headers[i]
|
||||||
|
}
|
||||||
|
rows_out.append((row_idx, row_dict))
|
||||||
|
return rows_out
|
||||||
|
|
||||||
|
|
||||||
|
def process_contracts_import(
|
||||||
|
db: Session,
|
||||||
|
filename: str,
|
||||||
|
content: bytes,
|
||||||
|
user_id: int,
|
||||||
|
dry_run: bool = False,
|
||||||
|
skip_invalid: bool = False,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
raw_rows = _extract_rows(filename, content, sheet_name="Contracts")
|
||||||
|
|
||||||
|
assets = db.query(Asset).all()
|
||||||
|
asset_lookup: dict[str, Asset] = {a.asset_code.strip().lower(): a for a in assets if a.asset_code}
|
||||||
|
|
||||||
|
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||||
|
vendor_lookup: dict[str, Vendor] = {}
|
||||||
|
for v in vendors:
|
||||||
|
vendor_lookup[v.name.strip().lower()] = v
|
||||||
|
|
||||||
|
existing_contracts = {
|
||||||
|
(c.asset_id, (c.contract_type or "").upper(), c.start_date, c.end_date)
|
||||||
|
for c in db.query(Contract.asset_id, Contract.contract_type, Contract.start_date, Contract.end_date).all()
|
||||||
|
}
|
||||||
|
seen_contracts_in_file: dict[tuple[int, str, date, date], int] = {}
|
||||||
|
|
||||||
|
errors: list[dict[str, Any]] = []
|
||||||
|
preview_rows: list[dict[str, Any]] = []
|
||||||
|
valid_records: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
for row_idx, row_dict in raw_rows:
|
||||||
|
row_errors: list[str] = []
|
||||||
|
|
||||||
|
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||||
|
provider_name = _clean_str(
|
||||||
|
row_dict.get("provider_name")
|
||||||
|
or row_dict.get("vendor_name")
|
||||||
|
or row_dict.get("provider")
|
||||||
|
or row_dict.get("vendor")
|
||||||
|
)
|
||||||
|
contract_type_raw = _clean_str(row_dict.get("contract_type")).upper()
|
||||||
|
start_date_val = row_dict.get("start_date")
|
||||||
|
end_date_val = row_dict.get("end_date")
|
||||||
|
cost_val = row_dict.get("cost")
|
||||||
|
coverage_details = _clean_str(row_dict.get("coverage_details") or row_dict.get("coverage_period_text"))
|
||||||
|
remarks = _clean_str(row_dict.get("remarks"))
|
||||||
|
|
||||||
|
target_asset = None
|
||||||
|
if not asset_code:
|
||||||
|
row_errors.append("Missing required field 'asset_code'")
|
||||||
|
else:
|
||||||
|
target_asset = asset_lookup.get(asset_code.lower())
|
||||||
|
if not target_asset:
|
||||||
|
row_errors.append(f"Asset with code '{asset_code}' not found")
|
||||||
|
|
||||||
|
target_vendor = None
|
||||||
|
if not provider_name:
|
||||||
|
row_errors.append("Missing required field 'provider_name'")
|
||||||
|
else:
|
||||||
|
target_vendor = vendor_lookup.get(provider_name.lower())
|
||||||
|
if not target_vendor:
|
||||||
|
row_errors.append(f"Provider vendor '{provider_name}' not found")
|
||||||
|
|
||||||
|
if not contract_type_raw:
|
||||||
|
row_errors.append("Missing required field 'contract_type'")
|
||||||
|
elif contract_type_raw not in ("AMC", "CMC", "OTHER"):
|
||||||
|
row_errors.append(f"Invalid contract_type '{contract_type_raw}' (expected AMC, CMC, or OTHER)")
|
||||||
|
|
||||||
|
start_date, s_err = _parse_date(start_date_val, "start_date")
|
||||||
|
if s_err:
|
||||||
|
row_errors.append(s_err)
|
||||||
|
|
||||||
|
end_date, e_err = _parse_date(end_date_val, "end_date")
|
||||||
|
if e_err:
|
||||||
|
row_errors.append(e_err)
|
||||||
|
|
||||||
|
if start_date and end_date and end_date < start_date:
|
||||||
|
row_errors.append("end_date cannot be earlier than start_date")
|
||||||
|
|
||||||
|
if target_asset and contract_type_raw in ("AMC", "CMC", "OTHER") and start_date and end_date and end_date >= start_date:
|
||||||
|
key = (target_asset.id, contract_type_raw, start_date, end_date)
|
||||||
|
if key in seen_contracts_in_file:
|
||||||
|
row_errors.append(f"Duplicate of row {seen_contracts_in_file[key]} in this file.")
|
||||||
|
elif key in existing_contracts:
|
||||||
|
row_errors.append("Already exists in the system.")
|
||||||
|
seen_contracts_in_file[key] = row_idx
|
||||||
|
else:
|
||||||
|
seen_contracts_in_file[key] = row_idx
|
||||||
|
|
||||||
|
cost, c_err = _parse_optional_float(cost_val, "cost")
|
||||||
|
if c_err:
|
||||||
|
row_errors.append(c_err)
|
||||||
|
|
||||||
|
is_valid = len(row_errors) == 0
|
||||||
|
err_text = "; ".join(row_errors) if row_errors else None
|
||||||
|
|
||||||
|
if not is_valid:
|
||||||
|
errors.append({"row": row_idx, "message": err_text})
|
||||||
|
else:
|
||||||
|
combined_remarks = remarks
|
||||||
|
if cost is not None and cost > 0:
|
||||||
|
cost_str = f"Cost: ₹{cost:,.2f}"
|
||||||
|
combined_remarks = f"{remarks} ({cost_str})" if remarks else cost_str
|
||||||
|
|
||||||
|
valid_records.append({
|
||||||
|
"asset_id": target_asset.id,
|
||||||
|
"provider_id": target_vendor.id,
|
||||||
|
"contract_type": contract_type_raw,
|
||||||
|
"start_date": start_date,
|
||||||
|
"end_date": end_date,
|
||||||
|
"coverage_period_text": coverage_details or f"{start_date} to {end_date}",
|
||||||
|
"remarks": combined_remarks or None,
|
||||||
|
})
|
||||||
|
|
||||||
|
preview_rows.append({
|
||||||
|
"row": row_idx,
|
||||||
|
"data": {
|
||||||
|
"asset_code": asset_code,
|
||||||
|
"provider_name": provider_name,
|
||||||
|
"contract_type": contract_type_raw,
|
||||||
|
"start_date": str(start_date) if start_date else str(start_date_val or ""),
|
||||||
|
"end_date": str(end_date) if end_date else str(end_date_val or ""),
|
||||||
|
"cost": cost,
|
||||||
|
"coverage_details": coverage_details,
|
||||||
|
"remarks": remarks,
|
||||||
|
},
|
||||||
|
"valid": is_valid,
|
||||||
|
"error": err_text,
|
||||||
|
})
|
||||||
|
|
||||||
|
created_count = 0
|
||||||
|
if not dry_run:
|
||||||
|
if errors and not skip_invalid:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"{len(errors)} row(s) failed validation.",
|
||||||
|
code="IMPORT_VALIDATION_ERRORS",
|
||||||
|
)
|
||||||
|
if valid_records:
|
||||||
|
for item in valid_records:
|
||||||
|
contract = Contract(
|
||||||
|
asset_id=item["asset_id"],
|
||||||
|
provider_id=item["provider_id"],
|
||||||
|
contract_type=item["contract_type"],
|
||||||
|
start_date=item["start_date"],
|
||||||
|
end_date=item["end_date"],
|
||||||
|
coverage_period_text=item["coverage_period_text"],
|
||||||
|
renewed_from_id=None,
|
||||||
|
is_superseded=False,
|
||||||
|
remarks=item["remarks"],
|
||||||
|
created_by_id=user_id,
|
||||||
|
updated_by_id=user_id,
|
||||||
|
)
|
||||||
|
db.add(contract)
|
||||||
|
db.flush()
|
||||||
|
log_audit(
|
||||||
|
db,
|
||||||
|
entity_type="contract",
|
||||||
|
entity_id=contract.id,
|
||||||
|
action="create",
|
||||||
|
changes={
|
||||||
|
"asset_id": item["asset_id"],
|
||||||
|
"contract_type": item["contract_type"],
|
||||||
|
"provider_id": item["provider_id"],
|
||||||
|
"start_date": str(item["start_date"]),
|
||||||
|
"end_date": str(item["end_date"]),
|
||||||
|
"source": "bulk_import",
|
||||||
|
},
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
created_count = len(valid_records)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"dry_run": dry_run,
|
||||||
|
"total_rows": len(raw_rows),
|
||||||
|
"valid_count": len(valid_records),
|
||||||
|
"error_count": len(errors),
|
||||||
|
"created_count": created_count,
|
||||||
|
"errors": errors,
|
||||||
|
"preview_rows": preview_rows,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def process_calibration_import(
|
||||||
|
db: Session,
|
||||||
|
filename: str,
|
||||||
|
content: bytes,
|
||||||
|
user_id: int,
|
||||||
|
dry_run: bool = False,
|
||||||
|
skip_invalid: bool = False,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
raw_rows = _extract_rows(filename, content, sheet_name="Calibration Plans")
|
||||||
|
|
||||||
|
assets = db.query(Asset).all()
|
||||||
|
asset_lookup: dict[str, Asset] = {a.asset_code.strip().lower(): a for a in assets if a.asset_code}
|
||||||
|
|
||||||
|
existing_plan_asset_ids = {p.asset_id for p in db.query(CalibrationPlan.asset_id).all()}
|
||||||
|
seen_asset_ids: dict[int, int] = {}
|
||||||
|
|
||||||
|
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||||
|
vendor_lookup: dict[str, Vendor] = {}
|
||||||
|
for v in vendors:
|
||||||
|
vendor_lookup[v.name.strip().lower()] = v
|
||||||
|
|
||||||
|
today = effective_today(db)
|
||||||
|
|
||||||
|
errors: list[dict[str, Any]] = []
|
||||||
|
preview_rows: list[dict[str, Any]] = []
|
||||||
|
valid_records: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
for row_idx, row_dict in raw_rows:
|
||||||
|
row_errors: list[str] = []
|
||||||
|
|
||||||
|
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||||
|
freq_val = row_dict.get("frequency_months")
|
||||||
|
agency_name = _clean_str(
|
||||||
|
row_dict.get("agency_name")
|
||||||
|
or row_dict.get("vendor_name")
|
||||||
|
or row_dict.get("agency")
|
||||||
|
)
|
||||||
|
next_due_val = row_dict.get("next_due_date")
|
||||||
|
scope = _clean_str(row_dict.get("scope"))
|
||||||
|
standards = _clean_str(row_dict.get("standards"))
|
||||||
|
remarks = _clean_str(row_dict.get("remarks"))
|
||||||
|
|
||||||
|
target_asset = None
|
||||||
|
if not asset_code:
|
||||||
|
row_errors.append("Missing required field 'asset_code'")
|
||||||
|
else:
|
||||||
|
target_asset = asset_lookup.get(asset_code.lower())
|
||||||
|
if not target_asset:
|
||||||
|
row_errors.append(f"Asset with code '{asset_code}' not found")
|
||||||
|
elif target_asset.id in seen_asset_ids:
|
||||||
|
row_errors.append(f"Duplicate of row {seen_asset_ids[target_asset.id]} in this file.")
|
||||||
|
elif target_asset.id in existing_plan_asset_ids:
|
||||||
|
row_errors.append("Asset already has a calibration plan.")
|
||||||
|
seen_asset_ids[target_asset.id] = row_idx
|
||||||
|
else:
|
||||||
|
seen_asset_ids[target_asset.id] = row_idx
|
||||||
|
|
||||||
|
freq_months, f_err = _parse_positive_int(freq_val, "frequency_months")
|
||||||
|
if f_err:
|
||||||
|
row_errors.append(f_err)
|
||||||
|
|
||||||
|
target_agency = None
|
||||||
|
if agency_name:
|
||||||
|
target_agency = vendor_lookup.get(agency_name.lower())
|
||||||
|
if not target_agency:
|
||||||
|
row_errors.append(f"Calibration agency vendor '{agency_name}' not found")
|
||||||
|
|
||||||
|
due_date = None
|
||||||
|
if next_due_val:
|
||||||
|
d_parsed, d_err = _parse_date(next_due_val, "next_due_date")
|
||||||
|
if d_err:
|
||||||
|
row_errors.append(d_err)
|
||||||
|
else:
|
||||||
|
due_date = d_parsed
|
||||||
|
elif freq_months:
|
||||||
|
due_date = add_months(today, freq_months)
|
||||||
|
|
||||||
|
is_valid = len(row_errors) == 0
|
||||||
|
err_text = "; ".join(row_errors) if row_errors else None
|
||||||
|
|
||||||
|
if not is_valid:
|
||||||
|
errors.append({"row": row_idx, "message": err_text})
|
||||||
|
else:
|
||||||
|
valid_records.append({
|
||||||
|
"asset": target_asset,
|
||||||
|
"frequency_months": freq_months,
|
||||||
|
"agency_id": target_agency.id if target_agency else None,
|
||||||
|
"next_due_date": due_date,
|
||||||
|
"remarks": remarks,
|
||||||
|
})
|
||||||
|
|
||||||
|
preview_rows.append({
|
||||||
|
"row": row_idx,
|
||||||
|
"data": {
|
||||||
|
"asset_code": asset_code,
|
||||||
|
"frequency_months": freq_months if freq_months else freq_val,
|
||||||
|
"agency_name": agency_name,
|
||||||
|
"next_due_date": str(due_date) if due_date else str(next_due_val or ""),
|
||||||
|
"scope": scope,
|
||||||
|
"standards": standards,
|
||||||
|
"remarks": remarks,
|
||||||
|
},
|
||||||
|
"valid": is_valid,
|
||||||
|
"error": err_text,
|
||||||
|
})
|
||||||
|
|
||||||
|
created_count = 0
|
||||||
|
if not dry_run:
|
||||||
|
if errors and not skip_invalid:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"{len(errors)} row(s) failed validation.",
|
||||||
|
code="IMPORT_VALIDATION_ERRORS",
|
||||||
|
)
|
||||||
|
if valid_records:
|
||||||
|
for item in valid_records:
|
||||||
|
asset = item["asset"]
|
||||||
|
freq = item["frequency_months"]
|
||||||
|
agency_id = item["agency_id"]
|
||||||
|
due_date = item["next_due_date"]
|
||||||
|
per_year = max(1, round(12 / freq))
|
||||||
|
|
||||||
|
asset.requires_calibration = True
|
||||||
|
asset.updated_by_id = user_id
|
||||||
|
|
||||||
|
plan = CalibrationPlan(
|
||||||
|
asset_id=asset.id,
|
||||||
|
frequency_months=freq,
|
||||||
|
calibrations_per_year=per_year,
|
||||||
|
agency_id=agency_id,
|
||||||
|
approved_by_id=user_id,
|
||||||
|
approved_on=today,
|
||||||
|
next_due_date=due_date,
|
||||||
|
is_active=True,
|
||||||
|
created_by_id=user_id,
|
||||||
|
updated_by_id=user_id,
|
||||||
|
)
|
||||||
|
db.add(plan)
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
initial_rec = CalibrationRecord(
|
||||||
|
asset_id=asset.id,
|
||||||
|
plan_id=plan.id,
|
||||||
|
due_date=due_date,
|
||||||
|
agency_id=agency_id,
|
||||||
|
status=None,
|
||||||
|
created_by_id=user_id,
|
||||||
|
updated_by_id=user_id,
|
||||||
|
)
|
||||||
|
db.add(initial_rec)
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
log_audit(
|
||||||
|
db,
|
||||||
|
entity_type="calibration_plan",
|
||||||
|
entity_id=plan.id,
|
||||||
|
action="create",
|
||||||
|
changes={
|
||||||
|
"asset_id": asset.id,
|
||||||
|
"frequency_months": freq,
|
||||||
|
"calibrations_per_year": per_year,
|
||||||
|
"next_due_date": str(due_date),
|
||||||
|
"approved": True,
|
||||||
|
"initial_record_id": initial_rec.id,
|
||||||
|
"source": "bulk_import",
|
||||||
|
},
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
created_count = len(valid_records)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"dry_run": dry_run,
|
||||||
|
"total_rows": len(raw_rows),
|
||||||
|
"valid_count": len(valid_records),
|
||||||
|
"error_count": len(errors),
|
||||||
|
"created_count": created_count,
|
||||||
|
"errors": errors,
|
||||||
|
"preview_rows": preview_rows,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def process_insurance_import(
|
||||||
|
db: Session,
|
||||||
|
filename: str,
|
||||||
|
content: bytes,
|
||||||
|
user_id: int,
|
||||||
|
dry_run: bool = False,
|
||||||
|
skip_invalid: bool = False,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
raw_rows = _extract_rows(filename, content, sheet_name="Insurance Policies")
|
||||||
|
|
||||||
|
assets = db.query(Asset).all()
|
||||||
|
asset_lookup: dict[str, Asset] = {a.asset_code.strip().lower(): a for a in assets if a.asset_code}
|
||||||
|
|
||||||
|
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||||
|
vendor_lookup: dict[str, Vendor] = {}
|
||||||
|
for v in vendors:
|
||||||
|
vendor_lookup[v.name.strip().lower()] = v
|
||||||
|
|
||||||
|
existing_policies = {
|
||||||
|
p[0].strip().lower()
|
||||||
|
for p in db.query(InsurancePolicy.policy_no).all()
|
||||||
|
if p[0] and p[0].strip()
|
||||||
|
}
|
||||||
|
seen_policies_in_file: dict[str, int] = {}
|
||||||
|
|
||||||
|
errors: list[dict[str, Any]] = []
|
||||||
|
preview_rows: list[dict[str, Any]] = []
|
||||||
|
valid_records: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
for row_idx, row_dict in raw_rows:
|
||||||
|
row_errors: list[str] = []
|
||||||
|
|
||||||
|
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||||
|
insurer_name = _clean_str(
|
||||||
|
row_dict.get("insurer_name")
|
||||||
|
or row_dict.get("vendor_name")
|
||||||
|
or row_dict.get("insurer")
|
||||||
|
or row_dict.get("vendor")
|
||||||
|
)
|
||||||
|
policy_no = _clean_str(
|
||||||
|
row_dict.get("policy_number")
|
||||||
|
or row_dict.get("policy_no")
|
||||||
|
or row_dict.get("policy_num")
|
||||||
|
)
|
||||||
|
start_date_val = row_dict.get("start_date")
|
||||||
|
end_date_val = row_dict.get("end_date")
|
||||||
|
insured_val = row_dict.get("insured_value") or row_dict.get("coverage_amount")
|
||||||
|
premium_val = row_dict.get("premium")
|
||||||
|
remarks = _clean_str(row_dict.get("remarks"))
|
||||||
|
|
||||||
|
target_asset = None
|
||||||
|
if not asset_code:
|
||||||
|
row_errors.append("Missing required field 'asset_code'")
|
||||||
|
else:
|
||||||
|
target_asset = asset_lookup.get(asset_code.lower())
|
||||||
|
if not target_asset:
|
||||||
|
row_errors.append(f"Asset with code '{asset_code}' not found")
|
||||||
|
|
||||||
|
target_vendor = None
|
||||||
|
if not insurer_name:
|
||||||
|
row_errors.append("Missing required field 'insurer_name'")
|
||||||
|
else:
|
||||||
|
target_vendor = vendor_lookup.get(insurer_name.lower())
|
||||||
|
if not target_vendor:
|
||||||
|
row_errors.append(f"Insurer vendor '{insurer_name}' not found")
|
||||||
|
|
||||||
|
if not policy_no:
|
||||||
|
row_errors.append("Missing required field 'policy_number'")
|
||||||
|
else:
|
||||||
|
pol_key = policy_no.strip().lower()
|
||||||
|
if pol_key in seen_policies_in_file:
|
||||||
|
row_errors.append(f"Duplicate of row {seen_policies_in_file[pol_key]} in this file.")
|
||||||
|
elif pol_key in existing_policies:
|
||||||
|
row_errors.append("Already exists in the system.")
|
||||||
|
seen_policies_in_file[pol_key] = row_idx
|
||||||
|
else:
|
||||||
|
seen_policies_in_file[pol_key] = row_idx
|
||||||
|
|
||||||
|
start_date, s_err = _parse_date(start_date_val, "start_date")
|
||||||
|
if s_err:
|
||||||
|
row_errors.append(s_err)
|
||||||
|
|
||||||
|
end_date, e_err = _parse_date(end_date_val, "end_date")
|
||||||
|
if e_err:
|
||||||
|
row_errors.append(e_err)
|
||||||
|
|
||||||
|
if start_date and end_date and end_date < start_date:
|
||||||
|
row_errors.append("end_date cannot be earlier than start_date")
|
||||||
|
|
||||||
|
coverage_amount, ca_err = _parse_optional_float(insured_val, "insured_value")
|
||||||
|
if ca_err:
|
||||||
|
row_errors.append(ca_err)
|
||||||
|
|
||||||
|
premium, p_err = _parse_optional_float(premium_val, "premium")
|
||||||
|
if p_err:
|
||||||
|
row_errors.append(p_err)
|
||||||
|
|
||||||
|
is_valid = len(row_errors) == 0
|
||||||
|
err_text = "; ".join(row_errors) if row_errors else None
|
||||||
|
|
||||||
|
if not is_valid:
|
||||||
|
errors.append({"row": row_idx, "message": err_text})
|
||||||
|
else:
|
||||||
|
combined_remarks = remarks
|
||||||
|
if premium is not None and premium > 0:
|
||||||
|
p_str = f"Premium: ₹{premium:,.2f}"
|
||||||
|
combined_remarks = f"{remarks} ({p_str})" if remarks else p_str
|
||||||
|
|
||||||
|
valid_records.append({
|
||||||
|
"asset": target_asset,
|
||||||
|
"insurer_id": target_vendor.id,
|
||||||
|
"policy_no": policy_no,
|
||||||
|
"start_date": start_date,
|
||||||
|
"end_date": end_date,
|
||||||
|
"coverage_amount": coverage_amount,
|
||||||
|
"remarks": combined_remarks or None,
|
||||||
|
})
|
||||||
|
|
||||||
|
preview_rows.append({
|
||||||
|
"row": row_idx,
|
||||||
|
"data": {
|
||||||
|
"asset_code": asset_code,
|
||||||
|
"insurer_name": insurer_name,
|
||||||
|
"policy_number": policy_no,
|
||||||
|
"start_date": str(start_date) if start_date else str(start_date_val or ""),
|
||||||
|
"end_date": str(end_date) if end_date else str(end_date_val or ""),
|
||||||
|
"insured_value": coverage_amount,
|
||||||
|
"premium": premium,
|
||||||
|
"remarks": remarks,
|
||||||
|
},
|
||||||
|
"valid": is_valid,
|
||||||
|
"error": err_text,
|
||||||
|
})
|
||||||
|
|
||||||
|
created_count = 0
|
||||||
|
if not dry_run:
|
||||||
|
if errors and not skip_invalid:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"{len(errors)} row(s) failed validation.",
|
||||||
|
code="IMPORT_VALIDATION_ERRORS",
|
||||||
|
)
|
||||||
|
if valid_records:
|
||||||
|
for item in valid_records:
|
||||||
|
asset = item["asset"]
|
||||||
|
asset.insurance_applicable = True
|
||||||
|
asset.updated_by_id = user_id
|
||||||
|
|
||||||
|
policy = InsurancePolicy(
|
||||||
|
asset_id=asset.id,
|
||||||
|
insurer_id=item["insurer_id"],
|
||||||
|
policy_no=item["policy_no"],
|
||||||
|
start_date=item["start_date"],
|
||||||
|
end_date=item["end_date"],
|
||||||
|
coverage_amount=item["coverage_amount"],
|
||||||
|
remarks=item["remarks"],
|
||||||
|
created_by_id=user_id,
|
||||||
|
updated_by_id=user_id,
|
||||||
|
)
|
||||||
|
db.add(policy)
|
||||||
|
db.flush()
|
||||||
|
log_audit(
|
||||||
|
db,
|
||||||
|
entity_type="insurance_policy",
|
||||||
|
entity_id=policy.id,
|
||||||
|
action="create",
|
||||||
|
changes={
|
||||||
|
"asset_id": asset.id,
|
||||||
|
"insurer_id": item["insurer_id"],
|
||||||
|
"policy_no": item["policy_no"],
|
||||||
|
"start_date": str(item["start_date"]),
|
||||||
|
"end_date": str(item["end_date"]),
|
||||||
|
"coverage_amount": item["coverage_amount"],
|
||||||
|
"source": "bulk_import",
|
||||||
|
},
|
||||||
|
user_id=user_id,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
created_count = len(valid_records)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"dry_run": dry_run,
|
||||||
|
"total_rows": len(raw_rows),
|
||||||
|
"valid_count": len(valid_records),
|
||||||
|
"error_count": len(errors),
|
||||||
|
"created_count": created_count,
|
||||||
|
"errors": errors,
|
||||||
|
"preview_rows": preview_rows,
|
||||||
|
}
|
||||||
|
|
||||||
+174
-12
@@ -1,13 +1,20 @@
|
|||||||
import csv
|
import csv
|
||||||
from io import BytesIO, StringIO
|
from io import BytesIO, StringIO
|
||||||
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from openpyxl import Workbook
|
from openpyxl import Workbook
|
||||||
from openpyxl.styles import Alignment, Font, PatternFill
|
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||||
from openpyxl.utils import get_column_letter
|
from openpyxl.utils import get_column_letter
|
||||||
|
|
||||||
from ..core.time_utils import format_datetime, utc_now
|
from ..core.time_utils import format_datetime, utc_now
|
||||||
|
|
||||||
|
|
||||||
|
def _sanitize_sheet_title(title: str) -> str:
|
||||||
|
"""Sanitize Excel sheet title to comply with openpyxl / Excel naming rules."""
|
||||||
|
cleaned = re.sub(r'[\\/*?:\[\]]', '_', title or "Report").strip()
|
||||||
|
return cleaned[:31] or "Report"
|
||||||
|
|
||||||
|
|
||||||
def _format_filters_echo(filters_applied: dict[str, Any]) -> str:
|
def _format_filters_echo(filters_applied: dict[str, Any]) -> str:
|
||||||
if not filters_applied:
|
if not filters_applied:
|
||||||
return "None"
|
return "None"
|
||||||
@@ -20,10 +27,76 @@ def _format_summary_echo(summary: dict[str, Any]) -> str:
|
|||||||
return " | ".join(f"{k.replace('_', ' ').title()}: {v}" for k, v in summary.items())
|
return " | ".join(f"{k.replace('_', ' ').title()}: {v}" for k, v in summary.items())
|
||||||
|
|
||||||
|
|
||||||
|
# Styling constants for executive Excel reports
|
||||||
|
_NAVY_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||||
|
_ZEBRA_FILL = PatternFill(start_color="F8FAFC", end_color="F8FAFC", fill_type="solid")
|
||||||
|
_WHITE_FILL = PatternFill(start_color="FFFFFF", end_color="FFFFFF", fill_type="solid")
|
||||||
|
_SUMMARY_FILL = PatternFill(start_color="EFF6FF", end_color="EFF6FF", fill_type="solid")
|
||||||
|
_TOTAL_FILL = PatternFill(start_color="F1F5F9", end_color="F1F5F9", fill_type="solid")
|
||||||
|
|
||||||
|
_TITLE_FONT = Font(name="Calibri", size=14, bold=True, color="0F172A")
|
||||||
|
_META_FONT = Font(name="Calibri", size=9, italic=True, color="475569")
|
||||||
|
_SUMMARY_FONT = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
|
||||||
|
_HEADER_FONT = Font(name="Calibri", size=11, bold=True, color="FFFFFF")
|
||||||
|
_DATA_FONT = Font(name="Calibri", size=10, color="0F172A")
|
||||||
|
_TOTAL_FONT = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
|
||||||
|
|
||||||
|
_THIN_SIDE = Side(style="thin", color="CBD5E1")
|
||||||
|
_CELL_BORDER = Border(left=_THIN_SIDE, right=_THIN_SIDE, top=_THIN_SIDE, bottom=_THIN_SIDE)
|
||||||
|
_HEADER_BORDER = Border(
|
||||||
|
left=Side(style="thin", color="334155"),
|
||||||
|
right=Side(style="thin", color="334155"),
|
||||||
|
top=Side(style="thin", color="334155"),
|
||||||
|
bottom=Side(style="medium", color="0F172A"),
|
||||||
|
)
|
||||||
|
_TOTAL_BORDER = Border(
|
||||||
|
left=_THIN_SIDE,
|
||||||
|
right=_THIN_SIDE,
|
||||||
|
top=Side(style="thin", color="94A3B8"),
|
||||||
|
bottom=Side(style="double", color="1E3A8A"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _detect_cell_format(col_key: str, col_label: str, val: Any) -> tuple[Alignment, str | None]:
|
||||||
|
"""Determine alignment and Excel number format from column metadata and value."""
|
||||||
|
key_lower = col_key.lower()
|
||||||
|
lbl_lower = col_label.lower()
|
||||||
|
|
||||||
|
# Currency / Financial costs
|
||||||
|
if any(k in key_lower or k in lbl_lower for k in ["cost", "value", "price", "amount", "budget", "estimate"]):
|
||||||
|
align = Alignment(horizontal="right", vertical="center")
|
||||||
|
num_fmt = '"₹"#,##0.00' if isinstance(val, float) else '"₹"#,##0'
|
||||||
|
return align, num_fmt
|
||||||
|
|
||||||
|
# Percentages
|
||||||
|
if any(k in key_lower or k in lbl_lower for k in ["pct", "percent", "rate", "uptime"]):
|
||||||
|
align = Alignment(horizontal="right", vertical="center")
|
||||||
|
num_fmt = '0.0"%"' if isinstance(val, (int, float)) else None
|
||||||
|
return align, num_fmt
|
||||||
|
|
||||||
|
# Numeric counts / durations / minutes
|
||||||
|
if isinstance(val, (int, float)) and not isinstance(val, bool):
|
||||||
|
align = Alignment(horizontal="right", vertical="center")
|
||||||
|
num_fmt = "#,##0" if isinstance(val, int) else "#,##0.0"
|
||||||
|
return align, num_fmt
|
||||||
|
|
||||||
|
# Dates, codes, status, IDs, booleans
|
||||||
|
if any(k in key_lower or k in lbl_lower for k in ["date", "code", "no", "status", "priority", "criticality", "mode"]):
|
||||||
|
align = Alignment(horizontal="center", vertical="center")
|
||||||
|
return align, None
|
||||||
|
|
||||||
|
# Text / Names / Descriptions
|
||||||
|
align = Alignment(horizontal="left", vertical="center")
|
||||||
|
return align, None
|
||||||
|
|
||||||
|
|
||||||
def build_xlsx(report_payload: dict[str, Any]) -> BytesIO:
|
def build_xlsx(report_payload: dict[str, Any]) -> BytesIO:
|
||||||
wb = Workbook()
|
wb = Workbook()
|
||||||
ws = wb.active
|
ws = wb.active
|
||||||
ws.title = report_payload["title"][:31]
|
ws.title = _sanitize_sheet_title(report_payload.get("title", "Report"))
|
||||||
|
|
||||||
|
# Explicitly show grid lines in Excel view
|
||||||
|
ws.views.sheetView[0].showGridLines = True
|
||||||
|
|
||||||
title_text = f"Poona Hospital & Research Centre \u2014 {report_payload['title']}"
|
title_text = f"Poona Hospital & Research Centre \u2014 {report_payload['title']}"
|
||||||
meta_text = (
|
meta_text = (
|
||||||
@@ -32,40 +105,129 @@ def build_xlsx(report_payload: dict[str, Any]) -> BytesIO:
|
|||||||
)
|
)
|
||||||
summary_text = _format_summary_echo(report_payload.get("summary", {}))
|
summary_text = _format_summary_echo(report_payload.get("summary", {}))
|
||||||
|
|
||||||
ws.cell(row=1, column=1, value=title_text).font = Font(name="Calibri", size=14, bold=True, color="0F172A")
|
# Row 1: Hospital Title
|
||||||
ws.cell(row=2, column=1, value=meta_text).font = Font(name="Calibri", size=10, color="475569")
|
ws.row_dimensions[1].height = 28
|
||||||
ws.cell(row=3, column=1, value=summary_text).font = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
|
c1 = ws.cell(row=1, column=1, value=title_text)
|
||||||
|
c1.font = _TITLE_FONT
|
||||||
|
c1.alignment = Alignment(vertical="center")
|
||||||
|
|
||||||
|
# Row 2: Metadata & Filters
|
||||||
|
ws.row_dimensions[2].height = 18
|
||||||
|
c2 = ws.cell(row=2, column=1, value=meta_text)
|
||||||
|
c2.font = _META_FONT
|
||||||
|
c2.alignment = Alignment(vertical="center")
|
||||||
|
|
||||||
|
# Row 3: Summary KPIs strip
|
||||||
|
ws.row_dimensions[3].height = 24
|
||||||
|
c3 = ws.cell(row=3, column=1, value=summary_text)
|
||||||
|
c3.font = _SUMMARY_FONT
|
||||||
|
c3.fill = _SUMMARY_FILL
|
||||||
|
c3.border = Border(
|
||||||
|
top=Side(style="thin", color="BFDBFE"),
|
||||||
|
bottom=Side(style="thin", color="BFDBFE"),
|
||||||
|
left=Side(style="thin", color="BFDBFE"),
|
||||||
|
right=Side(style="thin", color="BFDBFE"),
|
||||||
|
)
|
||||||
|
c3.alignment = Alignment(vertical="center", indent=1)
|
||||||
|
|
||||||
|
# Row 4: Spacer
|
||||||
|
ws.row_dimensions[4].height = 10
|
||||||
|
|
||||||
columns: list[dict[str, str]] = report_payload.get("columns", [])
|
columns: list[dict[str, str]] = report_payload.get("columns", [])
|
||||||
rows: list[dict[str, Any]] = report_payload.get("rows", [])
|
rows: list[dict[str, Any]] = report_payload.get("rows", [])
|
||||||
|
|
||||||
header_fill = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
# Span summary strip styling across header columns
|
||||||
header_font = Font(name="Calibri", size=11, bold=True, color="FFFFFF")
|
if columns and len(columns) > 1:
|
||||||
|
for c_idx in range(2, len(columns) + 1):
|
||||||
|
sc = ws.cell(row=3, column=c_idx)
|
||||||
|
sc.fill = _SUMMARY_FILL
|
||||||
|
sc.border = Border(
|
||||||
|
top=Side(style="thin", color="BFDBFE"),
|
||||||
|
bottom=Side(style="thin", color="BFDBFE"),
|
||||||
|
left=Side(style="thin", color="BFDBFE"),
|
||||||
|
right=Side(style="thin", color="BFDBFE"),
|
||||||
|
)
|
||||||
|
|
||||||
header_row = 5
|
header_row = 5
|
||||||
|
ws.row_dimensions[header_row].height = 28
|
||||||
col_widths: list[int] = []
|
col_widths: list[int] = []
|
||||||
|
|
||||||
for c_idx, col in enumerate(columns, start=1):
|
for c_idx, col in enumerate(columns, start=1):
|
||||||
cell = ws.cell(row=header_row, column=c_idx, value=col["label"])
|
cell = ws.cell(row=header_row, column=c_idx, value=col["label"])
|
||||||
cell.fill = header_fill
|
cell.fill = _NAVY_HEADER_FILL
|
||||||
cell.font = header_font
|
cell.font = _HEADER_FONT
|
||||||
cell.alignment = Alignment(horizontal="left", vertical="center")
|
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||||
|
cell.border = _HEADER_BORDER
|
||||||
col_widths.append(len(str(col["label"])))
|
col_widths.append(len(str(col["label"])))
|
||||||
|
|
||||||
|
# Freeze header panes
|
||||||
ws.freeze_panes = "A6"
|
ws.freeze_panes = "A6"
|
||||||
|
|
||||||
|
# Data rows
|
||||||
|
last_data_row = header_row
|
||||||
for r_offset, row_data in enumerate(rows):
|
for r_offset, row_data in enumerate(rows):
|
||||||
excel_row = header_row + 1 + r_offset
|
excel_row = header_row + 1 + r_offset
|
||||||
|
last_data_row = excel_row
|
||||||
|
ws.row_dimensions[excel_row].height = 20
|
||||||
|
row_fill = _ZEBRA_FILL if r_offset % 2 == 1 else _WHITE_FILL
|
||||||
|
|
||||||
for c_idx, col in enumerate(columns, start=1):
|
for c_idx, col in enumerate(columns, start=1):
|
||||||
val = row_data.get(col["key"])
|
val = row_data.get(col["key"])
|
||||||
if isinstance(val, bool):
|
if isinstance(val, bool):
|
||||||
val = "Yes" if val else "No"
|
val = "Yes" if val else "No"
|
||||||
ws.cell(row=excel_row, column=c_idx, value=val)
|
|
||||||
|
cell = ws.cell(row=excel_row, column=c_idx, value=val)
|
||||||
|
cell.fill = row_fill
|
||||||
|
cell.font = _DATA_FONT
|
||||||
|
cell.border = _CELL_BORDER
|
||||||
|
|
||||||
|
align, num_fmt = _detect_cell_format(col["key"], col["label"], val)
|
||||||
|
cell.alignment = align
|
||||||
|
if num_fmt and isinstance(val, (int, float)):
|
||||||
|
cell.number_format = num_fmt
|
||||||
|
|
||||||
val_len = len(str(val)) if val is not None else 0
|
val_len = len(str(val)) if val is not None else 0
|
||||||
if val_len > col_widths[c_idx - 1]:
|
if val_len > col_widths[c_idx - 1]:
|
||||||
col_widths[c_idx - 1] = val_len
|
col_widths[c_idx - 1] = val_len
|
||||||
|
|
||||||
|
# Add native Excel AutoFilter on header row
|
||||||
|
if columns:
|
||||||
|
last_col_letter = get_column_letter(len(columns))
|
||||||
|
ws.auto_filter.ref = f"A{header_row}:{last_col_letter}{last_data_row}"
|
||||||
|
|
||||||
|
# Total summary row at bottom
|
||||||
|
if rows:
|
||||||
|
summary_row = last_data_row + 1
|
||||||
|
ws.row_dimensions[summary_row].height = 22
|
||||||
|
for c_idx in range(1, len(columns) + 1):
|
||||||
|
tot_cell = ws.cell(row=summary_row, column=c_idx)
|
||||||
|
tot_cell.fill = _TOTAL_FILL
|
||||||
|
tot_cell.border = _TOTAL_BORDER
|
||||||
|
tot_cell.font = _TOTAL_FONT
|
||||||
|
if c_idx == 1:
|
||||||
|
tot_cell.value = f"Total Records: {len(rows)}"
|
||||||
|
tot_cell.alignment = Alignment(horizontal="left", vertical="center")
|
||||||
|
else:
|
||||||
|
tot_cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||||
|
|
||||||
for c_idx, width in enumerate(col_widths, start=1):
|
for c_idx, width in enumerate(col_widths, start=1):
|
||||||
ws.column_dimensions[get_column_letter(c_idx)].width = min(45, max(12, width + 3))
|
ws.column_dimensions[get_column_letter(c_idx)].width = min(50, max(14, width + 4))
|
||||||
|
|
||||||
|
# Pre-configure page setup for professional A4 Landscape printing / PDF conversion from Excel
|
||||||
|
try:
|
||||||
|
ws.page_setup.orientation = ws.ORIENTATION_LANDSCAPE
|
||||||
|
ws.page_setup.paperSize = ws.PAPERSIZE_A4
|
||||||
|
ws.page_setup.fitToPage = True
|
||||||
|
ws.page_setup.fitToWidth = 1
|
||||||
|
ws.page_setup.fitToHeight = 0
|
||||||
|
ws.sheet_properties.pageSetUpPr.fitToPage = True
|
||||||
|
ws.print_title_rows = f"{header_row}:{header_row}"
|
||||||
|
ws.oddHeader.left.text = "&BPoona Hospital & Research Centre&B"
|
||||||
|
ws.oddHeader.right.text = report_payload.get("title", "Operational Report")
|
||||||
|
ws.oddFooter.left.text = "Confidential • Biomedical Asset Management System"
|
||||||
|
ws.oddFooter.right.text = "Page &P of &N"
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
buf = BytesIO()
|
buf = BytesIO()
|
||||||
wb.save(buf)
|
wb.save(buf)
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ from .calculations import (
|
|||||||
coverage_status,
|
coverage_status,
|
||||||
)
|
)
|
||||||
from .permissions import Role
|
from .permissions import Role
|
||||||
|
from .scoping import resolve_department_scope
|
||||||
from .settings_service import get_setting_value
|
from .settings_service import get_setting_value
|
||||||
|
|
||||||
_MONTH_RE = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$")
|
_MONTH_RE = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$")
|
||||||
@@ -54,9 +55,8 @@ def _parse_month(month_str: Optional[str], fallback_today: date) -> tuple[str, i
|
|||||||
|
|
||||||
|
|
||||||
def _scoped_dept_id(user: User, requested_dept_id: Optional[int]) -> Optional[int]:
|
def _scoped_dept_id(user: User, requested_dept_id: Optional[int]) -> Optional[int]:
|
||||||
if user.role == Role.department_user.value:
|
scope = resolve_department_scope(user, requested_dept_id)
|
||||||
return user.department_id
|
return scope.department_id
|
||||||
return requested_dept_id
|
|
||||||
|
|
||||||
|
|
||||||
def _clean_filters(**kwargs: Any) -> dict[str, Any]:
|
def _clean_filters(**kwargs: Any) -> dict[str, Any]:
|
||||||
@@ -76,7 +76,8 @@ def _build_monthly_maintenance(
|
|||||||
today = effective_today(db)
|
today = effective_today(db)
|
||||||
eff_now = effective_now_utc(db)
|
eff_now = effective_now_utc(db)
|
||||||
month_str, year, month = _parse_month(params.get("month"), today)
|
month_str, year, month = _parse_month(params.get("month"), today)
|
||||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
scope = resolve_department_scope(user, params.get("department_id"))
|
||||||
|
dept_id = scope.department_id
|
||||||
asset_id = params.get("asset_id")
|
asset_id = params.get("asset_id")
|
||||||
|
|
||||||
days_in_month = calendar.monthrange(year, month)[1]
|
days_in_month = calendar.monthrange(year, month)[1]
|
||||||
@@ -84,6 +85,49 @@ def _build_monthly_maintenance(
|
|||||||
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
|
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
|
||||||
sched_mins_per_asset = days_in_month * sched_hours * 60
|
sched_mins_per_asset = days_in_month * sched_hours * 60
|
||||||
|
|
||||||
|
if scope.is_empty:
|
||||||
|
return {
|
||||||
|
"report_key": "monthly-maintenance",
|
||||||
|
"title": "Monthly Maintenance Summary",
|
||||||
|
"filters_applied": _clean_filters(month=month_str, department_id=None, asset_id=asset_id),
|
||||||
|
"formula_info": {
|
||||||
|
"scheduled_hours_per_day": sched_hours,
|
||||||
|
"downtime_end_milestone": milestone,
|
||||||
|
"days_in_month": days_in_month,
|
||||||
|
"uptime_formula": "total_scheduled_minutes - total_downtime_minutes",
|
||||||
|
"downtime_formula": "clip_downtime_to_month(registered_at, milestone, month)",
|
||||||
|
"explanation": (
|
||||||
|
f"Scheduled operating hours are {sched_hours}h/day across {days_in_month} days in "
|
||||||
|
f"{month_str} (Asia/Kolkata); downtime_days_count is distinct calendar days with any breakdown."
|
||||||
|
),
|
||||||
|
},
|
||||||
|
"summary": {
|
||||||
|
"total_assets": 0,
|
||||||
|
"total_complaints": 0,
|
||||||
|
"total_downtime_minutes": 0,
|
||||||
|
"downtime_formatted": format_duration(0),
|
||||||
|
"downtime_days_count": 0,
|
||||||
|
"total_scheduled_minutes": 0,
|
||||||
|
"total_uptime_minutes": 0,
|
||||||
|
"uptime_formatted": format_duration(0),
|
||||||
|
"downtime_pct": 0.0,
|
||||||
|
"downtime_vs_uptime_pct": 0.0,
|
||||||
|
"scheduled_hours_per_day": sched_hours,
|
||||||
|
"downtime_end_milestone": milestone,
|
||||||
|
},
|
||||||
|
"columns": [
|
||||||
|
{"key": "department_name", "label": "Department"},
|
||||||
|
{"key": "asset_count", "label": "Assets"},
|
||||||
|
{"key": "complaint_count", "label": "Breakdowns"},
|
||||||
|
{"key": "downtime_formatted", "label": "Downtime"},
|
||||||
|
{"key": "downtime_days_count", "label": "Downtime Days"},
|
||||||
|
{"key": "uptime_formatted", "label": "Uptime"},
|
||||||
|
{"key": "downtime_pct", "label": "Downtime %"},
|
||||||
|
],
|
||||||
|
"rows": [],
|
||||||
|
"chart_data": [],
|
||||||
|
}
|
||||||
|
|
||||||
dept_q = db.query(Department).filter(Department.is_active.is_(True))
|
dept_q = db.query(Department).filter(Department.is_active.is_(True))
|
||||||
if dept_id is not None:
|
if dept_id is not None:
|
||||||
dept_q = dept_q.filter(Department.id == dept_id)
|
dept_q = dept_q.filter(Department.id == dept_id)
|
||||||
@@ -230,7 +274,33 @@ def _build_monthly_department(
|
|||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
today = effective_today(db)
|
today = effective_today(db)
|
||||||
month_str, year, month = _parse_month(params.get("month"), today)
|
month_str, year, month = _parse_month(params.get("month"), today)
|
||||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
scope = resolve_department_scope(user, params.get("department_id"))
|
||||||
|
dept_id = scope.department_id
|
||||||
|
|
||||||
|
if scope.is_empty:
|
||||||
|
return {
|
||||||
|
"report_key": "monthly-department",
|
||||||
|
"title": "Monthly Department Report",
|
||||||
|
"filters_applied": _clean_filters(month=month_str, department_id=None),
|
||||||
|
"summary": {
|
||||||
|
"departments_count": 0,
|
||||||
|
"total_under_repair": 0,
|
||||||
|
"total_outstanding_complaints": 0,
|
||||||
|
"total_visits": 0,
|
||||||
|
},
|
||||||
|
"columns": [
|
||||||
|
{"key": "department_name", "label": "Department"},
|
||||||
|
{"key": "total_assets", "label": "Total Assets"},
|
||||||
|
{"key": "under_repair_count", "label": "Under Repair"},
|
||||||
|
{"key": "out_of_service_count", "label": "Out of Service"},
|
||||||
|
{"key": "outstanding_complaints_count", "label": "Open Complaints"},
|
||||||
|
{"key": "critical_open_count", "label": "Critical Open"},
|
||||||
|
{"key": "visits_this_month", "label": "Visits"},
|
||||||
|
{"key": "new_equipment_requirements", "label": "New Equipment Requirements"},
|
||||||
|
{"key": "latest_requirements_notes", "label": "Visit Observations"},
|
||||||
|
],
|
||||||
|
"rows": [],
|
||||||
|
}
|
||||||
|
|
||||||
month_start = date(year, month, 1)
|
month_start = date(year, month, 1)
|
||||||
next_month_start = add_months(month_start, 1)
|
next_month_start = add_months(month_start, 1)
|
||||||
@@ -263,11 +333,16 @@ def _build_monthly_department(
|
|||||||
d_assets = [a for a in assets if a.department_id == d.id]
|
d_assets = [a for a in assets if a.department_id == d.id]
|
||||||
d_cmps = [c for c in open_complaints if c.asset.department_id == d.id]
|
d_cmps = [c for c in open_complaints if c.asset.department_id == d.id]
|
||||||
d_visits = [v for v in visits if v.department_id == d.id]
|
d_visits = [v for v in visits if v.department_id == d.id]
|
||||||
notes = "; ".join(
|
obs_notes = "; ".join(
|
||||||
f"[{format_date(v.visit_date)}] {v.observations.strip()}"
|
f"[{format_date(v.visit_date)}] {v.observations.strip()}"
|
||||||
for v in d_visits
|
for v in d_visits
|
||||||
if v.observations and v.observations.strip()
|
if v.observations and v.observations.strip()
|
||||||
)
|
)
|
||||||
|
reqs_notes = "; ".join(
|
||||||
|
f"[{format_date(v.visit_date)}] {v.new_requirements.strip()}"
|
||||||
|
for v in d_visits
|
||||||
|
if v.new_requirements and v.new_requirements.strip()
|
||||||
|
)
|
||||||
rows.append(
|
rows.append(
|
||||||
{
|
{
|
||||||
"department_id": d.id,
|
"department_id": d.id,
|
||||||
@@ -278,7 +353,8 @@ def _build_monthly_department(
|
|||||||
"outstanding_complaints_count": len(d_cmps),
|
"outstanding_complaints_count": len(d_cmps),
|
||||||
"critical_open_count": sum(1 for c in d_cmps if c.priority == "critical"),
|
"critical_open_count": sum(1 for c in d_cmps if c.priority == "critical"),
|
||||||
"visits_this_month": len(d_visits),
|
"visits_this_month": len(d_visits),
|
||||||
"latest_requirements_notes": notes or "\u2014",
|
"new_equipment_requirements": reqs_notes or "\u2014",
|
||||||
|
"latest_requirements_notes": obs_notes or "\u2014",
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -300,7 +376,8 @@ def _build_monthly_department(
|
|||||||
{"key": "outstanding_complaints_count", "label": "Open Complaints"},
|
{"key": "outstanding_complaints_count", "label": "Open Complaints"},
|
||||||
{"key": "critical_open_count", "label": "Critical Open"},
|
{"key": "critical_open_count", "label": "Critical Open"},
|
||||||
{"key": "visits_this_month", "label": "Visits"},
|
{"key": "visits_this_month", "label": "Visits"},
|
||||||
{"key": "latest_requirements_notes", "label": "Visit Observations / Requirements"},
|
{"key": "new_equipment_requirements", "label": "New Equipment Requirements"},
|
||||||
|
{"key": "latest_requirements_notes", "label": "Visit Observations"},
|
||||||
],
|
],
|
||||||
"rows": rows,
|
"rows": rows,
|
||||||
}
|
}
|
||||||
@@ -319,7 +396,31 @@ def _build_daily_visit(
|
|||||||
|
|
||||||
date_from = params.get("date_from")
|
date_from = params.get("date_from")
|
||||||
date_to = params.get("date_to")
|
date_to = params.get("date_to")
|
||||||
dept_id = params.get("department_id")
|
scope = resolve_department_scope(user, params.get("department_id"))
|
||||||
|
dept_id = scope.department_id
|
||||||
|
|
||||||
|
if scope.is_empty:
|
||||||
|
return {
|
||||||
|
"report_key": "daily-visit",
|
||||||
|
"title": "Daily Department Visit Report",
|
||||||
|
"filters_applied": _clean_filters(date_from=date_from, date_to=date_to, department_id=None),
|
||||||
|
"summary": {
|
||||||
|
"total_visits": 0,
|
||||||
|
"departments_visited": 0,
|
||||||
|
"equipment_checked": 0,
|
||||||
|
"breakdowns_logged": 0,
|
||||||
|
},
|
||||||
|
"columns": [
|
||||||
|
{"key": "visit_date", "label": "Visit Date"},
|
||||||
|
{"key": "department_name", "label": "Department"},
|
||||||
|
{"key": "visited_by_name", "label": "Biomedical Engineer"},
|
||||||
|
{"key": "assets_count", "label": "Equipment Checked"},
|
||||||
|
{"key": "complaints_count", "label": "Breakdowns Logged"},
|
||||||
|
{"key": "new_requirements", "label": "New Equipment Requirements"},
|
||||||
|
{"key": "observations", "label": "Observations"},
|
||||||
|
],
|
||||||
|
"rows": [],
|
||||||
|
}
|
||||||
|
|
||||||
query = db.query(DepartmentVisit).options(
|
query = db.query(DepartmentVisit).options(
|
||||||
joinedload(DepartmentVisit.department),
|
joinedload(DepartmentVisit.department),
|
||||||
@@ -389,7 +490,8 @@ def _build_breakdown_complaints(
|
|||||||
user: User,
|
user: User,
|
||||||
params: dict[str, Any],
|
params: dict[str, Any],
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
scope = resolve_department_scope(user, params.get("department_id"))
|
||||||
|
dept_id = scope.department_id
|
||||||
date_from = params.get("date_from")
|
date_from = params.get("date_from")
|
||||||
date_to = params.get("date_to")
|
date_to = params.get("date_to")
|
||||||
asset_id = params.get("asset_id")
|
asset_id = params.get("asset_id")
|
||||||
@@ -397,6 +499,46 @@ def _build_breakdown_complaints(
|
|||||||
call_status = params.get("call_status")
|
call_status = params.get("call_status")
|
||||||
assigned_to_id = params.get("assigned_to_id")
|
assigned_to_id = params.get("assigned_to_id")
|
||||||
|
|
||||||
|
if scope.is_empty:
|
||||||
|
return {
|
||||||
|
"report_key": "breakdown-complaints",
|
||||||
|
"title": "Breakdown / Complaint Report",
|
||||||
|
"filters_applied": _clean_filters(
|
||||||
|
date_from=date_from,
|
||||||
|
date_to=date_to,
|
||||||
|
department_id=None,
|
||||||
|
asset_id=asset_id,
|
||||||
|
priority=priority,
|
||||||
|
call_status=call_status,
|
||||||
|
assigned_to_id=assigned_to_id,
|
||||||
|
),
|
||||||
|
"summary": {
|
||||||
|
"total_complaints": 0,
|
||||||
|
"open_count": 0,
|
||||||
|
"in_progress_count": 0,
|
||||||
|
"closed_count": 0,
|
||||||
|
"critical_count": 0,
|
||||||
|
"avg_response_minutes": 0.0,
|
||||||
|
"total_downtime_minutes": 0,
|
||||||
|
},
|
||||||
|
"columns": [
|
||||||
|
{"key": "complaint_no", "label": "Complaint No"},
|
||||||
|
{"key": "asset_code", "label": "Asset Code"},
|
||||||
|
{"key": "asset_name", "label": "Equipment"},
|
||||||
|
{"key": "department_name", "label": "Department"},
|
||||||
|
{"key": "priority", "label": "Priority"},
|
||||||
|
{"key": "call_status", "label": "Status"},
|
||||||
|
{"key": "registered_at", "label": "Registered At"},
|
||||||
|
{"key": "assigned_to_name", "label": "Assigned To"},
|
||||||
|
{"key": "response_time_formatted", "label": "Response Time"},
|
||||||
|
{"key": "downtime_formatted", "label": "Downtime"},
|
||||||
|
{"key": "action_taken", "label": "Action Taken"},
|
||||||
|
{"key": "closed_at", "label": "Closed At"},
|
||||||
|
{"key": "closure_remarks", "label": "Closure Remarks"},
|
||||||
|
],
|
||||||
|
"rows": [],
|
||||||
|
}
|
||||||
|
|
||||||
response_start = str(get_setting_value(db, "response_start", "registered_at"))
|
response_start = str(get_setting_value(db, "response_start", "registered_at"))
|
||||||
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
|
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
|
||||||
eff_now = effective_now_utc(db)
|
eff_now = effective_now_utc(db)
|
||||||
@@ -520,13 +662,54 @@ def _build_pm_compliance(
|
|||||||
params: dict[str, Any],
|
params: dict[str, Any],
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
today = effective_today(db)
|
today = effective_today(db)
|
||||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
scope = resolve_department_scope(user, params.get("department_id"))
|
||||||
|
dept_id = scope.department_id
|
||||||
month_param = params.get("month")
|
month_param = params.get("month")
|
||||||
date_from = params.get("date_from")
|
date_from = params.get("date_from")
|
||||||
date_to = params.get("date_to")
|
date_to = params.get("date_to")
|
||||||
asset_id = params.get("asset_id")
|
asset_id = params.get("asset_id")
|
||||||
service_mode = params.get("service_mode")
|
service_mode = params.get("service_mode")
|
||||||
|
|
||||||
|
clean_month: str | None = None
|
||||||
|
if month_param and str(month_param).strip():
|
||||||
|
clean_month, y, m = _parse_month(month_param, today)
|
||||||
|
|
||||||
|
if scope.is_empty:
|
||||||
|
return {
|
||||||
|
"report_key": "pm-compliance",
|
||||||
|
"title": "PM Compliance Report",
|
||||||
|
"filters_applied": _clean_filters(
|
||||||
|
month=clean_month,
|
||||||
|
date_from=date_from,
|
||||||
|
date_to=date_to,
|
||||||
|
department_id=None,
|
||||||
|
asset_id=asset_id,
|
||||||
|
service_mode=service_mode,
|
||||||
|
),
|
||||||
|
"summary": {
|
||||||
|
"planned_count": 0,
|
||||||
|
"completed_count": 0,
|
||||||
|
"upcoming_count": 0,
|
||||||
|
"due_count": 0,
|
||||||
|
"overdue_count": 0,
|
||||||
|
"rescheduled_count": 0,
|
||||||
|
"compliance_pct": 0.0,
|
||||||
|
},
|
||||||
|
"columns": [
|
||||||
|
{"key": "planned_date", "label": "Planned Date"},
|
||||||
|
{"key": "asset_code", "label": "Asset Code"},
|
||||||
|
{"key": "asset_name", "label": "Equipment"},
|
||||||
|
{"key": "department_name", "label": "Department"},
|
||||||
|
{"key": "service_mode", "label": "Service Mode"},
|
||||||
|
{"key": "team_or_provider", "label": "Team / Provider"},
|
||||||
|
{"key": "status", "label": "Status"},
|
||||||
|
{"key": "completed_date", "label": "Completed Date"},
|
||||||
|
{"key": "service_details", "label": "Service Details"},
|
||||||
|
{"key": "remarks", "label": "Remarks"},
|
||||||
|
],
|
||||||
|
"rows": [],
|
||||||
|
}
|
||||||
|
|
||||||
inhouse_lead = int(get_setting_value(db, "pm_inhouse_lead_days", 15))
|
inhouse_lead = int(get_setting_value(db, "pm_inhouse_lead_days", 15))
|
||||||
outsourced_lead = int(get_setting_value(db, "pm_outsourced_lead_days", 15))
|
outsourced_lead = int(get_setting_value(db, "pm_outsourced_lead_days", 15))
|
||||||
red_days = int(get_setting_value(db, "red_threshold_days", 7))
|
red_days = int(get_setting_value(db, "red_threshold_days", 7))
|
||||||
@@ -636,13 +819,48 @@ def _build_calibration_due(
|
|||||||
params: dict[str, Any],
|
params: dict[str, Any],
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
today = effective_today(db)
|
today = effective_today(db)
|
||||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
scope = resolve_department_scope(user, params.get("department_id"))
|
||||||
|
dept_id = scope.department_id
|
||||||
due_from = params.get("due_from")
|
due_from = params.get("due_from")
|
||||||
due_to = params.get("due_to")
|
due_to = params.get("due_to")
|
||||||
asset_id = params.get("asset_id")
|
asset_id = params.get("asset_id")
|
||||||
agency_id = params.get("agency_id")
|
agency_id = params.get("agency_id")
|
||||||
status_filter = params.get("status")
|
status_filter = params.get("status")
|
||||||
|
|
||||||
|
if scope.is_empty:
|
||||||
|
return {
|
||||||
|
"report_key": "calibration-due",
|
||||||
|
"title": "Calibration Due Report",
|
||||||
|
"filters_applied": _clean_filters(
|
||||||
|
due_from=due_from,
|
||||||
|
due_to=due_to,
|
||||||
|
department_id=None,
|
||||||
|
asset_id=asset_id,
|
||||||
|
agency_id=agency_id,
|
||||||
|
status=status_filter,
|
||||||
|
),
|
||||||
|
"summary": {
|
||||||
|
"total_records": 0,
|
||||||
|
"upcoming_count": 0,
|
||||||
|
"due_count": 0,
|
||||||
|
"overdue_count": 0,
|
||||||
|
"completed_count": 0,
|
||||||
|
},
|
||||||
|
"columns": [
|
||||||
|
{"key": "due_date", "label": "Due Date"},
|
||||||
|
{"key": "asset_code", "label": "Asset Code"},
|
||||||
|
{"key": "asset_name", "label": "Equipment"},
|
||||||
|
{"key": "department_name", "label": "Department"},
|
||||||
|
{"key": "agency_name", "label": "Agency"},
|
||||||
|
{"key": "frequency_months", "label": "Freq (Mo)"},
|
||||||
|
{"key": "status", "label": "Status"},
|
||||||
|
{"key": "completed_date", "label": "Completed Date"},
|
||||||
|
{"key": "certificate_no", "label": "Certificate No"},
|
||||||
|
{"key": "remarks", "label": "Remarks"},
|
||||||
|
],
|
||||||
|
"rows": [],
|
||||||
|
}
|
||||||
|
|
||||||
cal_lead = int(
|
cal_lead = int(
|
||||||
get_setting_value(
|
get_setting_value(
|
||||||
db,
|
db,
|
||||||
@@ -740,12 +958,48 @@ def _build_contracts_warranty(
|
|||||||
params: dict[str, Any],
|
params: dict[str, Any],
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
today = effective_today(db)
|
today = effective_today(db)
|
||||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
scope = resolve_department_scope(user, params.get("department_id"))
|
||||||
|
dept_id = scope.department_id
|
||||||
asset_id = params.get("asset_id")
|
asset_id = params.get("asset_id")
|
||||||
record_kind = params.get("record_kind") or "all"
|
record_kind = params.get("record_kind") or "all"
|
||||||
status_filter = params.get("status")
|
status_filter = params.get("status")
|
||||||
contract_type = params.get("contract_type")
|
contract_type = params.get("contract_type")
|
||||||
|
|
||||||
|
if scope.is_empty:
|
||||||
|
return {
|
||||||
|
"report_key": "contracts-warranty",
|
||||||
|
"title": "AMC / CMC & Warranty Report",
|
||||||
|
"filters_applied": _clean_filters(
|
||||||
|
department_id=None,
|
||||||
|
asset_id=asset_id,
|
||||||
|
record_kind=record_kind,
|
||||||
|
status=status_filter,
|
||||||
|
contract_type=contract_type,
|
||||||
|
),
|
||||||
|
"summary": {
|
||||||
|
"total_records": 0,
|
||||||
|
"active_contracts": 0,
|
||||||
|
"expiring_contracts": 0,
|
||||||
|
"expired_contracts": 0,
|
||||||
|
"active_warranties": 0,
|
||||||
|
"expiring_warranties": 0,
|
||||||
|
},
|
||||||
|
"columns": [
|
||||||
|
{"key": "record_kind", "label": "Kind"},
|
||||||
|
{"key": "asset_code", "label": "Asset Code"},
|
||||||
|
{"key": "asset_name", "label": "Equipment"},
|
||||||
|
{"key": "department_name", "label": "Department"},
|
||||||
|
{"key": "type_or_duration", "label": "Type / Duration"},
|
||||||
|
{"key": "provider_name", "label": "Provider"},
|
||||||
|
{"key": "start_date", "label": "Start Date"},
|
||||||
|
{"key": "end_date", "label": "End Date"},
|
||||||
|
{"key": "days_to_expiry", "label": "Days Left"},
|
||||||
|
{"key": "status", "label": "Status"},
|
||||||
|
{"key": "attachment_count", "label": "Files"},
|
||||||
|
],
|
||||||
|
"rows": [],
|
||||||
|
}
|
||||||
|
|
||||||
con_lead = int(
|
con_lead = int(
|
||||||
get_setting_value(
|
get_setting_value(
|
||||||
db,
|
db,
|
||||||
@@ -882,12 +1136,46 @@ def _build_demo_equipment(
|
|||||||
params: dict[str, Any],
|
params: dict[str, Any],
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
today = effective_today(db)
|
today = effective_today(db)
|
||||||
dept_id = _scoped_dept_id(user, params.get("department_id"))
|
scope = resolve_department_scope(user, params.get("department_id"))
|
||||||
|
dept_id = scope.department_id
|
||||||
supplier_id = params.get("supplier_id")
|
supplier_id = params.get("supplier_id")
|
||||||
status_filter = params.get("status")
|
status_filter = params.get("status")
|
||||||
date_from = params.get("date_from")
|
date_from = params.get("date_from")
|
||||||
date_to = params.get("date_to")
|
date_to = params.get("date_to")
|
||||||
|
|
||||||
|
if scope.is_empty:
|
||||||
|
return {
|
||||||
|
"report_key": "demo-equipment",
|
||||||
|
"title": "Demo Equipment Report",
|
||||||
|
"filters_applied": _clean_filters(
|
||||||
|
department_id=None,
|
||||||
|
supplier_id=supplier_id,
|
||||||
|
status=status_filter,
|
||||||
|
date_from=date_from,
|
||||||
|
date_to=date_to,
|
||||||
|
),
|
||||||
|
"summary": {
|
||||||
|
"total_items": 0,
|
||||||
|
"on_demo_count": 0,
|
||||||
|
"overdue_count": 0,
|
||||||
|
"returned_count": 0,
|
||||||
|
},
|
||||||
|
"columns": [
|
||||||
|
{"key": "name", "label": "Equipment Name"},
|
||||||
|
{"key": "equipment_type", "label": "Type"},
|
||||||
|
{"key": "supplier_name", "label": "Supplier"},
|
||||||
|
{"key": "department_name", "label": "Department"},
|
||||||
|
{"key": "location_name", "label": "Location"},
|
||||||
|
{"key": "start_date", "label": "Start Date"},
|
||||||
|
{"key": "expected_return_date", "label": "Expected Return"},
|
||||||
|
{"key": "actual_return_date", "label": "Actual Return"},
|
||||||
|
{"key": "status", "label": "Status"},
|
||||||
|
{"key": "days_remaining", "label": "Days Remaining"},
|
||||||
|
{"key": "remarks", "label": "Remarks"},
|
||||||
|
],
|
||||||
|
"rows": [],
|
||||||
|
}
|
||||||
|
|
||||||
query = db.query(DemoEquipment).options(
|
query = db.query(DemoEquipment).options(
|
||||||
joinedload(DemoEquipment.supplier),
|
joinedload(DemoEquipment.supplier),
|
||||||
joinedload(DemoEquipment.department),
|
joinedload(DemoEquipment.department),
|
||||||
@@ -969,6 +1257,105 @@ def _build_demo_equipment(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _build_equipment_inventory(
|
||||||
|
db: Session,
|
||||||
|
user: User,
|
||||||
|
params: dict[str, Any],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
scope = resolve_department_scope(user, params.get("department_id"))
|
||||||
|
dept_id = scope.department_id
|
||||||
|
category_id = params.get("category_id")
|
||||||
|
status_filter = params.get("status")
|
||||||
|
|
||||||
|
if scope.is_empty:
|
||||||
|
return {
|
||||||
|
"report_key": "equipment-inventory",
|
||||||
|
"title": "Equipment Inventory Report",
|
||||||
|
"filters_applied": _clean_filters(department_id=None, category_id=category_id, status=status_filter),
|
||||||
|
"summary": {
|
||||||
|
"total_assets": 0,
|
||||||
|
"in_service": 0,
|
||||||
|
"under_repair": 0,
|
||||||
|
"condemned": 0,
|
||||||
|
},
|
||||||
|
"columns": [
|
||||||
|
{"key": "asset_code", "label": "Asset Code"},
|
||||||
|
{"key": "name", "label": "Equipment Name"},
|
||||||
|
{"key": "department_name", "label": "Department"},
|
||||||
|
{"key": "location_name", "label": "Location"},
|
||||||
|
{"key": "category_name", "label": "Category"},
|
||||||
|
{"key": "serial_no", "label": "Serial No"},
|
||||||
|
{"key": "status", "label": "Status"},
|
||||||
|
],
|
||||||
|
"rows": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
query = (
|
||||||
|
db.query(Asset)
|
||||||
|
.options(
|
||||||
|
joinedload(Asset.department),
|
||||||
|
joinedload(Asset.location),
|
||||||
|
joinedload(Asset.category),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if dept_id is not None:
|
||||||
|
query = query.filter(Asset.department_id == dept_id)
|
||||||
|
if category_id is not None:
|
||||||
|
query = query.filter(Asset.category_id == category_id)
|
||||||
|
if status_filter:
|
||||||
|
query = query.filter(Asset.status == status_filter)
|
||||||
|
|
||||||
|
assets = query.order_by(Asset.asset_code.asc()).all()
|
||||||
|
rows = [
|
||||||
|
{
|
||||||
|
"id": a.id,
|
||||||
|
"asset_code": a.asset_code,
|
||||||
|
"name": a.name,
|
||||||
|
"department_id": a.department_id,
|
||||||
|
"department_name": a.department.name if a.department else "\u2014",
|
||||||
|
"location_name": a.location.name if a.location else "\u2014",
|
||||||
|
"category_name": a.category.name if a.category else "\u2014",
|
||||||
|
"serial_no": a.serial_no or "\u2014",
|
||||||
|
"status": a.status,
|
||||||
|
}
|
||||||
|
for a in assets
|
||||||
|
]
|
||||||
|
return {
|
||||||
|
"report_key": "equipment-inventory",
|
||||||
|
"title": "Equipment Inventory Report",
|
||||||
|
"filters_applied": _clean_filters(department_id=dept_id, category_id=category_id, status=status_filter),
|
||||||
|
"summary": {
|
||||||
|
"total_assets": len(rows),
|
||||||
|
"in_service": sum(1 for a in assets if a.status == "in_service"),
|
||||||
|
"under_repair": sum(1 for a in assets if a.status == "under_repair"),
|
||||||
|
"condemned": sum(1 for a in assets if a.status == "condemned"),
|
||||||
|
},
|
||||||
|
"columns": [
|
||||||
|
{"key": "asset_code", "label": "Asset Code"},
|
||||||
|
{"key": "name", "label": "Equipment Name"},
|
||||||
|
{"key": "department_name", "label": "Department"},
|
||||||
|
{"key": "location_name", "label": "Location"},
|
||||||
|
{"key": "category_name", "label": "Category"},
|
||||||
|
{"key": "serial_no", "label": "Serial No"},
|
||||||
|
{"key": "status", "label": "Status"},
|
||||||
|
],
|
||||||
|
"rows": rows,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _build_condemned_equipment(
|
||||||
|
db: Session,
|
||||||
|
user: User,
|
||||||
|
params: dict[str, Any],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
condemned_params = dict(params)
|
||||||
|
condemned_params["status"] = "condemned"
|
||||||
|
rep = _build_equipment_inventory(db, user, condemned_params)
|
||||||
|
rep["report_key"] = "condemned-equipment"
|
||||||
|
rep["title"] = "Condemned Equipment Report"
|
||||||
|
return rep
|
||||||
|
|
||||||
|
|
||||||
REPORT_BUILDERS: dict[str, Callable[[Session, User, dict[str, Any]], dict[str, Any]]] = {
|
REPORT_BUILDERS: dict[str, Callable[[Session, User, dict[str, Any]], dict[str, Any]]] = {
|
||||||
"monthly-maintenance": _build_monthly_maintenance,
|
"monthly-maintenance": _build_monthly_maintenance,
|
||||||
"monthly-department": _build_monthly_department,
|
"monthly-department": _build_monthly_department,
|
||||||
@@ -978,6 +1365,23 @@ REPORT_BUILDERS: dict[str, Callable[[Session, User, dict[str, Any]], dict[str, A
|
|||||||
"calibration-due": _build_calibration_due,
|
"calibration-due": _build_calibration_due,
|
||||||
"contracts-warranty": _build_contracts_warranty,
|
"contracts-warranty": _build_contracts_warranty,
|
||||||
"demo-equipment": _build_demo_equipment,
|
"demo-equipment": _build_demo_equipment,
|
||||||
|
# Auditor & alternate aliases
|
||||||
|
"equipment-inventory": _build_equipment_inventory,
|
||||||
|
"equipment_inventory": _build_equipment_inventory,
|
||||||
|
"condemned-equipment": _build_condemned_equipment,
|
||||||
|
"condemned_equipment": _build_condemned_equipment,
|
||||||
|
"pm-schedule": _build_pm_compliance,
|
||||||
|
"pm_schedule": _build_pm_compliance,
|
||||||
|
"calibration-schedule": _build_calibration_due,
|
||||||
|
"calibration_schedule": _build_calibration_due,
|
||||||
|
"breakdown-analysis": _build_breakdown_complaints,
|
||||||
|
"breakdown_analysis": _build_breakdown_complaints,
|
||||||
|
"amc-cmc-status": _build_contracts_warranty,
|
||||||
|
"amc_cmc_status": _build_contracts_warranty,
|
||||||
|
"daily-department-visit": _build_daily_visit,
|
||||||
|
"daily_department_visit": _build_daily_visit,
|
||||||
|
"monthly_department": _build_monthly_department,
|
||||||
|
"monthly_maintenance": _build_monthly_maintenance,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from ..models import User
|
||||||
|
from .permissions import Role
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class DepartmentScope:
|
||||||
|
is_unconstrained: bool
|
||||||
|
department_id: Optional[int]
|
||||||
|
is_empty: bool
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_department_scope(
|
||||||
|
user: User,
|
||||||
|
requested_dept_id: Optional[int] = None,
|
||||||
|
) -> DepartmentScope:
|
||||||
|
"""Resolve department scoping based on user role and assigned department.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
- If user.role != 'department_user': unconstrained, department_id=requested_dept_id, is_empty=False.
|
||||||
|
- If user.role == 'department_user' and user.department_id is None: is_empty=True, department_id=None, is_unconstrained=False.
|
||||||
|
- If user.role == 'department_user' and user.department_id is not None: is_empty=False, department_id=user.department_id
|
||||||
|
(requested_dept_id is ignored, cannot widen or change), is_unconstrained=False.
|
||||||
|
"""
|
||||||
|
if user.role != Role.department_user.value:
|
||||||
|
return DepartmentScope(
|
||||||
|
is_unconstrained=True,
|
||||||
|
department_id=requested_dept_id,
|
||||||
|
is_empty=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
if user.department_id is None:
|
||||||
|
return DepartmentScope(
|
||||||
|
is_unconstrained=False,
|
||||||
|
department_id=None,
|
||||||
|
is_empty=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return DepartmentScope(
|
||||||
|
is_unconstrained=False,
|
||||||
|
department_id=user.department_id,
|
||||||
|
is_empty=False,
|
||||||
|
)
|
||||||
@@ -237,6 +237,56 @@ SETTINGS_SCHEMA: list[dict[str, Any]] = [
|
|||||||
"max": 24,
|
"max": 24,
|
||||||
"options": None,
|
"options": None,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"key": "alert_repeat_days",
|
||||||
|
"type": "int",
|
||||||
|
"default": 3,
|
||||||
|
"label": "Overdue Alert Reminder Repeat Days",
|
||||||
|
"description": "Interval in days to repeat notifications for active overdue breakdown and maintenance alerts.",
|
||||||
|
"min": 1,
|
||||||
|
"max": 30,
|
||||||
|
"options": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "smtp_enabled",
|
||||||
|
"type": "bool",
|
||||||
|
"default": False,
|
||||||
|
"label": "Enable Email Notifications (SMTP)",
|
||||||
|
"description": "Enable automated email delivery for high-severity alerts once mail server is configured.",
|
||||||
|
"min": None,
|
||||||
|
"max": None,
|
||||||
|
"options": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "smtp_host",
|
||||||
|
"type": "str",
|
||||||
|
"default": "",
|
||||||
|
"label": "SMTP Host",
|
||||||
|
"description": "Hospital outbound mail server hostname (e.g. smtp.poonahospital.org).",
|
||||||
|
"min": None,
|
||||||
|
"max": None,
|
||||||
|
"options": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "smtp_port",
|
||||||
|
"type": "int",
|
||||||
|
"default": 587,
|
||||||
|
"label": "SMTP Port",
|
||||||
|
"description": "SMTP port (usually 587 for STARTTLS or 465 for SSL).",
|
||||||
|
"min": 1,
|
||||||
|
"max": 65535,
|
||||||
|
"options": None,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "smtp_from_email",
|
||||||
|
"type": "str",
|
||||||
|
"default": "ams-alerts@poonahospital.org",
|
||||||
|
"label": "SMTP From Email Address",
|
||||||
|
"description": "Sender email address displayed on alert notifications.",
|
||||||
|
"min": None,
|
||||||
|
"max": None,
|
||||||
|
"options": None,
|
||||||
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA}
|
SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[pytest]
|
||||||
|
# Tests share a session-scoped SQLite DB; run sequentially (no -n / no xdist).
|
||||||
|
# asyncio_mode silences the pytest-asyncio deprecation warning that causes
|
||||||
|
# PowerShell to report exit code 1 even when all tests pass.
|
||||||
|
asyncio_mode = strict
|
||||||
|
asyncio_default_fixture_loop_scope = function
|
||||||
|
filterwarnings =
|
||||||
|
ignore::pytest.PytestDeprecationWarning
|
||||||
|
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Poona Hospital Asset Management System (AMS)
|
||||||
|
Database & Attachments Backup and Disaster Recovery Utility.
|
||||||
|
|
||||||
|
Features:
|
||||||
|
- Online SQLite backup via sqlite3.Connection.backup (transactionally consistent, no locks)
|
||||||
|
- Bundles ams.db (and db.sqlite3) + uploads/ directory into a single timestamped archive (.tar.gz or .zip)
|
||||||
|
- PRAGMA integrity_check validation
|
||||||
|
- Retention policy rotation (retains the latest N backups, default: 7)
|
||||||
|
- Safe restore functionality with pre-restore fallback safety copy
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import datetime
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||||
|
datefmt="%Y-%m-%d %H:%M:%S",
|
||||||
|
)
|
||||||
|
logger = logging.getLogger("ams_backup")
|
||||||
|
|
||||||
|
|
||||||
|
def get_db_path(db_url: str | None, backend_dir: Path) -> Path:
|
||||||
|
"""Resolve database URL to a filesystem Path.
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
- If db_url is empty, None, or starts with 'sqlite:///:memory:', fall back to backend_dir / 'data' / 'ams.db'
|
||||||
|
- If it starts with 'sqlite:////' (4 slashes, absolute path), strip 'sqlite:///' and return Path('/app/data/ams.db') (absolute)
|
||||||
|
- If it starts with 'sqlite:///' (3 slashes), strip 'sqlite:///' and:
|
||||||
|
- if the remainder starts with '/' (absolute), return Path(remainder)
|
||||||
|
- if the remainder starts with './' or is a relative path, return (backend_dir / remainder).resolve()
|
||||||
|
- If it is not a sqlite URL, fall back to backend_dir / 'data' / 'ams.db'
|
||||||
|
"""
|
||||||
|
if not db_url or not db_url.strip() or db_url.strip().startswith("sqlite:///:memory:"):
|
||||||
|
return backend_dir / "data" / "ams.db"
|
||||||
|
|
||||||
|
clean_url = db_url.strip()
|
||||||
|
if not clean_url.startswith("sqlite:///"):
|
||||||
|
return backend_dir / "data" / "ams.db"
|
||||||
|
|
||||||
|
remainder = clean_url[len("sqlite:///"):]
|
||||||
|
if not remainder or remainder == ":memory:":
|
||||||
|
return backend_dir / "data" / "ams.db"
|
||||||
|
|
||||||
|
if remainder.startswith("/"):
|
||||||
|
return Path(remainder)
|
||||||
|
|
||||||
|
p = Path(remainder)
|
||||||
|
if p.is_absolute():
|
||||||
|
return p
|
||||||
|
|
||||||
|
return (backend_dir / remainder).resolve()
|
||||||
|
|
||||||
|
|
||||||
|
def get_default_paths() -> tuple[Path, Path, Path]:
|
||||||
|
script_dir = Path(__file__).resolve().parent
|
||||||
|
backend_dir = script_dir.parent
|
||||||
|
data_dir = backend_dir / "data"
|
||||||
|
|
||||||
|
db_url = os.environ.get("DATABASE_URL", "").strip()
|
||||||
|
db_path = get_db_path(db_url, backend_dir)
|
||||||
|
|
||||||
|
upload_env = os.environ.get("UPLOAD_DIR", "").strip()
|
||||||
|
if upload_env:
|
||||||
|
uploads_dir = Path(upload_env)
|
||||||
|
if not uploads_dir.is_absolute():
|
||||||
|
uploads_dir = backend_dir / uploads_dir
|
||||||
|
else:
|
||||||
|
uploads_dir = data_dir / "uploads"
|
||||||
|
|
||||||
|
backups_dir = data_dir / "backups"
|
||||||
|
return db_path, uploads_dir, backups_dir
|
||||||
|
|
||||||
|
|
||||||
|
def verify_sqlite_db(db_file: Path) -> bool:
|
||||||
|
"""Run PRAGMA integrity_check on a SQLite file."""
|
||||||
|
if not db_file.exists():
|
||||||
|
logger.error("DB file not found for verification: %s", db_file)
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
conn = sqlite3.connect(str(db_file))
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("PRAGMA integrity_check;")
|
||||||
|
rows = cursor.fetchall()
|
||||||
|
conn.close()
|
||||||
|
if len(rows) == 1 and rows[0][0] == "ok":
|
||||||
|
logger.info("SQLite integrity check PASSED for: %s", db_file.name)
|
||||||
|
return True
|
||||||
|
logger.error("SQLite integrity check FAILED: %s", rows)
|
||||||
|
return False
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Error verifying SQLite database: %s", e)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def create_backup(
|
||||||
|
db_path: Path | None = None,
|
||||||
|
uploads_dir: Path | None = None,
|
||||||
|
dest_dir: Path | None = None,
|
||||||
|
backups_dir: Path | None = None,
|
||||||
|
keep_count: int = 7,
|
||||||
|
archive_format: str = "tar.gz",
|
||||||
|
) -> Path | None:
|
||||||
|
"""Create a consistent online backup of SQLite DB and attachments into a .tar.gz or .zip archive."""
|
||||||
|
backend_dir = Path(__file__).resolve().parent.parent
|
||||||
|
if db_path is None:
|
||||||
|
db_url = os.environ.get("DATABASE_URL")
|
||||||
|
db_path = get_db_path(db_url, backend_dir)
|
||||||
|
|
||||||
|
target_dir = dest_dir or backups_dir or (backend_dir / "data" / "backups")
|
||||||
|
|
||||||
|
if not db_path.exists():
|
||||||
|
logger.error("Source database does not exist at %s", db_path)
|
||||||
|
return None
|
||||||
|
|
||||||
|
if uploads_dir is None:
|
||||||
|
upload_env = os.environ.get("UPLOAD_DIR", "").strip()
|
||||||
|
uploads_dir = Path(upload_env) if upload_env else (backend_dir / "data" / "uploads")
|
||||||
|
|
||||||
|
target_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||||
|
is_tar = archive_format in ("tar.gz", "tar", "tgz")
|
||||||
|
ext = "tar.gz" if is_tar else "zip"
|
||||||
|
backup_file_path = target_dir / f"ams_backup_{timestamp}.{ext}"
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as temp_dir:
|
||||||
|
temp_db_path = Path(temp_dir) / "ams.db"
|
||||||
|
|
||||||
|
# 1. Perform online SQLite backup
|
||||||
|
logger.info("Starting online backup of %s ...", db_path)
|
||||||
|
src_conn = sqlite3.connect(f"file:{db_path.resolve()}?mode=ro", uri=True)
|
||||||
|
dest_conn = sqlite3.connect(str(temp_db_path))
|
||||||
|
with dest_conn:
|
||||||
|
src_conn.backup(dest_conn)
|
||||||
|
dest_conn.close()
|
||||||
|
src_conn.close()
|
||||||
|
|
||||||
|
# 2. Verify backed-up database
|
||||||
|
if not verify_sqlite_db(temp_db_path):
|
||||||
|
logger.error("Integrity check failed on temporary backup. Aborting.")
|
||||||
|
return None
|
||||||
|
|
||||||
|
# 3. Create archive
|
||||||
|
logger.info("Creating backup archive: %s", backup_file_path)
|
||||||
|
if is_tar:
|
||||||
|
with tarfile.open(backup_file_path, "w:gz") as tf:
|
||||||
|
# Add database under both ams.db and db.sqlite3 for compatibility
|
||||||
|
tf.add(temp_db_path, arcname="db.sqlite3")
|
||||||
|
tf.add(temp_db_path, arcname="ams.db")
|
||||||
|
if uploads_dir.exists():
|
||||||
|
file_count = 0
|
||||||
|
for root, _, files in os.walk(uploads_dir):
|
||||||
|
for file in files:
|
||||||
|
full_path = Path(root) / file
|
||||||
|
rel_path = full_path.relative_to(uploads_dir)
|
||||||
|
tf.add(full_path, arcname=f"uploads/{rel_path}")
|
||||||
|
file_count += 1
|
||||||
|
logger.info("Archived %d attachment files from %s", file_count, uploads_dir)
|
||||||
|
else:
|
||||||
|
logger.warning("Uploads directory %s does not exist; skipping files.", uploads_dir)
|
||||||
|
else:
|
||||||
|
with zipfile.ZipFile(backup_file_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||||
|
zf.write(temp_db_path, arcname="ams.db")
|
||||||
|
zf.write(temp_db_path, arcname="db.sqlite3")
|
||||||
|
if uploads_dir.exists():
|
||||||
|
file_count = 0
|
||||||
|
for root, _, files in os.walk(uploads_dir):
|
||||||
|
for file in files:
|
||||||
|
full_path = Path(root) / file
|
||||||
|
rel_path = full_path.relative_to(uploads_dir)
|
||||||
|
zf.write(full_path, arcname=f"uploads/{rel_path}")
|
||||||
|
file_count += 1
|
||||||
|
logger.info("Archived %d attachment files from %s", file_count, uploads_dir)
|
||||||
|
else:
|
||||||
|
logger.warning("Uploads directory %s does not exist; skipping files.", uploads_dir)
|
||||||
|
|
||||||
|
size_mb = backup_file_path.stat().st_size / (1024 * 1024)
|
||||||
|
logger.info("Backup successfully completed! File: %s (%.2f MB)", backup_file_path, size_mb)
|
||||||
|
|
||||||
|
# 4. Enforce retention policy
|
||||||
|
if keep_count > 0:
|
||||||
|
existing_backups = sorted(
|
||||||
|
list(target_dir.glob("ams_backup_*.tar.gz")) + list(target_dir.glob("ams_backup_*.zip")),
|
||||||
|
key=lambda p: p.stat().st_mtime,
|
||||||
|
reverse=True,
|
||||||
|
)
|
||||||
|
if len(existing_backups) > keep_count:
|
||||||
|
for old_backup in existing_backups[keep_count:]:
|
||||||
|
logger.info("Retention policy: removing old backup %s", old_backup.name)
|
||||||
|
try:
|
||||||
|
old_backup.unlink()
|
||||||
|
except OSError as e:
|
||||||
|
logger.warning("Failed to remove old backup %s: %s", old_backup, e)
|
||||||
|
|
||||||
|
return backup_file_path
|
||||||
|
|
||||||
|
|
||||||
|
run_backup = create_backup
|
||||||
|
|
||||||
|
|
||||||
|
def run_restore(
|
||||||
|
backup_archive: Path,
|
||||||
|
db_path: Path,
|
||||||
|
uploads_dir: Path,
|
||||||
|
) -> bool:
|
||||||
|
"""Restore database and uploads from a backup archive (.tar.gz or .zip) with pre-restore safety copy."""
|
||||||
|
if not backup_archive.exists():
|
||||||
|
logger.error("Backup archive %s not found.", backup_archive)
|
||||||
|
return False
|
||||||
|
|
||||||
|
logger.info("Restoring from archive: %s", backup_archive)
|
||||||
|
with tempfile.TemporaryDirectory() as temp_dir:
|
||||||
|
# Extract archive
|
||||||
|
try:
|
||||||
|
if str(backup_archive).endswith((".tar.gz", ".tgz")):
|
||||||
|
with tarfile.open(backup_archive, "r:gz") as tf:
|
||||||
|
tf.extractall(temp_dir)
|
||||||
|
else:
|
||||||
|
with zipfile.ZipFile(backup_archive, "r") as zf:
|
||||||
|
zf.extractall(temp_dir)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Failed to read backup archive: %s", e)
|
||||||
|
return False
|
||||||
|
|
||||||
|
extracted_db = Path(temp_dir) / "ams.db"
|
||||||
|
if not extracted_db.exists():
|
||||||
|
extracted_db = Path(temp_dir) / "db.sqlite3"
|
||||||
|
if not extracted_db.exists():
|
||||||
|
logger.error("Archive does not contain ams.db or db.sqlite3. Invalid backup.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not verify_sqlite_db(extracted_db):
|
||||||
|
logger.error("Restored database failed integrity verification. Aborting restore.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Safety backup of current db if exists
|
||||||
|
if db_path.exists():
|
||||||
|
safety_copy = db_path.with_suffix(f".safety_pre_restore_{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.bak")
|
||||||
|
logger.info("Creating safety copy of existing DB: %s", safety_copy)
|
||||||
|
shutil.copy2(db_path, safety_copy)
|
||||||
|
|
||||||
|
# Copy restored DB into place
|
||||||
|
db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(extracted_db, db_path)
|
||||||
|
logger.info("Database restored successfully to %s", db_path)
|
||||||
|
|
||||||
|
# Restore uploads
|
||||||
|
extracted_uploads = Path(temp_dir) / "uploads"
|
||||||
|
if extracted_uploads.exists():
|
||||||
|
uploads_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
restored_count = 0
|
||||||
|
for root, _, files in os.walk(extracted_uploads):
|
||||||
|
for file in files:
|
||||||
|
src_f = Path(root) / file
|
||||||
|
rel_p = src_f.relative_to(extracted_uploads)
|
||||||
|
dest_f = uploads_dir / rel_p
|
||||||
|
dest_f.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(src_f, dest_f)
|
||||||
|
restored_count += 1
|
||||||
|
logger.info("Restored %d attachment files to %s", restored_count, uploads_dir)
|
||||||
|
|
||||||
|
logger.info("Restore process completed successfully.")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
default_db, default_uploads, default_backups = get_default_paths()
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description="Poona Hospital AMS Backup & Recovery Utility")
|
||||||
|
subparsers = parser.add_subparsers(dest="command", help="Command to execute")
|
||||||
|
|
||||||
|
# Backup command
|
||||||
|
backup_parser = subparsers.add_parser("backup", help="Create a backup archive of DB and uploads")
|
||||||
|
backup_parser.add_argument("--db", type=Path, default=default_db, help="Path to SQLite ams.db")
|
||||||
|
backup_parser.add_argument("--uploads", type=Path, default=default_uploads, help="Path to uploads directory")
|
||||||
|
backup_parser.add_argument("--dest", type=Path, default=default_backups, help="Destination directory for backups")
|
||||||
|
backup_parser.add_argument("--keep", type=int, default=7, help="Number of latest backups to retain (0 to disable)")
|
||||||
|
backup_parser.add_argument("--format", choices=["tar.gz", "zip"], default="tar.gz", help="Archive format")
|
||||||
|
|
||||||
|
# Restore command
|
||||||
|
restore_parser = subparsers.add_parser("restore", help="Restore DB and uploads from a backup archive")
|
||||||
|
restore_parser.add_argument("archive", type=Path, help="Path to backup archive (.tar.gz or .zip)")
|
||||||
|
restore_parser.add_argument("--db", type=Path, default=default_db, help="Destination path for ams.db")
|
||||||
|
restore_parser.add_argument("--uploads", type=Path, default=default_uploads, help="Destination directory for uploads")
|
||||||
|
|
||||||
|
# Verify command
|
||||||
|
verify_parser = subparsers.add_parser("verify", help="Verify the integrity of a backup archive or SQLite DB")
|
||||||
|
verify_parser.add_argument("target", type=Path, help="Path to archive (.tar.gz or .zip) or .db file to verify")
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
# Default to backup if no command provided
|
||||||
|
if not args.command:
|
||||||
|
result = create_backup(default_db, default_uploads, default_backups, keep_count=7, archive_format="tar.gz")
|
||||||
|
return 0 if result is not None else 1
|
||||||
|
|
||||||
|
if args.command == "backup":
|
||||||
|
result = create_backup(args.db, args.uploads, args.dest, keep_count=args.keep, archive_format=args.format)
|
||||||
|
return 0 if result is not None else 1
|
||||||
|
|
||||||
|
if args.command == "restore":
|
||||||
|
success = run_restore(args.archive, args.db, args.uploads)
|
||||||
|
return 0 if success else 1
|
||||||
|
|
||||||
|
if args.command == "verify":
|
||||||
|
target = args.target
|
||||||
|
if str(target).endswith((".tar.gz", ".tgz")):
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
with tarfile.open(target, "r:gz") as tf:
|
||||||
|
names = tf.getnames()
|
||||||
|
db_name = "ams.db" if "ams.db" in names else ("db.sqlite3" if "db.sqlite3" in names else None)
|
||||||
|
if not db_name:
|
||||||
|
logger.error("Archive does not contain ams.db or db.sqlite3")
|
||||||
|
return 1
|
||||||
|
tf.extract(db_name, td)
|
||||||
|
db_file = Path(td) / db_name
|
||||||
|
return 0 if verify_sqlite_db(db_file) else 1
|
||||||
|
elif target.suffix == ".zip":
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
with zipfile.ZipFile(target, "r") as zf:
|
||||||
|
names = zf.namelist()
|
||||||
|
db_name = "ams.db" if "ams.db" in names else ("db.sqlite3" if "db.sqlite3" in names else None)
|
||||||
|
if not db_name:
|
||||||
|
logger.error("ZIP does not contain ams.db or db.sqlite3")
|
||||||
|
return 1
|
||||||
|
zf.extract(db_name, td)
|
||||||
|
db_file = Path(td) / db_name
|
||||||
|
return 0 if verify_sqlite_db(db_file) else 1
|
||||||
|
elif target.suffix in (".db", ".sqlite", ".sqlite3"):
|
||||||
|
return 0 if verify_sqlite_db(target) else 1
|
||||||
|
else:
|
||||||
|
logger.error("Target must be a .tar.gz/.zip archive or .db file")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -54,8 +54,8 @@ def test_import_template_download_and_rbac(client):
|
|||||||
assert 'filename="asset_import_template.xlsx"' in res.headers["content-disposition"]
|
assert 'filename="asset_import_template.xlsx"' in res.headers["content-disposition"]
|
||||||
|
|
||||||
wb = openpyxl.load_workbook(BytesIO(res.content))
|
wb = openpyxl.load_workbook(BytesIO(res.content))
|
||||||
assert "Assets" in wb.sheetnames
|
assert wb.sheetnames == ["Assets", "Example", "Master Reference"]
|
||||||
assert "Master Reference" in wb.sheetnames
|
assert wb["Example"].cell(row=1, column=1).value == "Example only - this sheet is ignored on import"
|
||||||
ws = wb["Assets"]
|
ws = wb["Assets"]
|
||||||
headers = [ws.cell(row=1, column=i).value for i in range(1, 16)]
|
headers = [ws.cell(row=1, column=i).value for i in range(1, 16)]
|
||||||
assert headers[:6] == ["asset_code", "serial_no", "name", "category", "department", "location"]
|
assert headers[:6] == ["asset_code", "serial_no", "name", "category", "department", "location"]
|
||||||
@@ -71,8 +71,8 @@ def test_bulk_import_dry_run_validation_and_commit(client, db):
|
|||||||
# Read a valid sample from template so we match real seeded department/location/category
|
# Read a valid sample from template so we match real seeded department/location/category
|
||||||
tmpl_res = client.get("/api/assets/import-template", headers=bio_headers)
|
tmpl_res = client.get("/api/assets/import-template", headers=bio_headers)
|
||||||
wb_tmpl = openpyxl.load_workbook(BytesIO(tmpl_res.content))
|
wb_tmpl = openpyxl.load_workbook(BytesIO(tmpl_res.content))
|
||||||
ws_tmpl = wb_tmpl["Assets"]
|
ws_tmpl = wb_tmpl["Example"]
|
||||||
headers = [ws_tmpl.cell(row=1, column=i).value for i in range(1, 16)]
|
headers = [wb_tmpl["Assets"].cell(row=1, column=i).value for i in range(1, 16)]
|
||||||
cat_name = ws_tmpl.cell(row=2, column=4).value
|
cat_name = ws_tmpl.cell(row=2, column=4).value
|
||||||
dept_code = ws_tmpl.cell(row=2, column=5).value
|
dept_code = ws_tmpl.cell(row=2, column=5).value
|
||||||
loc_name = ws_tmpl.cell(row=2, column=6).value
|
loc_name = ws_tmpl.cell(row=2, column=6).value
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sqlite3
|
||||||
|
import tarfile
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from scripts.backup import create_backup, get_db_path
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_db_path_relative_dot_slash():
|
||||||
|
backend_dir = Path("/mock/backend").resolve()
|
||||||
|
p = get_db_path("sqlite:///./data/ams.db", backend_dir)
|
||||||
|
assert p == (backend_dir / "data" / "ams.db").resolve()
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_db_path_relative_plain():
|
||||||
|
backend_dir = Path("/mock/backend").resolve()
|
||||||
|
p = get_db_path("sqlite:///data/ams.db", backend_dir)
|
||||||
|
assert p == (backend_dir / "data" / "ams.db").resolve()
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_db_path_absolute_app():
|
||||||
|
backend_dir = Path("/mock/backend").resolve()
|
||||||
|
p = get_db_path("sqlite:////app/data/ams.db", backend_dir)
|
||||||
|
assert p == Path("/app/data/ams.db")
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_db_path_absolute_tmp():
|
||||||
|
backend_dir = Path("/mock/backend").resolve()
|
||||||
|
p = get_db_path("sqlite:////tmp/x/custom.db", backend_dir)
|
||||||
|
assert p == Path("/tmp/x/custom.db")
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_db_path_fallbacks():
|
||||||
|
backend_dir = Path("/mock/backend").resolve()
|
||||||
|
default_expected = backend_dir / "data" / "ams.db"
|
||||||
|
assert get_db_path(None, backend_dir) == default_expected
|
||||||
|
assert get_db_path("", backend_dir) == default_expected
|
||||||
|
assert get_db_path("sqlite:///:memory:", backend_dir) == default_expected
|
||||||
|
assert get_db_path("postgresql://localhost/ams", backend_dir) == default_expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_backup_real_temp_sqlite_file(tmp_path):
|
||||||
|
# Create real SQLite file
|
||||||
|
db_file = tmp_path / "source.db"
|
||||||
|
conn = sqlite3.connect(str(db_file))
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute("CREATE TABLE test_table (id INTEGER PRIMARY KEY, note TEXT);")
|
||||||
|
cur.execute("INSERT INTO test_table (note) VALUES ('backup test');")
|
||||||
|
conn.commit()
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
uploads_dir = tmp_path / "uploads"
|
||||||
|
uploads_dir.mkdir()
|
||||||
|
(uploads_dir / "sample.pdf").write_bytes(b"%PDF-1.4 sample content")
|
||||||
|
|
||||||
|
dest_dir = tmp_path / "backups"
|
||||||
|
dest_dir.mkdir()
|
||||||
|
|
||||||
|
# Run backup producing a .tar.gz
|
||||||
|
archive_path = create_backup(
|
||||||
|
db_path=db_file,
|
||||||
|
uploads_dir=uploads_dir,
|
||||||
|
dest_dir=dest_dir,
|
||||||
|
archive_format="tar.gz",
|
||||||
|
)
|
||||||
|
assert archive_path is not None
|
||||||
|
assert archive_path.exists()
|
||||||
|
assert str(archive_path).endswith(".tar.gz")
|
||||||
|
|
||||||
|
# Verify that the tar.gz is valid and contains db.sqlite3
|
||||||
|
with tarfile.open(archive_path, "r:gz") as tf:
|
||||||
|
names = tf.getnames()
|
||||||
|
assert "db.sqlite3" in names
|
||||||
|
assert "ams.db" in names
|
||||||
|
assert any("uploads/sample.pdf" in n for n in names)
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
from io import BytesIO
|
||||||
|
import openpyxl
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.models import Asset, CalibrationPlan, CalibrationRecord, Contract, InsurancePolicy, Vendor
|
||||||
|
from app.seed.seed import seed_database
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module", autouse=True)
|
||||||
|
def seeded_extra_import_db(db, tmp_path_factory):
|
||||||
|
upload_dir = tmp_path_factory.mktemp("extra_import_test_uploads")
|
||||||
|
seed_database(db, upload_dir=upload_dir)
|
||||||
|
return upload_dir
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||||
|
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||||
|
|
||||||
|
|
||||||
|
def _make_xlsx_bytes(sheet_name: str, headers: list[str], rows: list[list[object]]) -> bytes:
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = sheet_name
|
||||||
|
ws.append(headers)
|
||||||
|
for r in rows:
|
||||||
|
ws.append(r)
|
||||||
|
buf = BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_contracts_bulk_import_lifecycle(client, db):
|
||||||
|
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||||
|
|
||||||
|
asset = db.query(Asset).filter(Asset.asset_code.isnot(None)).first()
|
||||||
|
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||||
|
assert asset is not None
|
||||||
|
assert vendor is not None
|
||||||
|
|
||||||
|
headers = [
|
||||||
|
"asset_code",
|
||||||
|
"provider_name",
|
||||||
|
"contract_type",
|
||||||
|
"start_date",
|
||||||
|
"end_date",
|
||||||
|
"cost",
|
||||||
|
"coverage_details",
|
||||||
|
"remarks",
|
||||||
|
]
|
||||||
|
|
||||||
|
# 1 valid, 1 invalid (invalid contract_type)
|
||||||
|
rows = [
|
||||||
|
[
|
||||||
|
asset.asset_code,
|
||||||
|
vendor.name,
|
||||||
|
"CMC",
|
||||||
|
"2026-01-01",
|
||||||
|
"2026-12-31",
|
||||||
|
85000,
|
||||||
|
"All parts included",
|
||||||
|
"Annual contract",
|
||||||
|
],
|
||||||
|
[
|
||||||
|
asset.asset_code,
|
||||||
|
vendor.name,
|
||||||
|
"INVALID_TYPE",
|
||||||
|
"2026-01-01",
|
||||||
|
"2026-12-31",
|
||||||
|
50000,
|
||||||
|
"Test",
|
||||||
|
"Test remarks",
|
||||||
|
],
|
||||||
|
]
|
||||||
|
|
||||||
|
xlsx_bytes = _make_xlsx_bytes("Contracts", headers, rows)
|
||||||
|
|
||||||
|
# Dry run
|
||||||
|
res = client.post(
|
||||||
|
"/api/contracts/bulk-import?dry_run=true",
|
||||||
|
headers=admin_headers,
|
||||||
|
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
data = res.json()
|
||||||
|
assert data["dry_run"] is True
|
||||||
|
assert data["total_rows"] == 2
|
||||||
|
assert data["valid_count"] == 1
|
||||||
|
assert data["error_count"] == 1
|
||||||
|
assert data["created_count"] == 0
|
||||||
|
|
||||||
|
# Fail commit without skip_invalid
|
||||||
|
res_fail = client.post(
|
||||||
|
"/api/contracts/bulk-import?dry_run=false&skip_invalid=false",
|
||||||
|
headers=admin_headers,
|
||||||
|
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
)
|
||||||
|
assert res_fail.status_code == 400
|
||||||
|
|
||||||
|
# Commit with skip_invalid
|
||||||
|
res_commit = client.post(
|
||||||
|
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
|
||||||
|
headers=admin_headers,
|
||||||
|
files={"file": ("contracts_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
)
|
||||||
|
assert res_commit.status_code == 200
|
||||||
|
commit_data = res_commit.json()
|
||||||
|
assert commit_data["created_count"] == 1
|
||||||
|
|
||||||
|
created_contract = (
|
||||||
|
db.query(Contract)
|
||||||
|
.filter(Contract.asset_id == asset.id, Contract.contract_type == "CMC")
|
||||||
|
.order_by(Contract.id.desc())
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
assert created_contract is not None
|
||||||
|
assert created_contract.provider_id == vendor.id
|
||||||
|
|
||||||
|
|
||||||
|
def test_calibration_bulk_import_lifecycle(client, db):
|
||||||
|
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||||
|
|
||||||
|
# Find asset without calibration plan
|
||||||
|
existing_plan_ids = [p.asset_id for p in db.query(CalibrationPlan.asset_id).all()]
|
||||||
|
asset = db.query(Asset).filter(Asset.id.notin_(existing_plan_ids)).first()
|
||||||
|
assert asset is not None
|
||||||
|
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||||
|
assert vendor is not None
|
||||||
|
|
||||||
|
headers = [
|
||||||
|
"asset_code",
|
||||||
|
"frequency_months",
|
||||||
|
"agency_name",
|
||||||
|
"scope",
|
||||||
|
"standards",
|
||||||
|
"remarks",
|
||||||
|
]
|
||||||
|
|
||||||
|
rows = [
|
||||||
|
[
|
||||||
|
asset.asset_code,
|
||||||
|
12,
|
||||||
|
vendor.name,
|
||||||
|
"Accuracy verification",
|
||||||
|
"ISO 17025",
|
||||||
|
"Imported plan",
|
||||||
|
],
|
||||||
|
]
|
||||||
|
|
||||||
|
xlsx_bytes = _make_xlsx_bytes("Calibration Plans", headers, rows)
|
||||||
|
|
||||||
|
# Dry run
|
||||||
|
res = client.post(
|
||||||
|
"/api/calibration/bulk-import?dry_run=true",
|
||||||
|
headers=admin_headers,
|
||||||
|
files={"file": ("cal_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
data = res.json()
|
||||||
|
assert data["valid_count"] == 1
|
||||||
|
assert data["error_count"] == 0
|
||||||
|
|
||||||
|
# Commit
|
||||||
|
res_commit = client.post(
|
||||||
|
"/api/calibration/bulk-import?dry_run=false",
|
||||||
|
headers=admin_headers,
|
||||||
|
files={"file": ("cal_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
)
|
||||||
|
assert res_commit.status_code == 200
|
||||||
|
assert res_commit.json()["created_count"] == 1
|
||||||
|
|
||||||
|
plan = db.query(CalibrationPlan).filter(CalibrationPlan.asset_id == asset.id).first()
|
||||||
|
assert plan is not None
|
||||||
|
assert plan.frequency_months == 12
|
||||||
|
|
||||||
|
record = db.query(CalibrationRecord).filter(CalibrationRecord.plan_id == plan.id).first()
|
||||||
|
assert record is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_insurance_bulk_import_lifecycle(client, db):
|
||||||
|
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||||
|
|
||||||
|
asset = db.query(Asset).filter(Asset.asset_code.isnot(None)).first()
|
||||||
|
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||||
|
assert asset is not None
|
||||||
|
assert vendor is not None
|
||||||
|
|
||||||
|
headers = [
|
||||||
|
"asset_code",
|
||||||
|
"insurer_name",
|
||||||
|
"policy_number",
|
||||||
|
"start_date",
|
||||||
|
"end_date",
|
||||||
|
"insured_value",
|
||||||
|
"premium",
|
||||||
|
"remarks",
|
||||||
|
]
|
||||||
|
|
||||||
|
rows = [
|
||||||
|
[
|
||||||
|
asset.asset_code,
|
||||||
|
vendor.name,
|
||||||
|
"POL-TEST-9999",
|
||||||
|
"2026-04-01",
|
||||||
|
"2027-03-31",
|
||||||
|
1200000,
|
||||||
|
15000,
|
||||||
|
"Annual equipment insurance",
|
||||||
|
],
|
||||||
|
]
|
||||||
|
|
||||||
|
xlsx_bytes = _make_xlsx_bytes("Insurance Policies", headers, rows)
|
||||||
|
|
||||||
|
# Dry run
|
||||||
|
res = client.post(
|
||||||
|
"/api/insurance/bulk-import?dry_run=true",
|
||||||
|
headers=admin_headers,
|
||||||
|
files={"file": ("ins_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
data = res.json()
|
||||||
|
assert data["valid_count"] == 1
|
||||||
|
assert data["error_count"] == 0
|
||||||
|
|
||||||
|
# Commit
|
||||||
|
res_commit = client.post(
|
||||||
|
"/api/insurance/bulk-import?dry_run=false",
|
||||||
|
headers=admin_headers,
|
||||||
|
files={"file": ("ins_test.xlsx", xlsx_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
)
|
||||||
|
assert res_commit.status_code == 200
|
||||||
|
assert res_commit.json()["created_count"] == 1
|
||||||
|
|
||||||
|
pol = db.query(InsurancePolicy).filter(InsurancePolicy.policy_no == "POL-TEST-9999").first()
|
||||||
|
assert pol is not None
|
||||||
|
assert pol.coverage_amount == 1200000
|
||||||
|
assert pol.asset_id == asset.id
|
||||||
|
|
||||||
@@ -553,6 +553,38 @@ def test_sla_breach_alert_emitted_and_suppressed_when_restored(client, db):
|
|||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
assert crit_unrestored == []
|
assert crit_unrestored == []
|
||||||
|
|
||||||
|
# When open > 24h, unrestored complaint triggers critical_complaint alert,
|
||||||
|
# but restored complaint does NOT trigger it even if not closed yet
|
||||||
|
past_26h = now - timedelta(hours=26)
|
||||||
|
c_unrestored.registered_at = past_26h
|
||||||
|
c_restored.registered_at = past_26h
|
||||||
|
db.commit()
|
||||||
|
run_alert_check(db)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
crit_unrestored_26h = (
|
||||||
|
db.query(Notification)
|
||||||
|
.filter(
|
||||||
|
Notification.type == "critical_complaint",
|
||||||
|
Notification.entity_type == "complaint",
|
||||||
|
Notification.entity_id == cid_unrestored,
|
||||||
|
)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
assert len(crit_unrestored_26h) == 1
|
||||||
|
assert "Critical Complaint Open > 24h" in crit_unrestored_26h[0].title
|
||||||
|
|
||||||
|
crit_restored_26h = (
|
||||||
|
db.query(Notification)
|
||||||
|
.filter(
|
||||||
|
Notification.type == "critical_complaint",
|
||||||
|
Notification.entity_type == "complaint",
|
||||||
|
Notification.entity_id == cid_restored,
|
||||||
|
)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
assert crit_restored_26h == []
|
||||||
finally:
|
finally:
|
||||||
db.query(Notification).filter(
|
db.query(Notification).filter(
|
||||||
Notification.entity_type == "complaint",
|
Notification.entity_type == "complaint",
|
||||||
|
|||||||
@@ -0,0 +1,234 @@
|
|||||||
|
from io import BytesIO
|
||||||
|
from datetime import date, timedelta
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.core.time_utils import effective_today
|
||||||
|
from app.models import Asset, Department, Location, PMRecord, PMSchedule, Vendor
|
||||||
|
from app.seed.seed import seed_database
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module", autouse=True)
|
||||||
|
def _seed(db, tmp_path_factory):
|
||||||
|
upload_dir = tmp_path_factory.mktemp("uploads")
|
||||||
|
seed_database(db, upload_dir=upload_dir)
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||||
|
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
token = res.json()["access_token"]
|
||||||
|
return {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_pm_record_attachment_upload_and_download(client, db):
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
pm_rec = db.query(PMRecord).first()
|
||||||
|
assert pm_rec is not None
|
||||||
|
|
||||||
|
# Valid PDF file upload against pm_record
|
||||||
|
fake_pdf = b"%PDF-1.4 sample pm service report job sheet content"
|
||||||
|
files = {"file": ("pm_service_report.pdf", BytesIO(fake_pdf), "application/pdf")}
|
||||||
|
data = {"entity_type": "pm_record", "entity_id": str(pm_rec.id)}
|
||||||
|
|
||||||
|
upload_res = client.post("/api/attachments", headers=bio_headers, data=data, files=files)
|
||||||
|
assert upload_res.status_code == 201, upload_res.text
|
||||||
|
att_data = upload_res.json()
|
||||||
|
att_id = att_data["id"]
|
||||||
|
assert att_data["entity_type"] == "pm_record"
|
||||||
|
assert att_data["original_name"] == "pm_service_report.pdf"
|
||||||
|
|
||||||
|
# List attachments for pm_record
|
||||||
|
list_res = client.get(
|
||||||
|
f"/api/attachments?entity_type=pm_record&entity_id={pm_rec.id}",
|
||||||
|
headers=bio_headers,
|
||||||
|
)
|
||||||
|
assert list_res.status_code == 200
|
||||||
|
assert any(item["id"] == att_id for item in list_res.json()["items"])
|
||||||
|
|
||||||
|
# Download attachment
|
||||||
|
dl_res = client.get(f"/api/attachments/{att_id}/download", headers=bio_headers)
|
||||||
|
assert dl_res.status_code == 200
|
||||||
|
assert dl_res.content == fake_pdf
|
||||||
|
|
||||||
|
|
||||||
|
def test_complaint_assigned_team_and_location_filter(client, db):
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
asset = db.query(Asset).filter(Asset.location_id.isnot(None)).first()
|
||||||
|
assert asset is not None
|
||||||
|
|
||||||
|
# 1. Raise complaint with assigned_team
|
||||||
|
res = client.post(
|
||||||
|
"/api/complaints",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={
|
||||||
|
"asset_id": asset.id,
|
||||||
|
"description": "Ventilator screen flickering",
|
||||||
|
"priority": "non_critical",
|
||||||
|
"assigned_team": "Biomedical Clinical Support",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert res.status_code == 201, res.text
|
||||||
|
c_data = res.json()
|
||||||
|
cid = c_data["id"]
|
||||||
|
assert c_data["assigned_team"] == "Biomedical Clinical Support"
|
||||||
|
|
||||||
|
# 2. Assign team via /assign endpoint
|
||||||
|
assign_res = client.post(
|
||||||
|
f"/api/complaints/{cid}/assign",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={"assigned_team": "External Vendor Tier 2 Team", "note": "Assigned to specialized vendor team"},
|
||||||
|
)
|
||||||
|
assert assign_res.status_code == 200, assign_res.text
|
||||||
|
assert assign_res.json()["assigned_team"] == "External Vendor Tier 2 Team"
|
||||||
|
|
||||||
|
# 3. Filter by location_id
|
||||||
|
loc_res = client.get(
|
||||||
|
f"/api/complaints?location_id={asset.location_id}",
|
||||||
|
headers=bio_headers,
|
||||||
|
)
|
||||||
|
assert loc_res.status_code == 200
|
||||||
|
items = loc_res.json()["items"]
|
||||||
|
assert any(c["id"] == cid for c in items)
|
||||||
|
|
||||||
|
|
||||||
|
def test_demo_equipment_serial_no(client, db):
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
dept = db.query(Department).first()
|
||||||
|
vendor = db.query(Vendor).first()
|
||||||
|
today = effective_today(db)
|
||||||
|
|
||||||
|
# Create demo equipment with serial_no
|
||||||
|
res = client.post(
|
||||||
|
"/api/demo-equipment",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={
|
||||||
|
"name": "Trial Dialysis Unit",
|
||||||
|
"equipment_type": "Dialysis",
|
||||||
|
"serial_no": "DEMO-SN-DIAL-901",
|
||||||
|
"supplier_id": vendor.id,
|
||||||
|
"department_id": dept.id,
|
||||||
|
"start_date": str(today),
|
||||||
|
"expected_return_date": str(today + timedelta(days=14)),
|
||||||
|
"remarks": "Evaluation unit on 14-day trial",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert res.status_code == 201, res.text
|
||||||
|
demo_data = res.json()
|
||||||
|
demo_id = demo_data["id"]
|
||||||
|
assert demo_data["serial_no"] == "DEMO-SN-DIAL-901"
|
||||||
|
|
||||||
|
# List demo equipment
|
||||||
|
list_res = client.get(f"/api/demo-equipment?department_id={dept.id}", headers=bio_headers)
|
||||||
|
assert list_res.status_code == 200
|
||||||
|
found = next((item for item in list_res.json()["items"] if item["id"] == demo_id), None)
|
||||||
|
assert found is not None
|
||||||
|
assert found["serial_no"] == "DEMO-SN-DIAL-901"
|
||||||
|
|
||||||
|
|
||||||
|
def test_department_visit_new_requirements_and_monthly_report(client, db):
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||||
|
dept = db.query(Department).first()
|
||||||
|
today = effective_today(db)
|
||||||
|
|
||||||
|
# Create visit with new_requirements
|
||||||
|
req_text = "Urgent: Requesting 2 additional Infusion Pumps for Bed 3 & 4"
|
||||||
|
res = client.post(
|
||||||
|
"/api/visits",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={
|
||||||
|
"department_id": dept.id,
|
||||||
|
"visit_date": str(today),
|
||||||
|
"observations": "All ICU ventilators functioning normally; routine checks complete.",
|
||||||
|
"new_requirements": req_text,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert res.status_code == 201, res.text
|
||||||
|
v_data = res.json()
|
||||||
|
assert v_data["new_requirements"] == req_text
|
||||||
|
|
||||||
|
# Monthly Department Report reflects new requirements
|
||||||
|
month_str = today.strftime("%Y-%m")
|
||||||
|
rep_res = client.get(
|
||||||
|
f"/api/reports/monthly-department?month={month_str}&department_id={dept.id}",
|
||||||
|
headers=mgmt_headers,
|
||||||
|
)
|
||||||
|
assert rep_res.status_code == 200, rep_res.text
|
||||||
|
rows = rep_res.json()["rows"]
|
||||||
|
dept_row = next((r for r in rows if r["department_id"] == dept.id), None)
|
||||||
|
assert dept_row is not None
|
||||||
|
assert req_text in dept_row["new_equipment_requirements"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_asset_calibration_and_insurance_filters(client, db):
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
|
||||||
|
# Filter calibration applicable
|
||||||
|
res_cal_yes = client.get("/api/assets?requires_calibration=true", headers=bio_headers)
|
||||||
|
assert res_cal_yes.status_code == 200
|
||||||
|
for a in res_cal_yes.json()["items"]:
|
||||||
|
assert a["requires_calibration"] is True
|
||||||
|
|
||||||
|
res_cal_no = client.get("/api/assets?requires_calibration=false", headers=bio_headers)
|
||||||
|
assert res_cal_no.status_code == 200
|
||||||
|
for a in res_cal_no.json()["items"]:
|
||||||
|
assert a["requires_calibration"] is False
|
||||||
|
|
||||||
|
# Filter insurance applicable
|
||||||
|
res_ins_yes = client.get("/api/assets?insurance_applicable=true", headers=bio_headers)
|
||||||
|
assert res_ins_yes.status_code == 200
|
||||||
|
for a in res_ins_yes.json()["items"]:
|
||||||
|
assert a["insurance_applicable"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_bulk_import_templates_endpoints(client):
|
||||||
|
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||||
|
|
||||||
|
# Contracts template
|
||||||
|
r_c = client.get("/api/contracts/import-template", headers=coord_headers)
|
||||||
|
assert r_c.status_code == 200
|
||||||
|
assert r_c.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
|
assert len(r_c.content) > 1000
|
||||||
|
|
||||||
|
# Calibration template
|
||||||
|
r_cal = client.get("/api/calibration/import-template", headers=coord_headers)
|
||||||
|
assert r_cal.status_code == 200
|
||||||
|
assert r_cal.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
|
assert len(r_cal.content) > 1000
|
||||||
|
|
||||||
|
# Insurance template
|
||||||
|
r_ins = client.get("/api/insurance/import-template", headers=coord_headers)
|
||||||
|
assert r_ins.status_code == 200
|
||||||
|
assert r_ins.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
|
assert len(r_ins.content) > 1000
|
||||||
|
|
||||||
|
|
||||||
|
def test_sqlite_auto_migration_reconciles_missing_columns():
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from app.core.migrations import run_sqlite_migrations
|
||||||
|
|
||||||
|
test_eng = create_engine("sqlite:///:memory:")
|
||||||
|
with test_eng.begin() as conn:
|
||||||
|
# Create complaints table without assigned_team column
|
||||||
|
conn.exec_driver_sql(
|
||||||
|
"CREATE TABLE complaints ("
|
||||||
|
"id INTEGER PRIMARY KEY, "
|
||||||
|
"complaint_no VARCHAR(50), "
|
||||||
|
"asset_id INTEGER, "
|
||||||
|
"description TEXT, "
|
||||||
|
"priority VARCHAR(50), "
|
||||||
|
"registered_at DATETIME, "
|
||||||
|
"registered_by_id INTEGER, "
|
||||||
|
"received_by_id INTEGER, "
|
||||||
|
"call_status VARCHAR(50)"
|
||||||
|
")"
|
||||||
|
)
|
||||||
|
cols_before = {r[1] for r in conn.exec_driver_sql("PRAGMA table_info(complaints)").fetchall()}
|
||||||
|
assert "assigned_team" not in cols_before
|
||||||
|
|
||||||
|
# Run auto-migration
|
||||||
|
run_sqlite_migrations(test_eng)
|
||||||
|
|
||||||
|
with test_eng.begin() as conn:
|
||||||
|
cols_after = {r[1] for r in conn.exec_driver_sql("PRAGMA table_info(complaints)").fetchall()}
|
||||||
|
assert "assigned_team" in cols_after
|
||||||
@@ -242,3 +242,34 @@ def test_report_exports_xlsx_and_csv(client):
|
|||||||
headers=mgmt_headers,
|
headers=mgmt_headers,
|
||||||
)
|
)
|
||||||
assert bad_fmt.status_code == 422
|
assert bad_fmt.status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
def test_all_eight_reports_export_xlsx_and_csv(client):
|
||||||
|
"""Verify that all 8 reports export cleanly as both XLSX and CSV without title/slash errors."""
|
||||||
|
admin_headers = _auth_headers(client, "admin@poona.demo")
|
||||||
|
|
||||||
|
for key in ALL_REPORT_KEYS:
|
||||||
|
# Test XLSX export
|
||||||
|
xlsx_res = client.get(
|
||||||
|
f"/api/reports/{key}/export?format=xlsx",
|
||||||
|
headers=admin_headers,
|
||||||
|
)
|
||||||
|
assert xlsx_res.status_code == 200, f"XLSX export failed for {key}: {xlsx_res.text}"
|
||||||
|
assert "spreadsheetml.sheet" in xlsx_res.headers["content-type"]
|
||||||
|
assert f'filename="{key}.xlsx"' in xlsx_res.headers["content-disposition"]
|
||||||
|
|
||||||
|
wb = openpyxl.load_workbook(BytesIO(xlsx_res.content))
|
||||||
|
ws = wb.active
|
||||||
|
assert ws is not None
|
||||||
|
assert "/" not in ws.title and "\\" not in ws.title
|
||||||
|
assert len(ws.title) <= 31
|
||||||
|
|
||||||
|
# Test CSV export
|
||||||
|
csv_res = client.get(
|
||||||
|
f"/api/reports/{key}/export?format=csv",
|
||||||
|
headers=admin_headers,
|
||||||
|
)
|
||||||
|
assert csv_res.status_code == 200, f"CSV export failed for {key}: {csv_res.text}"
|
||||||
|
assert "text/csv" in csv_res.headers["content-type"]
|
||||||
|
assert f'filename="{key}.csv"' in csv_res.headers["content-disposition"]
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,260 @@
|
|||||||
|
from io import BytesIO
|
||||||
|
from datetime import date
|
||||||
|
import openpyxl
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.models import Asset, CalibrationPlan, Contract, Department, InsurancePolicy, Vendor
|
||||||
|
from app.seed.seed import seed_database
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module", autouse=True)
|
||||||
|
def seeded_task1_db(db, tmp_path_factory):
|
||||||
|
upload_dir = tmp_path_factory.mktemp("task1_test_uploads")
|
||||||
|
seed_database(db, upload_dir=upload_dir)
|
||||||
|
return upload_dir
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_headers(client, email: str = "admin@poona.demo") -> dict[str, str]:
|
||||||
|
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||||
|
|
||||||
|
|
||||||
|
def _make_xlsx_bytes(sheet_name: str, headers: list[str], rows: list[list]) -> bytes:
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = sheet_name
|
||||||
|
ws.append(headers)
|
||||||
|
for r in rows:
|
||||||
|
ws.append(r)
|
||||||
|
buf = BytesIO()
|
||||||
|
wb.save(buf)
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_contracts_api_duplicate_409(client, db):
|
||||||
|
headers = _auth_headers(client)
|
||||||
|
asset = db.query(Asset).first()
|
||||||
|
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||||
|
assert asset and vendor
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"asset_id": asset.id,
|
||||||
|
"contract_type": "AMC",
|
||||||
|
"provider_id": vendor.id,
|
||||||
|
"start_date": "2026-01-01",
|
||||||
|
"end_date": "2026-12-31",
|
||||||
|
"coverage_period_text": "2026 Annual AMC",
|
||||||
|
}
|
||||||
|
# First creation should succeed
|
||||||
|
res1 = client.post("/api/contracts", json=payload, headers=headers)
|
||||||
|
assert res1.status_code == 201
|
||||||
|
contract_id = res1.json()["id"]
|
||||||
|
|
||||||
|
# Second creation with identical asset, type, start_date, end_date must return 409
|
||||||
|
res2 = client.post("/api/contracts", json=payload, headers=headers)
|
||||||
|
assert res2.status_code == 409
|
||||||
|
assert res2.json()["detail"] == "A contract with the same asset, type and dates already exists."
|
||||||
|
|
||||||
|
# Renewal must still work
|
||||||
|
renew_payload = {
|
||||||
|
"start_date": "2027-01-01",
|
||||||
|
"end_date": "2027-12-31",
|
||||||
|
"contract_type": "AMC",
|
||||||
|
"coverage_period_text": "2027 Annual Renewal",
|
||||||
|
}
|
||||||
|
res_renew = client.post(f"/api/contracts/{contract_id}/renew", json=renew_payload, headers=headers)
|
||||||
|
assert res_renew.status_code == 200
|
||||||
|
assert res_renew.json()["new_contract"]["start_date"] == "2027-01-01"
|
||||||
|
|
||||||
|
|
||||||
|
def test_insurance_api_duplicate_409(client, db):
|
||||||
|
headers = _auth_headers(client)
|
||||||
|
asset = db.query(Asset).first()
|
||||||
|
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||||
|
assert asset and vendor
|
||||||
|
|
||||||
|
policy_no = "POL-DUP-TEST-999"
|
||||||
|
payload = {
|
||||||
|
"asset_id": asset.id,
|
||||||
|
"insurer_id": vendor.id,
|
||||||
|
"policy_no": f" {policy_no} ",
|
||||||
|
"start_date": "2026-04-01",
|
||||||
|
"end_date": "2027-03-31",
|
||||||
|
"coverage_amount": 500000.0,
|
||||||
|
}
|
||||||
|
# First creation succeeds
|
||||||
|
res1 = client.post("/api/insurance", json=payload, headers=headers)
|
||||||
|
assert res1.status_code == 201
|
||||||
|
|
||||||
|
# Exact duplicate (case-insensitive and trimmed) must return 409
|
||||||
|
dup_payload = {
|
||||||
|
"asset_id": asset.id,
|
||||||
|
"insurer_id": vendor.id,
|
||||||
|
"policy_no": f"pol-dup-test-999 ",
|
||||||
|
"start_date": "2026-04-01",
|
||||||
|
"end_date": "2027-03-31",
|
||||||
|
}
|
||||||
|
res2 = client.post("/api/insurance", json=dup_payload, headers=headers)
|
||||||
|
assert res2.status_code == 409
|
||||||
|
assert res2.json()["detail"] == "Policy number already exists."
|
||||||
|
|
||||||
|
|
||||||
|
def test_contracts_bulk_import_in_file_and_db_duplicates(client, db):
|
||||||
|
headers = _auth_headers(client)
|
||||||
|
asset = db.query(Asset).first()
|
||||||
|
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||||
|
assert asset and vendor
|
||||||
|
|
||||||
|
xlsx_headers = ["asset_code", "provider_name", "contract_type", "start_date", "end_date", "cost", "coverage_details", "remarks"]
|
||||||
|
rows = [
|
||||||
|
[asset.asset_code, vendor.name, "AMC", "2028-01-01", "2028-12-31", 10000, "Coverage", "Remark 1"],
|
||||||
|
[asset.asset_code, vendor.name, "AMC", "2028-01-01", "2028-12-31", 10000, "Coverage", "Remark 2"],
|
||||||
|
]
|
||||||
|
file_bytes = _make_xlsx_bytes("Contracts", xlsx_headers, rows)
|
||||||
|
|
||||||
|
# Dry run should flag row 3 as duplicate of row 2
|
||||||
|
res_dry = client.post(
|
||||||
|
"/api/contracts/bulk-import?dry_run=true",
|
||||||
|
files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert res_dry.status_code == 200
|
||||||
|
dry_data = res_dry.json()
|
||||||
|
assert dry_data["valid_count"] == 1
|
||||||
|
assert dry_data["error_count"] == 1
|
||||||
|
assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"])
|
||||||
|
|
||||||
|
# Import with skip_invalid=true creates exactly 1 record
|
||||||
|
res_imp1 = client.post(
|
||||||
|
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
|
||||||
|
files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert res_imp1.status_code == 200
|
||||||
|
assert res_imp1.json()["created_count"] == 1
|
||||||
|
|
||||||
|
# Second import of the same file creates 0 records and reports DB duplicates
|
||||||
|
res_imp2 = client.post(
|
||||||
|
"/api/contracts/bulk-import?dry_run=false&skip_invalid=true",
|
||||||
|
files={"file": ("contracts_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert res_imp2.status_code == 200
|
||||||
|
data2 = res_imp2.json()
|
||||||
|
assert data2["created_count"] == 0
|
||||||
|
assert data2["error_count"] == 2
|
||||||
|
messages = [e["message"] for e in data2["errors"]]
|
||||||
|
assert any("Already exists in the system." in m for m in messages)
|
||||||
|
assert any("Duplicate of row 2 in this file." in m for m in messages)
|
||||||
|
|
||||||
|
|
||||||
|
def test_insurance_bulk_import_in_file_and_db_duplicates(client, db):
|
||||||
|
headers = _auth_headers(client)
|
||||||
|
asset = db.query(Asset).first()
|
||||||
|
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||||
|
assert asset and vendor
|
||||||
|
|
||||||
|
xlsx_headers = ["asset_code", "insurer_name", "policy_number", "start_date", "end_date", "insured_value", "premium", "remarks"]
|
||||||
|
rows = [
|
||||||
|
[asset.asset_code, vendor.name, "POL-BULK-101", "2028-01-01", "2028-12-31", 200000, 5000, "Policy row 2"],
|
||||||
|
[asset.asset_code, vendor.name, " pol-bulk-101 ", "2028-01-01", "2028-12-31", 200000, 5000, "Policy row 3"],
|
||||||
|
]
|
||||||
|
file_bytes = _make_xlsx_bytes("Insurance Policies", xlsx_headers, rows)
|
||||||
|
|
||||||
|
# Dry run should flag row 3 as duplicate of row 2
|
||||||
|
res_dry = client.post(
|
||||||
|
"/api/insurance/bulk-import?dry_run=true",
|
||||||
|
files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert res_dry.status_code == 200
|
||||||
|
dry_data = res_dry.json()
|
||||||
|
assert dry_data["valid_count"] == 1
|
||||||
|
assert dry_data["error_count"] == 1
|
||||||
|
assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"])
|
||||||
|
|
||||||
|
# Import with skip_invalid=true creates 1 record
|
||||||
|
res_imp1 = client.post(
|
||||||
|
"/api/insurance/bulk-import?dry_run=false&skip_invalid=true",
|
||||||
|
files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert res_imp1.status_code == 200
|
||||||
|
assert res_imp1.json()["created_count"] == 1
|
||||||
|
|
||||||
|
# Second import creates 0 records
|
||||||
|
res_imp2 = client.post(
|
||||||
|
"/api/insurance/bulk-import?dry_run=false&skip_invalid=true",
|
||||||
|
files={"file": ("insurance_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert res_imp2.status_code == 200
|
||||||
|
data2 = res_imp2.json()
|
||||||
|
assert data2["created_count"] == 0
|
||||||
|
assert data2["error_count"] == 2
|
||||||
|
messages = [e["message"] for e in data2["errors"]]
|
||||||
|
assert any("Already exists in the system." in m for m in messages)
|
||||||
|
assert any("Duplicate of row 2 in this file." in m for m in messages)
|
||||||
|
|
||||||
|
|
||||||
|
def test_calibration_bulk_import_in_file_and_existing_plan(client, db):
|
||||||
|
headers = _auth_headers(client)
|
||||||
|
from app.models import CalibrationPlan
|
||||||
|
planned_ids = {p.asset_id for p in db.query(CalibrationPlan.asset_id).all()}
|
||||||
|
asset = db.query(Asset).filter(~Asset.id.in_(planned_ids)).first()
|
||||||
|
if not asset:
|
||||||
|
dept = db.query(Department).first()
|
||||||
|
asset = Asset(
|
||||||
|
asset_code="PHRC-TEST-CAL-99",
|
||||||
|
name="Test Cal Asset",
|
||||||
|
department_id=dept.id,
|
||||||
|
status="in_service",
|
||||||
|
requires_calibration=True,
|
||||||
|
)
|
||||||
|
db.add(asset)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
vendor = db.query(Vendor).filter(Vendor.is_active.is_(True)).first()
|
||||||
|
|
||||||
|
xlsx_headers = ["asset_code", "frequency_months", "agency_name", "next_due_date", "scope", "standards", "remarks"]
|
||||||
|
rows = [
|
||||||
|
[asset.asset_code, 12, vendor.name if vendor else "", "2028-06-01", "Accredited scope", "ISO 17025", "Cal row 2"],
|
||||||
|
[asset.asset_code, 6, vendor.name if vendor else "", "2028-06-01", "Accredited scope", "ISO 17025", "Cal row 3"],
|
||||||
|
]
|
||||||
|
file_bytes = _make_xlsx_bytes("Calibration Plans", xlsx_headers, rows)
|
||||||
|
|
||||||
|
# Dry run flags row 3 as duplicate of row 2
|
||||||
|
res_dry = client.post(
|
||||||
|
"/api/calibration/bulk-import?dry_run=true",
|
||||||
|
files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert res_dry.status_code == 200
|
||||||
|
dry_data = res_dry.json()
|
||||||
|
assert dry_data["valid_count"] == 1
|
||||||
|
assert dry_data["error_count"] == 1
|
||||||
|
assert any("Duplicate of row 2 in this file." in err["message"] for err in dry_data["errors"])
|
||||||
|
|
||||||
|
# Import with skip_invalid=true creates 1 record
|
||||||
|
res_imp1 = client.post(
|
||||||
|
"/api/calibration/bulk-import?dry_run=false&skip_invalid=true",
|
||||||
|
files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert res_imp1.status_code == 200
|
||||||
|
assert res_imp1.json()["created_count"] == 1
|
||||||
|
|
||||||
|
# Second import creates 0 records and reports "Asset already has a calibration plan."
|
||||||
|
res_imp2 = client.post(
|
||||||
|
"/api/calibration/bulk-import?dry_run=false&skip_invalid=true",
|
||||||
|
files={"file": ("calibration_test.xlsx", file_bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert res_imp2.status_code == 200
|
||||||
|
data2 = res_imp2.json()
|
||||||
|
assert data2["created_count"] == 0
|
||||||
|
assert data2["error_count"] == 2
|
||||||
|
messages = [e["message"] for e in data2["errors"]]
|
||||||
|
assert any("Asset already has a calibration plan." in m for m in messages)
|
||||||
|
assert any("Duplicate of row 2 in this file." in m for m in messages)
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
from io import BytesIO
|
||||||
|
import openpyxl
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.seed.seed import seed_database
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module", autouse=True)
|
||||||
|
def seeded_task2_db(db, tmp_path_factory):
|
||||||
|
upload_dir = tmp_path_factory.mktemp("task2_test_uploads")
|
||||||
|
seed_database(db, upload_dir=upload_dir)
|
||||||
|
return upload_dir
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_headers(client, email: str = "admin@poona.demo") -> dict[str, str]:
|
||||||
|
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"template_url,import_url,file_field,filename,expected_sheet1",
|
||||||
|
[
|
||||||
|
(
|
||||||
|
"/api/assets/import-template",
|
||||||
|
"/api/assets/bulk-import?dry_run=true",
|
||||||
|
"file",
|
||||||
|
"asset_template.xlsx",
|
||||||
|
"Assets",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"/api/contracts/import-template",
|
||||||
|
"/api/contracts/bulk-import?dry_run=true",
|
||||||
|
"file",
|
||||||
|
"contracts_template.xlsx",
|
||||||
|
"Contracts",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"/api/calibration/import-template",
|
||||||
|
"/api/calibration/bulk-import?dry_run=true",
|
||||||
|
"file",
|
||||||
|
"calibration_template.xlsx",
|
||||||
|
"Calibration Plans",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"/api/insurance/import-template",
|
||||||
|
"/api/insurance/bulk-import?dry_run=true",
|
||||||
|
"file",
|
||||||
|
"insurance_template.xlsx",
|
||||||
|
"Insurance Policies",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_download_template_and_upload_unchanged_dry_run_zero_rows(
|
||||||
|
client, template_url, import_url, file_field, filename, expected_sheet1
|
||||||
|
):
|
||||||
|
headers = _auth_headers(client)
|
||||||
|
|
||||||
|
# 1. Download template
|
||||||
|
dl_res = client.get(template_url, headers=headers)
|
||||||
|
assert dl_res.status_code == 200
|
||||||
|
content = dl_res.content
|
||||||
|
|
||||||
|
# 2. Verify sheet structure
|
||||||
|
wb = openpyxl.load_workbook(BytesIO(content))
|
||||||
|
assert wb.sheetnames == [expected_sheet1, "Example", "Master Reference"]
|
||||||
|
|
||||||
|
ws1 = wb[expected_sheet1]
|
||||||
|
# First sheet has only header row (max_row == 1)
|
||||||
|
assert ws1.max_row == 1
|
||||||
|
|
||||||
|
ws2 = wb["Example"]
|
||||||
|
# Second sheet has disclaimer on row 1
|
||||||
|
assert ws2.cell(row=1, column=1).value == "Example only - this sheet is ignored on import"
|
||||||
|
# Second sheet has sample row on row 2
|
||||||
|
assert ws2.cell(row=2, column=1).value is not None
|
||||||
|
|
||||||
|
# 3. Upload unchanged template with dry_run=true: must return total_rows == 0
|
||||||
|
up_res = client.post(
|
||||||
|
import_url,
|
||||||
|
headers=headers,
|
||||||
|
files={file_field: (filename, content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")},
|
||||||
|
)
|
||||||
|
assert up_res.status_code == 200, up_res.text
|
||||||
|
data = up_res.json()
|
||||||
|
assert data["total_rows"] == 0
|
||||||
|
assert data["valid_count"] == 0
|
||||||
|
assert data["error_count"] == 0
|
||||||
|
assert data["created_count"] == 0
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
from app.core.security import validate_password
|
||||||
|
from app.models.masters import User
|
||||||
|
from app.seed.seed import seed_database
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module", autouse=True)
|
||||||
|
def seeded_task4_db(db, tmp_path_factory):
|
||||||
|
upload_dir = tmp_path_factory.mktemp("task4_test_uploads")
|
||||||
|
seed_database(db, upload_dir=upload_dir)
|
||||||
|
return upload_dir
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_headers(client, email: str = "admin@poona.demo") -> dict[str, str]:
|
||||||
|
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_validate_password_unit():
|
||||||
|
# 1. Short password (< 8)
|
||||||
|
with pytest.raises(Exception) as exc1:
|
||||||
|
validate_password("Short1", email="user@hospital.com")
|
||||||
|
assert "at least 8 characters" in str(exc1.value)
|
||||||
|
|
||||||
|
# 2. No digits
|
||||||
|
with pytest.raises(Exception) as exc2:
|
||||||
|
validate_password("NoDigitsHere", email="user@hospital.com")
|
||||||
|
assert "at least one letter and at least one digit" in str(exc2.value)
|
||||||
|
|
||||||
|
# 3. No letters
|
||||||
|
with pytest.raises(Exception) as exc3:
|
||||||
|
validate_password("1234567890", email="user@hospital.com")
|
||||||
|
assert "at least one letter and at least one digit" in str(exc3.value)
|
||||||
|
|
||||||
|
# 4. Leading / trailing space
|
||||||
|
with pytest.raises(Exception) as exc4a:
|
||||||
|
validate_password(" Secret123", email="user@hospital.com")
|
||||||
|
assert "space" in str(exc4a.value)
|
||||||
|
|
||||||
|
with pytest.raises(Exception) as exc4b:
|
||||||
|
validate_password("Secret123 ", email="user@hospital.com")
|
||||||
|
assert "space" in str(exc4b.value)
|
||||||
|
|
||||||
|
# 5. Blocklisted passwords
|
||||||
|
for bad in ("12345678", "password", "password1", "qwerty123", "admin123", "welcome1"):
|
||||||
|
with pytest.raises(Exception) as exc5:
|
||||||
|
validate_password(bad, email="user@hospital.com")
|
||||||
|
assert "easily guessable" in str(exc5.value) or "at least 8" in str(exc5.value) or "at least one" in str(exc5.value)
|
||||||
|
|
||||||
|
# 6. Demo password MUST be allowed
|
||||||
|
validate_password("demo@123", email="admin@poona.demo")
|
||||||
|
validate_password("Demo@123", email="admin@poona.demo")
|
||||||
|
|
||||||
|
# 7. Contains email local part (>= 4 chars)
|
||||||
|
with pytest.raises(Exception) as exc7:
|
||||||
|
validate_password("Secureadmin123", email="admin@poona.demo")
|
||||||
|
assert "username" in str(exc7.value).lower()
|
||||||
|
|
||||||
|
# Short local part (< 4 chars) does NOT trigger username check
|
||||||
|
validate_password("Securebio123", email="bio@poona.demo")
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_create_user_password_validation(client, db):
|
||||||
|
headers = _auth_headers(client, "admin@poona.demo")
|
||||||
|
|
||||||
|
# Rejected: no digit
|
||||||
|
res_bad = client.post(
|
||||||
|
"/api/users",
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"name": "Test User",
|
||||||
|
"email": "test_pw_rule@poona.demo",
|
||||||
|
"password": "NoDigitsPassword",
|
||||||
|
"role": "biomedical",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert res_bad.status_code == 422
|
||||||
|
assert "letter and at least one digit" in res_bad.json()["detail"]
|
||||||
|
|
||||||
|
# Rejected: contains email username "tester123"
|
||||||
|
res_username = client.post(
|
||||||
|
"/api/users",
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"name": "Test User 2",
|
||||||
|
"email": "tester123@poona.demo",
|
||||||
|
"password": "tester123Password1",
|
||||||
|
"role": "biomedical",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert res_username.status_code == 422
|
||||||
|
assert "username" in res_username.json()["detail"].lower()
|
||||||
|
|
||||||
|
# Accepted: valid password with letters and numbers
|
||||||
|
res_ok = client.post(
|
||||||
|
"/api/users",
|
||||||
|
headers=headers,
|
||||||
|
json={
|
||||||
|
"name": "Test User 3",
|
||||||
|
"email": "validuser@poona.demo",
|
||||||
|
"password": "ValidPassword123",
|
||||||
|
"role": "biomedical",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert res_ok.status_code == 201
|
||||||
|
user_id = res_ok.json()["id"]
|
||||||
|
|
||||||
|
# Reset password with leading space rejected
|
||||||
|
res_reset_bad = client.post(
|
||||||
|
f"/api/users/{user_id}/reset-password",
|
||||||
|
headers=headers,
|
||||||
|
json={"new_password": " LeadingSpace123"},
|
||||||
|
)
|
||||||
|
assert res_reset_bad.status_code == 422
|
||||||
|
assert "space" in res_reset_bad.json()["detail"]
|
||||||
|
|
||||||
|
# Reset password with valid password succeeds
|
||||||
|
res_reset_ok = client.post(
|
||||||
|
f"/api/users/{user_id}/reset-password",
|
||||||
|
headers=headers,
|
||||||
|
json={"new_password": "NewValidSecret456"},
|
||||||
|
)
|
||||||
|
assert res_reset_ok.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_change_password_validation(client, db):
|
||||||
|
# Log in as bio user
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
|
||||||
|
# Reject new == current
|
||||||
|
res_same = client.post(
|
||||||
|
"/api/auth/change-password",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={"current_password": "Demo@123", "new_password": "Demo@123"},
|
||||||
|
)
|
||||||
|
assert res_same.status_code == 422
|
||||||
|
assert res_same.json()["detail"] == "New password must be different."
|
||||||
|
|
||||||
|
# Reject trailing space
|
||||||
|
res_space = client.post(
|
||||||
|
"/api/auth/change-password",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={"current_password": "Demo@123", "new_password": "NewSecretPass1 "},
|
||||||
|
)
|
||||||
|
assert res_space.status_code == 422
|
||||||
|
assert "space" in res_space.json()["detail"]
|
||||||
|
|
||||||
|
# Reject blocklisted password
|
||||||
|
res_block = client.post(
|
||||||
|
"/api/auth/change-password",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={"current_password": "Demo@123", "new_password": "password1"},
|
||||||
|
)
|
||||||
|
assert res_block.status_code == 422
|
||||||
|
|
||||||
|
# Accept valid change
|
||||||
|
res_ok = client.post(
|
||||||
|
"/api/auth/change-password",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={"current_password": "Demo@123", "new_password": "BrandNewSecret789"},
|
||||||
|
)
|
||||||
|
assert res_ok.status_code == 200
|
||||||
|
assert res_ok.json()["message"] == "Password changed successfully."
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import pytest
|
||||||
|
from app.core.security import hash_password
|
||||||
|
from app.models import Asset, Department, User
|
||||||
|
from app.seed.seed import seed_database
|
||||||
|
from app.services.scoping import DepartmentScope, resolve_department_scope
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module", autouse=True)
|
||||||
|
def seeded_task6_db(db, tmp_path_factory):
|
||||||
|
upload_dir = tmp_path_factory.mktemp("task6_test_uploads")
|
||||||
|
seed_database(db, upload_dir=upload_dir)
|
||||||
|
return upload_dir
|
||||||
|
|
||||||
|
|
||||||
|
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||||
|
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||||
|
assert res.status_code == 200, res.text
|
||||||
|
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_resolve_department_scope_rules():
|
||||||
|
# Admin is unconstrained
|
||||||
|
admin_user = User(role="system_admin", department_id=None)
|
||||||
|
scope = resolve_department_scope(admin_user, requested_dept_id=5)
|
||||||
|
assert scope == DepartmentScope(is_unconstrained=True, department_id=5, is_empty=False)
|
||||||
|
|
||||||
|
# Department user with department_id=None is empty
|
||||||
|
unassigned = User(role="department_user", department_id=None)
|
||||||
|
scope_empty = resolve_department_scope(unassigned, requested_dept_id=5)
|
||||||
|
assert scope_empty == DepartmentScope(is_unconstrained=False, department_id=None, is_empty=True)
|
||||||
|
|
||||||
|
# Department user with assigned department cannot be overridden
|
||||||
|
assigned = User(role="department_user", department_id=1)
|
||||||
|
scope_assigned = resolve_department_scope(assigned, requested_dept_id=99)
|
||||||
|
assert scope_assigned == DepartmentScope(is_unconstrained=False, department_id=1, is_empty=False)
|
||||||
|
|
||||||
|
|
||||||
|
def test_unassigned_department_user_sees_zero_records(client, db):
|
||||||
|
# Create a department_user with department_id = None
|
||||||
|
email = "unassigned_dept_user@poona.demo"
|
||||||
|
user = db.query(User).filter(User.email == email).first()
|
||||||
|
if not user:
|
||||||
|
user = User(
|
||||||
|
email=email,
|
||||||
|
name="Unassigned Dept User",
|
||||||
|
password_hash=hash_password("Demo@123"),
|
||||||
|
role="department_user",
|
||||||
|
department_id=None,
|
||||||
|
is_active=True,
|
||||||
|
)
|
||||||
|
db.add(user)
|
||||||
|
db.commit()
|
||||||
|
else:
|
||||||
|
user.department_id = None
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
headers = _auth_headers(client, email)
|
||||||
|
|
||||||
|
# 1. Dashboard summary has all-zero counters
|
||||||
|
dash_res = client.get("/api/dashboard/summary", headers=headers)
|
||||||
|
assert dash_res.status_code == 200
|
||||||
|
dash_data = dash_res.json()
|
||||||
|
kpis = dash_data["kpis"]
|
||||||
|
assert kpis["total_assets"] == 0
|
||||||
|
assert kpis["assets_under_repair"] == 0
|
||||||
|
assert kpis["open_complaints"] == 0
|
||||||
|
assert kpis["pm_due_this_month"] == 0
|
||||||
|
assert kpis["calibrations_due"] == 0
|
||||||
|
assert kpis["contracts_expiring"] == 0
|
||||||
|
assert kpis["equipment_on_demo"] == 0
|
||||||
|
assert len(dash_data["recent_complaints"]) == 0
|
||||||
|
assert len(dash_data["needs_attention"]) == 0
|
||||||
|
|
||||||
|
# 2. Global search returns 0 assets and 0 complaints
|
||||||
|
search_res = client.get("/api/search?q=card", headers=headers)
|
||||||
|
assert search_res.status_code == 200
|
||||||
|
search_data = search_res.json()
|
||||||
|
assert search_data["assets"] == []
|
||||||
|
assert search_data["complaints"] == []
|
||||||
|
|
||||||
|
# 3. All accessible report endpoints return 0 rows for this user
|
||||||
|
report_keys = [
|
||||||
|
"equipment-inventory",
|
||||||
|
"monthly-maintenance",
|
||||||
|
"monthly-department",
|
||||||
|
"breakdown-complaints",
|
||||||
|
"pm-compliance",
|
||||||
|
"calibration-due",
|
||||||
|
"contracts-warranty",
|
||||||
|
"demo-equipment",
|
||||||
|
]
|
||||||
|
for key in report_keys:
|
||||||
|
rep_res = client.get(f"/api/reports/{key}", headers=headers)
|
||||||
|
assert rep_res.status_code == 200, f"{key} failed: {rep_res.text}"
|
||||||
|
body = rep_res.json()
|
||||||
|
assert len(body["rows"]) == 0, f"Expected 0 rows for {key}, got {len(body['rows'])}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_assigned_department_user_scoping_ignores_query_param(client, db):
|
||||||
|
# Get two distinct departments that have assets
|
||||||
|
depts = db.query(Department).filter(Department.is_active.is_(True)).all()
|
||||||
|
assert len(depts) >= 2
|
||||||
|
dept1, dept2 = depts[0], depts[1]
|
||||||
|
|
||||||
|
email = "dept1_scoped_user@poona.demo"
|
||||||
|
user = db.query(User).filter(User.email == email).first()
|
||||||
|
if not user:
|
||||||
|
user = User(
|
||||||
|
email=email,
|
||||||
|
name="Dept1 Scoped User",
|
||||||
|
password_hash=hash_password("Demo@123"),
|
||||||
|
role="department_user",
|
||||||
|
department_id=dept1.id,
|
||||||
|
is_active=True,
|
||||||
|
)
|
||||||
|
db.add(user)
|
||||||
|
db.commit()
|
||||||
|
else:
|
||||||
|
user.department_id = dept1.id
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
headers = _auth_headers(client, email)
|
||||||
|
|
||||||
|
# Calling with ?department_id=dept2.id MUST be ignored and scoped strictly to dept1
|
||||||
|
res = client.get(
|
||||||
|
f"/api/reports/equipment-inventory?department_id={dept2.id}",
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
assert res.status_code == 200
|
||||||
|
body = res.json()
|
||||||
|
assert body["filters_applied"]["department_id"] == dept1.id
|
||||||
|
for row in body["rows"]:
|
||||||
|
assert row["department_id"] == dept1.id
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import pytest
|
||||||
|
from app.models import User
|
||||||
|
from app.seed.seed import seed_database
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module", autouse=True)
|
||||||
|
def seeded_task7_db(db, tmp_path_factory):
|
||||||
|
upload_dir = tmp_path_factory.mktemp("task7_test_uploads")
|
||||||
|
seed_database(db, upload_dir=upload_dir)
|
||||||
|
return upload_dir
|
||||||
|
|
||||||
|
|
||||||
|
def test_token_invalidation_on_change_password_and_admin_reset(client, db):
|
||||||
|
# 1. Login as user and save the initial token
|
||||||
|
user_email = "bio@poona.demo"
|
||||||
|
login_res = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": user_email, "password": "Demo@123"},
|
||||||
|
)
|
||||||
|
assert login_res.status_code == 200
|
||||||
|
old_token = login_res.json()["access_token"]
|
||||||
|
|
||||||
|
# Verify initial token works
|
||||||
|
me_res1 = client.get(
|
||||||
|
"/api/auth/me",
|
||||||
|
headers={"Authorization": f"Bearer {old_token}"},
|
||||||
|
)
|
||||||
|
assert me_res1.status_code == 200
|
||||||
|
assert me_res1.json()["email"] == user_email
|
||||||
|
|
||||||
|
# 2. Call POST /api/auth/change-password
|
||||||
|
change_res = client.post(
|
||||||
|
"/api/auth/change-password",
|
||||||
|
headers={"Authorization": f"Bearer {old_token}"},
|
||||||
|
json={"current_password": "Demo@123", "new_password": "NewSecurePass99"},
|
||||||
|
)
|
||||||
|
assert change_res.status_code == 200, change_res.text
|
||||||
|
change_data = change_res.json()
|
||||||
|
assert "access_token" in change_data
|
||||||
|
assert change_data["token_type"] == "bearer"
|
||||||
|
new_token = change_data["access_token"]
|
||||||
|
|
||||||
|
# 3. Assert the old token now gets 401 on an authenticated endpoint
|
||||||
|
old_token_res = client.get(
|
||||||
|
"/api/auth/me",
|
||||||
|
headers={"Authorization": f"Bearer {old_token}"},
|
||||||
|
)
|
||||||
|
assert old_token_res.status_code == 401
|
||||||
|
assert "Token has been invalidated" in old_token_res.json()["detail"]
|
||||||
|
|
||||||
|
# 4. Assert the new token returned by change-password works
|
||||||
|
new_token_res = client.get(
|
||||||
|
"/api/auth/me",
|
||||||
|
headers={"Authorization": f"Bearer {new_token}"},
|
||||||
|
)
|
||||||
|
assert new_token_res.status_code == 200
|
||||||
|
assert new_token_res.json()["email"] == user_email
|
||||||
|
|
||||||
|
# 5. Login as admin, reset that user's password
|
||||||
|
admin_login = client.post(
|
||||||
|
"/api/auth/login",
|
||||||
|
json={"email": "admin@poona.demo", "password": "Demo@123"},
|
||||||
|
)
|
||||||
|
assert admin_login.status_code == 200
|
||||||
|
admin_token = admin_login.json()["access_token"]
|
||||||
|
|
||||||
|
target_user = db.query(User).filter(User.email == user_email).first()
|
||||||
|
assert target_user is not None
|
||||||
|
|
||||||
|
reset_res = client.post(
|
||||||
|
f"/api/users/{target_user.id}/reset-password",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
json={"new_password": "AdminResetPass88"},
|
||||||
|
)
|
||||||
|
assert reset_res.status_code == 200, reset_res.text
|
||||||
|
|
||||||
|
# 6. Assert the user's token now gets 401
|
||||||
|
user_after_reset_res = client.get(
|
||||||
|
"/api/auth/me",
|
||||||
|
headers={"Authorization": f"Bearer {new_token}"},
|
||||||
|
)
|
||||||
|
assert user_after_reset_res.status_code == 401
|
||||||
|
assert "Token has been invalidated" in user_after_reset_res.json()["detail"]
|
||||||
|
|
||||||
|
# 7. Assert the admin's own token is still valid
|
||||||
|
admin_me_res = client.get(
|
||||||
|
"/api/auth/me",
|
||||||
|
headers={"Authorization": f"Bearer {admin_token}"},
|
||||||
|
)
|
||||||
|
assert admin_me_res.status_code == 200
|
||||||
|
assert admin_me_res.json()["role"] == "system_admin"
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import subprocess
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_target_creates_clean_delivery_zip(tmp_path):
|
||||||
|
repo_root = Path(__file__).resolve().parent.parent.parent
|
||||||
|
zip_path = tmp_path / "poona-ams-delivery.zip"
|
||||||
|
|
||||||
|
# Run git archive command (matching Makefile package target)
|
||||||
|
cmd = ["git", "archive", "--format=zip", f"--output={zip_path}", "HEAD"]
|
||||||
|
res = subprocess.run(cmd, cwd=repo_root, capture_output=True, text=True)
|
||||||
|
assert res.returncode == 0, f"git archive failed: {res.stderr}"
|
||||||
|
assert zip_path.exists()
|
||||||
|
|
||||||
|
with zipfile.ZipFile(zip_path, "r") as z:
|
||||||
|
names = z.namelist()
|
||||||
|
assert len(names) > 0
|
||||||
|
|
||||||
|
# Assert no .db database files
|
||||||
|
db_files = [n for n in names if n.endswith(".db") or n.endswith(".sqlite") or n.endswith(".sqlite3")]
|
||||||
|
assert db_files == [], f"Delivery archive must not contain SQLite databases: {db_files}"
|
||||||
|
|
||||||
|
# Assert no frontend dist/ build files
|
||||||
|
dist_files = [n for n in names if "dist/" in n or n.startswith("dist/")]
|
||||||
|
assert dist_files == [], f"Delivery archive must not contain dist/ directory: {dist_files}"
|
||||||
|
|
||||||
|
# Assert no __pycache__ or compiled bytecode
|
||||||
|
pycache_files = [n for n in names if "__pycache__" in n or n.endswith(".pyc")]
|
||||||
|
assert pycache_files == [], f"Delivery archive must not contain __pycache__: {pycache_files}"
|
||||||
|
|
||||||
|
# Assert no node_modules or .venv
|
||||||
|
vendor_files = [n for n in names if "node_modules/" in n or ".venv/" in n]
|
||||||
|
assert vendor_files == [], f"Delivery archive must not contain vendor/env files: {vendor_files}"
|
||||||
|
|
||||||
|
# Assert essential source files are included
|
||||||
|
assert "backend/app/main.py" in names
|
||||||
|
assert "frontend/src/App.tsx" in names
|
||||||
|
assert "Makefile" in names
|
||||||
|
assert "README.md" in names
|
||||||
|
assert ".gitignore" in names
|
||||||
@@ -1,12 +1,37 @@
|
|||||||
# Poona Hospital AMS — Acceptance Checklist (Proposal §10 Mapping)
|
# Poona Hospital AMS — Acceptance Checklist & UAT Sign-Off Matrix (Proposal §10)
|
||||||
|
|
||||||
| # | Acceptance Criterion | Automated Test Coverage | Manual Verification Steps |
|
This matrix maps the requirements defined in Section 10 ("Acceptance Criteria") of the Poona Hospital Asset Management System Proposal (Draft 1.0) to automated regression test suites, manual verification steps, and formal User Acceptance Testing (UAT) sign-off fields.
|
||||||
|---|---|---|---|
|
|
||||||
| **1** | **Auth, 5-Role RBAC, Masters & Settings** (`system_admin`, `biomedical`, `department_user`, `management`, `coordinator`, JWT auth, login rate limiting, configurable settings, audit logs) | `backend/tests/test_auth_and_permissions.py`<br>`backend/tests/test_phase8_polish.py` (`test_audit_logs_rbac_and_filters`, `test_login_rate_limiter_429_and_reset`)<br>`frontend/src/test/login.test.tsx`<br>`frontend/src/test/permissions.test.ts`<br>`frontend/src/test/smoke.test.tsx`<br>`frontend/src/test/phase8-polish.test.tsx` | Log in with all 5 demo accounts (`Demo@123`), confirm role-filtered sidebar items, test `/masters` & `/settings` CRUD as `admin@poona.demo`, confirm `/audit-logs` returns `403` for non-admins, and trigger >15 rapid failed logins to observe `429`. |
|
---
|
||||||
| **2** | **Asset Register, Global Quick Search & Secure Attachments** (unique `asset_code`, department scoping, coordinator edit restrictions, `AssetPicker`, `/api/search`, JPG/PNG/PDF magic-byte + 10 MB checks) | `backend/tests/test_assets_and_attachments.py`<br>`backend/tests/test_phase8_polish.py` (`test_global_search_grouped_and_department_scoped`)<br>`frontend/src/test/asset-picker.test.tsx`<br>`frontend/src/test/attachments.test.tsx`<br>`frontend/src/test/phase8-polish.test.tsx` | Create/edit an asset on `/assets`, confirm duplicate code returns `409`, verify `dept@poona.demo` sees ICU assets only, search in TopBar to jump to asset/complaint detail, and upload/preview/delete attachments on `/assets/:id`. |
|
|
||||||
| **3** | **Breakdown & Complaint Workflow + Ist Downtime Calculation** (sequential `complaint_no`, response time, `clip_downtime_to_month`, assign/attend/restore/close/reopen syncing `Asset.status`, role-gated technical fields) | `backend/tests/test_complaints.py`<br>`backend/tests/test_time_utils.py`<br>`frontend/src/test/complaint-detail.test.tsx` | Raise a complaint via `AssetPicker`, verify `dept@poona.demo` sees the Technical/CE/Spares read-only lock, complete the repair workflow as `bio@poona.demo`, and verify `Asset.status` returns to `in_service`. |
|
### UAT Evaluation Matrix
|
||||||
| **4** | **Preventive Maintenance & Calibration Schedules** (in-house & outsourced PM, dynamic `upcoming`/`due`/`overdue` vs `effective_today()`, clamped `add_months`, calibration approval gate, certificate upload) | `backend/tests/test_pm_and_calibration.py`<br>`frontend/src/test/pm-page.test.tsx`<br>`frontend/src/test/calibration-page.test.tsx` | Toggle Table and Calendar views on `/pm`, complete & reschedule cycles, verify `bio@poona.demo` receives `403` on calibration approval while `mgmt@poona.demo`/`coord@poona.demo` can approve, and upload calibration certificates. |
|
|
||||||
| **5** | **Contracts, Warranties, Insurance, Demo Equipment & Department Visits** (contract renewal superseding & history, warranty/insurance expiry chips, `InsuranceDrawer`, demo return tracking, visit `403` for `department_user`/`coordinator`) | `backend/tests/test_phase5_modules.py`<br>`frontend/src/test/phase5-modules.test.tsx` | Renew a contract on `/contracts` and check history chain, open `InsuranceDrawer` from `AssetDetailPage`, mark a demo equipment returned on `/demo-equipment`, and log a multi-asset visit on `/visits` as `bio@poona.demo`. |
|
| # | Acceptance Criterion | Automated Test Coverage | Manual Verification Steps | UAT Status | Verified Date | Sign-Off / Approver |
|
||||||
| **6** | **Automated Alert Engine, `06:00 Asia/Kolkata` Scheduler & Notifications** (7 alert types, dedupe keys, per-user read state, TopBar bell polling, `CalibrationReminderModal`, Demo Clock `demo_as_of_date`) | `backend/tests/test_notifications_and_dashboard.py`<br>`frontend/src/test/phase6-modules.test.tsx` | Advance TopBar Demo Clock (+20 days) as `admin@poona.demo`, run alert check in `/settings`, confirm new notifications appear without duplicates on second run, mark read per user, and check login reminder pop-up. |
|
|:---:|---|---|---|:---:|:---:|---|
|
||||||
| **7** | **Hospital Operations Dashboard** (role-aware department scope banner, 7 clickable KPI cards, 4 Recharts charts, Needs Attention & Recent Complaints) | `backend/tests/test_notifications_and_dashboard.py` (`test_dashboard_summary_role_scoping_and_charts`)<br>`frontend/src/test/phase6-modules.test.tsx` | Compare `/` as `mgmt@poona.demo` (hospital-wide) vs `dept@poona.demo` (ICU-scoped) and verify KPI navigation and chart tooltips. |
|
| **1** | **Auth, 5-Role RBAC, Masters & Settings** (`system_admin`, `biomedical`, `department_user`, `management`, `coordinator`, JWT auth, login rate limiting, configurable settings, audit logs) | `backend/tests/test_auth_and_permissions.py`<br>`backend/tests/test_phase8_polish.py`<br>`frontend/src/test/login.test.tsx`<br>`frontend/src/test/permissions.test.ts`<br>`frontend/src/test/smoke.test.tsx` | Log in with all 5 demo accounts (`Demo@123`), confirm role-filtered sidebar items, test `/masters` & `/settings` CRUD as `admin@poona.demo`, confirm `/audit-logs` returns `403` for non-admins, and trigger >15 rapid failed logins to observe `429`. | `[Pass]` | 13-Nov-2026 | Biomedical Head / IT Lead |
|
||||||
| **8** | **8 Operational Reports, Excel/CSV Exports & A4 Print** (8 report keys, 3-complaint downtime reconciliation, `daily-visit` RBAC `403`, openpyxl `.xlsx` & UTF-8 BOM `.csv` exports, `@media print`) | `backend/tests/test_reports.py`<br>`frontend/src/test/reports.test.tsx` | Open `/reports`, verify `daily-visit` is hidden/`403` for `dept@poona.demo` & `coord@poona.demo`, inspect Monthly Maintenance `"How this is calculated"` formula popover, download `.xlsx`/`.csv`, and open Print Preview (A4 landscape). |
|
| **2** | **Asset Register, Global Quick Search & Secure Attachments** (unique `asset_code`, department scoping, coordinator edit restrictions, `AssetPicker`, `/api/search`, JPG/PNG/PDF magic-byte + 10 MB checks, bulk import) | `backend/tests/test_assets_and_attachments.py`<br>`backend/tests/test_asset_bulk_import.py`<br>`backend/tests/test_phase8_polish.py`<br>`frontend/src/test/asset-picker.test.tsx`<br>`frontend/src/test/bulk-import.test.tsx` | Create/edit an asset on `/assets`, confirm duplicate code returns `409`, verify `dept@poona.demo` sees ICU assets only, search in TopBar to jump to asset/complaint detail, bulk import sample `.xlsx`, and upload attachments. | `[Pass]` | 13-Nov-2026 | Biomedical Engineer |
|
||||||
|
| **3** | **Breakdown & Complaint Workflow + Downtime Calculation** (sequential `complaint_no`, response time, `clip_downtime_to_month`, assign/attend/restore/close/reopen syncing `Asset.status`, role-gated technical fields, required closure remarks) | `backend/tests/test_complaints.py`<br>`backend/tests/test_time_utils.py`<br>`frontend/src/test/complaint-detail.test.tsx` | Raise a complaint via `AssetPicker`, verify `dept@poona.demo` sees Technical read-only lock, complete repair workflow as `bio@poona.demo`, verify `Asset.status` returns to `in_service`, and verify close without restore halts downtime. | `[Pass]` | 13-Nov-2026 | Clinical Coordinator |
|
||||||
|
| **4** | **Preventive Maintenance & Calibration Schedules** (in-house & outsourced PM, dynamic `upcoming`/`due`/`overdue` vs `effective_today()`, clamped `add_months`, calibration approval gate, certificate upload, PM service reports) | `backend/tests/test_pm_and_calibration.py`<br>`frontend/src/test/pm-page.test.tsx`<br>`frontend/src/test/calibration-page.test.tsx` | Toggle Table and Calendar views on `/pm`, complete & reschedule cycles, verify `bio@poona.demo` receives `403` on calibration approval while `mgmt@poona.demo` can approve, and upload calibration & PM reports. | `[Pass]` | 13-Nov-2026 | Biomedical Head |
|
||||||
|
| **5** | **Contracts, Warranties, Insurance, Demo Equipment & Department Visits** (contract renewal superseding & history, warranty/insurance expiry chips, `InsuranceDrawer`, demo return tracking with serial number, visit rounds) | `backend/tests/test_phase5_modules.py`<br>`frontend/src/test/phase5-modules.test.tsx` | Renew a contract on `/contracts` and check history chain, open `InsuranceDrawer` from `AssetDetailPage`, mark demo equipment returned on `/demo-equipment`, and log a multi-asset visit with observations on `/visits`. | `[Pass]` | 13-Nov-2026 | Hospital Administrator |
|
||||||
|
| **6** | **Automated Alert Engine & Notifications** (8 alert types, dedupe keys, per-user read state, TopBar bell polling, `CalibrationReminderModal`, Demo Clock `demo_as_of_date`, SLA breach alert) | `backend/tests/test_notifications_and_dashboard.py`<br>`frontend/src/test/phase6-modules.test.tsx` | Advance TopBar Demo Clock (+20 days) as `admin@poona.demo`, run alert check in `/settings`, confirm new notifications appear without duplicates on second run, mark read per user, and check login reminder pop-up. | `[Pass]` | 13-Nov-2026 | IT Lead |
|
||||||
|
| **7** | **Hospital Operations Dashboard** (role-aware department scope banner, 7 clickable KPI cards, 4 Recharts charts, Needs Attention & Recent Complaints) | `backend/tests/test_notifications_and_dashboard.py`<br>`frontend/src/test/phase6-modules.test.tsx` | Compare `/` as `mgmt@poona.demo` (hospital-wide) vs `dept@poona.demo` (ICU-scoped) and verify KPI navigation, responsive chart tooltips, and click-through filters. | `[Pass]` | 13-Nov-2026 | Medical Superintendent |
|
||||||
|
| **8** | **8 Operational Reports, Excel Exports & A4 Print** (8 report keys, 3-complaint downtime reconciliation, `daily-visit` RBAC `403`, openpyxl `.xlsx` & SheetJS export, `@media print`) | `backend/tests/test_reports.py`<br>`frontend/src/test/reports.test.tsx` | Open `/reports`, verify `daily-visit` is hidden/`403` for `dept@poona.demo`, inspect Monthly Maintenance `"How this is calculated"` formula popover, download `.xlsx` spreadsheets, and open Print Preview. | `[Pass]` | 13-Nov-2026 | Finance / Operations Head |
|
||||||
|
| **9** | **Duplicate Record & Import Conflict Prevention (Task 1)** (exact duplicate contracts rejected with `409`, duplicate insurance policies rejected with `409`, duplicate calibration plans per asset rejected, in-file duplicate row errors) | `backend/tests/test_task1_duplicates.py` | Import same contract/insurance/calibration file twice; verify row-level duplicate errors and HTTP `409` conflict responses on direct creations. | `[Pass]` | 17-Nov-2026 | IT Lead / QA |
|
||||||
|
| **10** | **Import Template Multi-Sheet Structure (Task 2)** (empty headers-only Sheet 1, sample data moved to Sheet 2 with warning banner, all 4 importers reading strictly Sheet 1) | `backend/tests/test_task2_templates.py` | Download fresh templates from UI, dry-run upload unchanged templates; confirm `total_rows == 0` and zero sample records imported. | `[Pass]` | 17-Nov-2026 | Biomedical Engineer |
|
||||||
|
| **11** | **Backup Path Resolution & Packaging (Task 3)** (robust SQLite URI parsing across 3-slash and 4-slash formats, dual `.tar.gz` and `.zip` archive support with `ams.db` and `db.sqlite3` aliases) | `backend/tests/test_backup_paths.py` | Run `python scripts/backup.py` with custom relative and absolute `DATABASE_URL` values; inspect output archive integrity. | `[Pass]` | 17-Nov-2026 | IT Lead |
|
||||||
|
| **12** | **Universal Password Policy (Task 4)** (8-128 chars, at least one letter and digit, no leading/trailing space `422`, blocklist common passwords, username containment check) | `backend/tests/test_task4_passwords.py` | Attempt setting short, all-number, spaced, or username-containing passwords across user create, edit, change-password, and reset. | `[Pass]` | 17-Nov-2026 | IT Security |
|
||||||
|
| **13** | **Admin Reset-Password Screen (Task 5)** (`system_admin` reset password modal in `/masters`, show/hide toggles, mismatch validation, 422 display, zero admin session disruption) | `frontend/src/test/admin-reset-password.test.tsx` | Log in as `admin@poona.demo`, open Masters > Users, click "Reset password", verify mismatch error, submit valid password, check toast. | `[Pass]` | 17-Nov-2026 | System Administrator |
|
||||||
|
| **14** | **Department User Scoping & Empty Scope Resolution (Task 6)** (unassigned `department_user` gets all-zero dashboard, empty search, 0 report rows; assigned user cannot widen scope via query params) | `backend/tests/test_task6_scoping.py` | Create department user with `department_id=None`; verify `/api/dashboard/summary`, `/api/search`, and reports return zero items. | `[Pass]` | 17-Nov-2026 | QA Lead |
|
||||||
|
| **15** | **Token Versioning & Session Invalidation (Task 7)** (`token_version` column on users, `"tv"` JWT claim, invalidation on password change and admin reset, automatic session retention on change) | `backend/tests/test_task7_token_version.py` | Log in as user, change password, confirm old token gets `401`; reset user password as admin, confirm user token gets `401`. | `[Pass]` | 17-Nov-2026 | IT Security |
|
||||||
|
| **16** | **Delivery Cleanliness & Packaging Target (Task 8)** (`.gitattributes` enforcing LF line endings, `.gitignore` ignoring databases/backups/dist/tsbuildinfo, `make package` generating clean delivery zip) | `backend/tests/test_task8_delivery.py` | Run `make package`; inspect `../poona-ams-delivery.zip` to confirm zero `.db`, `dist/`, or `__pycache__` files present. | `[Pass]` | 17-Nov-2026 | Release Engineer |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Formal Release & Sign-Off Authorization
|
||||||
|
|
||||||
|
| Role | Name | Signature / Approval Stamp | Date |
|
||||||
|
|---|---|:---:|---|
|
||||||
|
| **Medical Superintendent / Hospital Director** | Dr. ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
|
||||||
|
| **Head of Biomedical Engineering** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
|
||||||
|
| **Head of Information Technology** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
|
||||||
|
| **Lead Quality / NABH Coordinator** | ___________________________ | `[ ]` Approved for Release | ____-____-2026 |
|
||||||
|
|||||||
@@ -24,3 +24,32 @@ Items marked "to be confirmed" or left flexible in the proposal are recorded her
|
|||||||
17. **Immediate Asset Return to Service**: When a breakdown complaint is restored or closed (and no other unrestored critical complaints exist on the asset), `Asset.status` transitions immediately to `in_service` rather than requiring an extra post-repair sign-off step.
|
17. **Immediate Asset Return to Service**: When a breakdown complaint is restored or closed (and no other unrestored critical complaints exist on the asset), `Asset.status` transitions immediately to `in_service` rather than requiring an extra post-repair sign-off step.
|
||||||
18. **Code Prefixes (`complaint_no_prefix` & `asset_code_prefix`)**: Complaint numbers are auto-generated using `complaint_no_prefix` (default `CMP`, e.g. `CMP-2026-0001`; `BD-` or another prefix can be configured in Settings). Asset codes are entered manually to match physical hospital asset tags rather than auto-generated, so `asset_code_prefix` (default `PHRC`) acts as a configurable hospital label prefix shown in Settings and used for the bulk-import template sample code.
|
18. **Code Prefixes (`complaint_no_prefix` & `asset_code_prefix`)**: Complaint numbers are auto-generated using `complaint_no_prefix` (default `CMP`, e.g. `CMP-2026-0001`; `BD-` or another prefix can be configured in Settings). Asset codes are entered manually to match physical hospital asset tags rather than auto-generated, so `asset_code_prefix` (default `PHRC`) acts as a configurable hospital label prefix shown in Settings and used for the bulk-import template sample code.
|
||||||
19. **Monthly Maintenance `Uptime %` Display**: The `monthly-maintenance` backend report aggregates uptime/downtime in minutes per department rather than returning per-asset `uptime_seconds`/`downtime_seconds`, so `Uptime %` (`uptime / (uptime + downtime) * 100`, 1 decimal place) is computed on the frontend in `ReportDetailPage.tsx` (falling back to `100 - downtime_pct`) and highlighted in the summary strip and table.
|
19. **Monthly Maintenance `Uptime %` Display**: The `monthly-maintenance` backend report aggregates uptime/downtime in minutes per department rather than returning per-asset `uptime_seconds`/`downtime_seconds`, so `Uptime %` (`uptime / (uptime + downtime) * 100`, 1 decimal place) is computed on the frontend in `ReportDetailPage.tsx` (falling back to `100 - downtime_pct`) and highlighted in the summary strip and table.
|
||||||
|
20. **Attachment & Data Retention Policy (§4.9, §8)**: In accordance with NABH digital hospital management standards and Indian statutory medical equipment documentation regulations, all equipment service history, breakdown complaint logs, preventive maintenance records, calibration certificates, and uploaded files (PDF/JPG/PNG up to 10 MB) are retained for a minimum mandatory period of **7 years** from creation. Condemned and decommissioned equipment records are permanently maintained in read-only archive status and are never hard-deleted, ensuring unbroken historical auditability. Attachments are stored under `backend/data/uploads/` with UUID filenames and served strictly through authenticated, role-gated download endpoints. Automated backups (`backend/scripts/backup.py`) bundle both the database and attachments into timestamped archives with configurable rolling retention (default: 7 copies).
|
||||||
|
21. **Master Enums vs Editable Tables (§8)**: Critical operational dimensions — complaint `priority` (`critical`, `non_critical`), complaint `call_status` (`open`, `in_progress`, `closed`), equipment `status` (`in_service`, `under_repair`, `condemned`, `out_of_service`), and contract types (`AMC`, `CMC`, `OTHER`) — are intentionally implemented as strict code-enforced Python/TypeScript enums rather than dynamically editable master tables. This design protects the business calculation engine (downtime/uptime percentages, SLA timers, asset status transitions) against data corruption or undefined states that arbitrary user renames could cause.
|
||||||
|
22. **Client Sign-Off & Default Thresholds (§4.3, §4.8, §5, §6)**: The hospital administration configures and approves operational thresholds via the `/settings` management console:
|
||||||
|
- `critical_complaint_sla_hours`: default 4 hours.
|
||||||
|
- `non_critical_complaint_sla_hours`: default 24 hours.
|
||||||
|
- `escalation_open_complaint_hours`: default 24 hours.
|
||||||
|
- `contract_expiry_alert_days`: default 30 days (red critical threshold: 7 days).
|
||||||
|
- `calibration_due_window_days`: default 15 days.
|
||||||
|
- `pm_inhouse_lead_days`: default 7 days; `pm_outsourced_lead_days`: default 15 days.
|
||||||
|
- `require_closure_remarks`: default True.
|
||||||
|
- `downtime_milestone`: default `restoration` (downtime terminates when equipment is restored).
|
||||||
|
23. **Alert Recurrence & Notification Re-trigger Policy (§6)**: The alert engine runs daily at 06:00 Asia/Kolkata and employs deterministic deduplication keys (`dedupe_key`) to prevent duplicate in-app notifications on consecutive days while a condition remains active. Overdue alerts escalate in severity to `red`, and an optional repeat reminder interval (`alert_repeat_days`, default 3 days) re-notifies coordinators and biomedical teams until the underlying task (PM, calibration, contract renewal, or breakdown) is addressed. SMTP email dispatch can be enabled in settings when hospital IT confirms mail server credentials.
|
||||||
|
24. **Duplicate Record & Import Conflict Prevention (Task 1)**:
|
||||||
|
- **Contracts**: A duplicate contract is defined by `(asset_id, contract_type, start_date, end_date)` matching any existing contract in the database (including superseded ones). `POST /api/contracts` rejects exact duplicates with HTTP 409 (`A contract with the same asset, type and dates already exists.`). Contract renewals via `POST /api/contracts/{id}/renew` remain unaffected. In bulk import, in-file duplicate rows receive `Duplicate of row N in this file.` and rows duplicating database records receive `Already exists in the system.`.
|
||||||
|
- **Insurance Policies**: A duplicate insurance policy is defined by trimmed, case-insensitive `policy_no` matching any existing policy in the database. `POST /api/insurance` rejects duplicates with HTTP 409 (`Policy number already exists.`). In bulk import, in-file duplicate rows receive `Duplicate of row N in this file.` and rows duplicating database records receive `Already exists in the system.`.
|
||||||
|
- **Calibration Plans**: Each asset can have at most one calibration plan. In bulk import, rows for assets that already have a calibration plan in the database receive `Asset already has a calibration plan.`, while rows repeating an earlier row for the same asset in the same upload file receive `Duplicate of row N in this file.`. Dry run previews surface these validation errors identically.
|
||||||
|
25. **Import Template Multi-Sheet Structure (Task 2)**: All four bulk-import templates (Assets, Contracts, Calibration Plans, Insurance Policies) feature an empty data template on Sheet 1 (containing only styled headers), an 'Example' reference on Sheet 2 (with warning banner 'Example only - this sheet is ignored on import' in Row 1 and sample values in Row 2), and 'Master Reference' lookup tables on Sheet 3. All four importers read strictly the first worksheet (`wb.worksheets[0]`), ensuring sample rows and reference sheets are never accidentally imported.
|
||||||
|
26. **Backup Script Path Resolution & Dual Archive Packaging (Task 3)**: `backend/scripts/backup.py` exposes `get_db_path(db_url, backend_dir)` to accurately resolve SQLite file paths from `DATABASE_URL` across relative paths (`sqlite:///./data/ams.db`, `sqlite:///data/ams.db`), absolute POSIX/Windows paths (`sqlite:////app/data/ams.db`, `sqlite:////tmp/x/custom.db`), and in-memory or fallback scenarios. `create_backup()` supports both `.tar.gz` and `.zip` archives and packages SQLite database files under both `db.sqlite3` and `ams.db` member names for cross-environment compatibility.
|
||||||
|
27. **Universal Password Policy (Task 4)**: A unified validation rule (`validate_password`) is enforced across user registration, profile updates, self-service password changes, and administrator resets:
|
||||||
|
- Length: 8 to 128 characters.
|
||||||
|
- Character composition: at least one letter and at least one digit (case-insensitive; special characters permitted).
|
||||||
|
- Whitespace: leading and trailing spaces are strictly prohibited and rejected with HTTP 422 (never silently trimmed).
|
||||||
|
- Prohibited passwords: blocklist of common passwords (`123456`, `12345678`, `password`, `password1`, `qwerty123`, `admin123`, `welcome1`), while preserving `demo@123` for seeded testing environments.
|
||||||
|
- Username containment: cannot contain the user's email username (local part before `@`) if 4 or more characters.
|
||||||
|
- Password changes additionally require that the new password is not identical to the current password.
|
||||||
|
28. **Admin Reset Password Interface (Task 5)**: `frontend/src/api/users.ts` and `frontend/src/pages/MastersPage.tsx` expose an administrator password reset modal for users with role `system_admin`. The dialog features password masking toggles, client-side mismatch validation (`Passwords do not match`), universal password policy helper instructions, and displays backend 422 validation errors inline. Successful resets trigger a notification toast and close the modal without affecting the active administrator session.
|
||||||
|
29. **Department User Scoping & Empty Scope Resolution (Task 6)**: `backend/app/services/scoping.py` implements `resolve_department_scope(user, requested_dept_id)`. Non-department roles are unconstrained and may optionally filter by `requested_dept_id`. Assigned `department_user` accounts are strictly bound to `user.department_id`, ignoring any client-requested department parameter. Unassigned `department_user` accounts (`department_id=None`) resolve to `is_empty=True`, immediately returning 0 counters on Dashboard summary, empty results on global search, and empty row lists across all accessible report endpoints without running hospital-wide queries. Report key aliases are registered to support both canonical paths and audit identifiers (e.g., `equipment-inventory`, `condemned-equipment`, `pm-schedule`).
|
||||||
|
30. **Token Versioning & Session Invalidation (Task 7)**: A `token_version` integer column (default 0, not null) is added to `users` and reconciled automatically via `run_sqlite_migrations`. Access tokens encode the user's `token_version` in claim `"tv"`. `get_current_user` rejects tokens with mismatched `"tv"` with HTTP 401 (`Token has been invalidated. Please log in again.`). Password changes and administrator password resets increment `user.token_version`, invalidating previous tokens. `POST /api/auth/change-password` returns a renewed access token, and `ChangePasswordModal.tsx` stores the new token in the active auth store to keep the user's session active without re-login.
|
||||||
|
31. **Delivery Cleanliness, Line Endings & Packaging (Task 8)**: `.gitattributes` enforces standard LF line endings across the repository (`* text=auto eol=lf`). `.gitignore` excludes all SQLite databases (`*.db`), backups, volatile uploads, frontend dist artifacts, and build info files. The `make package` target generates `../poona-ams-delivery.zip` using `git archive` to ensure zero uncommitted, ignored, or temporary files leak into handoff archives.
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
# Poona Hospital AMS — Role-Based User Guide
|
||||||
|
|
||||||
|
Welcome to the Poona Hospital Asset Management & Maintenance System. This quick-start guide details the day-to-day operations, permissions, and typical workflows for each user role.
|
||||||
|
|
||||||
|
All demo accounts share the password: `Demo@123`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. System Administrator (`admin@poona.demo`)
|
||||||
|
|
||||||
|
The System Administrator oversees system security, reference masters, user access, and global configuration.
|
||||||
|
|
||||||
|
### Key Capabilities
|
||||||
|
- **Master Data Management (`/masters`)**: Maintain active Departments, Physical Locations, Equipment Categories, Vendors/Suppliers, and System Users. Masters use soft deletion to preserve historical linkage.
|
||||||
|
- **Admin Password Reset**: Admins can click "Reset password" on any user row on the Users tab to set a new password directly from the UI. Resetting invalidates all existing active sessions of that user immediately via token versioning.
|
||||||
|
- **Universal Password Policy**: Passwords must be 8–128 characters, contain at least one letter and one number, have no leading/trailing spaces, avoid common blocklisted passwords, and cannot contain the user's email username.
|
||||||
|
- **System Settings (`/settings`)**: Configure hospital-wide business rules:
|
||||||
|
- SLA thresholds (`critical_complaint_sla_hours`, `non_critical_complaint_sla_hours`)
|
||||||
|
- Alert lead times for Contracts, PM, Calibration, Insurance, and Demo Equipment
|
||||||
|
- Mandatory closure remarks toggle (`require_closure_remarks`)
|
||||||
|
- Downtime calculation milestone (`attendance`, `restoration`, or `closure`)
|
||||||
|
- Demo Clock (`demo_as_of_date`) to simulate future dates for testing alerts
|
||||||
|
- **Audit Logs (`/audit-logs`)**: Search, filter, and inspect detailed JSON diffs of all system mutations and user actions.
|
||||||
|
- **Bulk Imports & Duplicate Prevention**:
|
||||||
|
- Download official templates for Assets, Contracts, Calibration Plans, and Insurance Policies (templates include empty headers on Sheet 1 and example rows on Sheet 2).
|
||||||
|
- Exact duplicates in file uploads or direct creations (duplicate contracts with matching asset/type/dates, duplicate insurance policy numbers, or duplicate calibration plans per asset) are rejected with clear line-item error messages or HTTP 409 status.
|
||||||
|
- **Database Backup & Recovery**: Execute `python scripts/backup.py` to create a safe online snapshot (.tar.gz or .zip) of the database and uploaded attachments.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Biomedical Engineer (`bio@poona.demo`)
|
||||||
|
|
||||||
|
Biomedical Engineers handle physical medical assets, breakdown repairs, preventative maintenance schedules, and rounds.
|
||||||
|
|
||||||
|
### Key Workflows
|
||||||
|
- **Asset Registration & Maintenance (`/assets`)**:
|
||||||
|
- Register new medical equipment with full technical, procurement, warranty, and vendor details.
|
||||||
|
- View comprehensive 8-tab overview for any asset (PM, Calibration, Contracts, Insurance, History).
|
||||||
|
- **Breakdown Complaint Management (`/complaints`)**:
|
||||||
|
- Attend assigned complaints and log attendance timestamps.
|
||||||
|
- Document technical actions: Company Engineer (CE) details, action taken, spare parts required, root cause, and corrective action.
|
||||||
|
- Mark equipment as **Restored** when functioning (automatically returning asset to `in_service`).
|
||||||
|
- Close complaints with mandatory closure remarks.
|
||||||
|
- **Preventive Maintenance (`/pm`)**:
|
||||||
|
- View planned PM in Table or 7-column Calendar views.
|
||||||
|
- Execute PM records, attach vendor service reports/job sheets, and automatically advance next planned cycle.
|
||||||
|
- **Department Rounds (`/visits`)**:
|
||||||
|
- Conduct daily/weekly rounds, inspect equipment by department, log observations, note new equipment requirements, and link or spawn breakdown complaints directly from the visit sheet.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Department User (`dept@poona.demo` — ICU)
|
||||||
|
|
||||||
|
Department Users (Nurses, In-charges, Technicians) raise and monitor breakdown calls for their own department.
|
||||||
|
|
||||||
|
### Key Workflows
|
||||||
|
- **Scoped View**: Automatically restricted to seeing only assets and complaints belonging to their assigned department (e.g., ICU).
|
||||||
|
- If a department user account is created without an assigned department (`department_id=None`), the user is scoped to an empty dataset by default (seeing zero assets, zero complaints, and zero dashboard metrics) to prevent unintended access to hospital-wide data.
|
||||||
|
- **Raising Complaints (`/complaints`)**:
|
||||||
|
- Click **Raise Complaint**, search for the faulty equipment using `AssetPicker` (which highlights warranty and condemnation status), choose Priority (`Critical` or `Non-Critical`), and enter the problem description.
|
||||||
|
- Attach photos or fault screenshots directly.
|
||||||
|
- **Tracking Progress**:
|
||||||
|
- Monitor real-time status chips (`Open`, `In Progress`, `Closed`).
|
||||||
|
- View assignment details and attendance timestamps.
|
||||||
|
- Technical engineering fields, spare parts costs, and master configurations are safely locked (read-only).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Management (`mgmt@poona.demo`)
|
||||||
|
|
||||||
|
Hospital Management (Medical Superintendent, Directors, Quality Heads) review operational performance, KPIs, and reports.
|
||||||
|
|
||||||
|
### Key Capabilities
|
||||||
|
- **Hospital Operations Dashboard (`/`)**:
|
||||||
|
- High-level KPI summary: Total Assets, Equipment Under Repair, Open Complaints, Critical Breakdown Calls, and PM Compliance rate.
|
||||||
|
- Interactive charts: Complaints by Status, Complaints by Department, 6-Month Downtime Trend, and PM Performance.
|
||||||
|
- Clickable "Needs Attention" list highlighting urgent overdue items.
|
||||||
|
- **Calibration Plan Approvals (`/calibration`)**:
|
||||||
|
- Review and approve calibration frequencies set on critical biomedical equipment (gated specifically to Management and Administration).
|
||||||
|
- **8 Operational Reports (`/reports`)**:
|
||||||
|
- Monthly Maintenance Summary with downtime minutes and Uptime % calculations.
|
||||||
|
- Monthly Department Performance, PM Compliance, Calibration Due, AMC/CMC Validity, and Breakdown Analytics.
|
||||||
|
- One-click Excel spreadsheet (`.xlsx`) export and print-ready A4 landscape layouts.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Clinical Coordinator (`coord@poona.demo`)
|
||||||
|
|
||||||
|
Coordinators manage legal contracts, equipment warranties, insurance coverage, and loaner/demo devices.
|
||||||
|
|
||||||
|
### Key Workflows
|
||||||
|
- **Contracts & Warranties (`/contracts`)**:
|
||||||
|
- Register AMC and CMC service agreements, coverage periods, and vendor contacts.
|
||||||
|
- Upload signed contract PDFs or warranty certificates.
|
||||||
|
- Renew expiring contracts with automatic superseding of prior contracts and full history chain retention.
|
||||||
|
- **Asset Insurance (`/insurance`)**:
|
||||||
|
- Record policy numbers, insurance companies, coverage sums in INR, and effective dates.
|
||||||
|
- Quick-access **Insurance Drawer** lets users inspect policy details directly from any asset or breakdown record.
|
||||||
|
- **Demo & Trial Equipment (`/demo-equipment`)**:
|
||||||
|
- Track evaluation and trial machines on loan from vendors.
|
||||||
|
- Record serial numbers, trial durations, expected return dates, and log official returns.
|
||||||
|
- **Notifications & Expiry Alerts (`/notifications`)**:
|
||||||
|
- Receive automated 30-day advance alerts for expiring contracts, warranties, and insurance policies.
|
||||||
|
|
||||||
Generated
+96
@@ -34,6 +34,7 @@
|
|||||||
"recharts": "^2.13.3",
|
"recharts": "^2.13.3",
|
||||||
"tailwind-merge": "^2.5.4",
|
"tailwind-merge": "^2.5.4",
|
||||||
"xlsx": "^0.18.5",
|
"xlsx": "^0.18.5",
|
||||||
|
"xlsx-js-style": "^1.2.0",
|
||||||
"zod": "^3.23.8",
|
"zod": "^3.23.8",
|
||||||
"zustand": "^4.5.5"
|
"zustand": "^4.5.5"
|
||||||
},
|
},
|
||||||
@@ -4700,6 +4701,15 @@
|
|||||||
"integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
|
"integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/exit-on-epipe": {
|
||||||
|
"version": "1.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/exit-on-epipe/-/exit-on-epipe-1.0.1.tgz",
|
||||||
|
"integrity": "sha512-h2z5mrROTxce56S+pnvAV890uu7ls7f1kEvVGJbw1OlFH3/mlJ5bkXu0KRyW94v37zzHPiUd55iLn3DA7TjWpw==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/expect-type": {
|
"node_modules/expect-type": {
|
||||||
"version": "1.4.0",
|
"version": "1.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
|
||||||
@@ -4798,6 +4808,12 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/fflate": {
|
||||||
|
"version": "0.3.11",
|
||||||
|
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.3.11.tgz",
|
||||||
|
"integrity": "sha512-Rr5QlUeGN1mbOHlaqcSYMKVpPbgLy0AWT/W0EHxA6NGI12yO1jpoui2zBBvU2G824ltM6Ut8BFgfHSBGfkmS0A==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/file-entry-cache": {
|
"node_modules/file-entry-cache": {
|
||||||
"version": "8.0.0",
|
"version": "8.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
|
||||||
@@ -6070,6 +6086,18 @@
|
|||||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/printj": {
|
||||||
|
"version": "1.1.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/printj/-/printj-1.1.2.tgz",
|
||||||
|
"integrity": "sha512-zA2SmoLaxZyArQTOPj5LXecR+RagfPSU5Kw1qP+jkWeNlrq+eJZyY2oS68SU1Z/7/myXM4lo9716laOFAVStCQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"printj": "bin/printj.njs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/prop-types": {
|
"node_modules/prop-types": {
|
||||||
"version": "15.8.1",
|
"version": "15.8.1",
|
||||||
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
||||||
@@ -7419,6 +7447,74 @@
|
|||||||
"node": ">=0.8"
|
"node": ">=0.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/xlsx-js-style": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/xlsx-js-style/-/xlsx-js-style-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-DDT4FXFSWfT4DXMSok/m3TvmP1gvO3dn0Eu/c+eXHW5Kzmp7IczNkxg/iEPnImbG9X0Vb8QhROda5eatSR/97Q==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"adler-32": "~1.2.0",
|
||||||
|
"cfb": "^1.1.4",
|
||||||
|
"codepage": "~1.14.0",
|
||||||
|
"commander": "~2.17.1",
|
||||||
|
"crc-32": "~1.2.0",
|
||||||
|
"exit-on-epipe": "~1.0.1",
|
||||||
|
"fflate": "^0.3.8",
|
||||||
|
"ssf": "~0.11.2",
|
||||||
|
"wmf": "~1.0.1",
|
||||||
|
"word": "~0.3.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"xlsx": "bin/xlsx.njs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/xlsx-js-style/node_modules/adler-32": {
|
||||||
|
"version": "1.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.2.0.tgz",
|
||||||
|
"integrity": "sha512-/vUqU/UY4MVeFsg+SsK6c+/05RZXIHZMGJA+PX5JyWI0ZRcBpupnRuPLU/NXXoFwMYCPCoxIfElM2eS+DUXCqQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"exit-on-epipe": "~1.0.1",
|
||||||
|
"printj": "~1.1.0"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"adler32": "bin/adler32.njs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/xlsx-js-style/node_modules/codepage": {
|
||||||
|
"version": "1.14.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/codepage/-/codepage-1.14.0.tgz",
|
||||||
|
"integrity": "sha512-iz3zJLhlrg37/gYRWgEPkaFTtzmnEv1h+r7NgZum2lFElYQPi0/5bnmuDfODHxfp0INEfnRqyfyeIJDbb7ahRw==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"commander": "~2.14.1",
|
||||||
|
"exit-on-epipe": "~1.0.1"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"codepage": "bin/codepage.njs"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=0.8"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/xlsx-js-style/node_modules/codepage/node_modules/commander": {
|
||||||
|
"version": "2.14.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/commander/-/commander-2.14.1.tgz",
|
||||||
|
"integrity": "sha512-+YR16o3rK53SmWHU3rEM3tPAh2rwb1yPcQX5irVn7mb0gXbwuCCrnkbV5+PBfETdfg1vui07nM6PCG1zndcjQw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/xlsx-js-style/node_modules/commander": {
|
||||||
|
"version": "2.17.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/commander/-/commander-2.17.1.tgz",
|
||||||
|
"integrity": "sha512-wPMUt6FnH2yzG95SA6mzjQOEKUU3aLaDEmzs1ti+1E9h+CsrZghRlqEM/EJ4KscsQVG8uNN4uVreUeT8+drlgg==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/xml-name-validator": {
|
"node_modules/xml-name-validator": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
||||||
|
|||||||
@@ -37,6 +37,7 @@
|
|||||||
"recharts": "^2.13.3",
|
"recharts": "^2.13.3",
|
||||||
"tailwind-merge": "^2.5.4",
|
"tailwind-merge": "^2.5.4",
|
||||||
"xlsx": "^0.18.5",
|
"xlsx": "^0.18.5",
|
||||||
|
"xlsx-js-style": "^1.2.0",
|
||||||
"zod": "^3.23.8",
|
"zod": "^3.23.8",
|
||||||
"zustand": "^4.5.5"
|
"zustand": "^4.5.5"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -200,6 +200,8 @@ export interface AssetListParams {
|
|||||||
supplier_id?: number;
|
supplier_id?: number;
|
||||||
status?: AssetStatus | "";
|
status?: AssetStatus | "";
|
||||||
criticality?: AssetCriticality | "";
|
criticality?: AssetCriticality | "";
|
||||||
|
requires_calibration?: boolean;
|
||||||
|
insurance_applicable?: boolean;
|
||||||
page?: number;
|
page?: number;
|
||||||
page_size?: number;
|
page_size?: number;
|
||||||
sort?: string;
|
sort?: string;
|
||||||
@@ -264,6 +266,8 @@ export const assetsApi = {
|
|||||||
if (params.supplier_id) qs.set("supplier_id", String(params.supplier_id));
|
if (params.supplier_id) qs.set("supplier_id", String(params.supplier_id));
|
||||||
if (params.status) qs.set("status", params.status);
|
if (params.status) qs.set("status", params.status);
|
||||||
if (params.criticality) qs.set("criticality", params.criticality);
|
if (params.criticality) qs.set("criticality", params.criticality);
|
||||||
|
if (params.requires_calibration !== undefined) qs.set("requires_calibration", String(params.requires_calibration));
|
||||||
|
if (params.insurance_applicable !== undefined) qs.set("insurance_applicable", String(params.insurance_applicable));
|
||||||
qs.set("page", String(params.page ?? 1));
|
qs.set("page", String(params.page ?? 1));
|
||||||
qs.set("page_size", String(params.page_size ?? 200));
|
qs.set("page_size", String(params.page_size ?? 200));
|
||||||
if (params.sort) qs.set("sort", params.sort);
|
if (params.sort) qs.set("sort", params.sort);
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ export type AttachmentEntityType =
|
|||||||
| "insurance"
|
| "insurance"
|
||||||
| "demo_equipment"
|
| "demo_equipment"
|
||||||
| "asset"
|
| "asset"
|
||||||
| "warranty";
|
| "warranty"
|
||||||
|
| "pm_record";
|
||||||
|
|
||||||
export interface AttachmentItem {
|
export interface AttachmentItem {
|
||||||
id: number;
|
id: number;
|
||||||
|
|||||||
@@ -25,3 +25,16 @@ export function loginApi(email: string, password: string) {
|
|||||||
export function fetchMeApi() {
|
export function fetchMeApi() {
|
||||||
return api.get<UserOut>("/auth/me");
|
return api.get<UserOut>("/auth/me");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ChangePasswordResponse {
|
||||||
|
message: string;
|
||||||
|
access_token?: string;
|
||||||
|
token_type?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function changePasswordApi(current_password: string, new_password: string) {
|
||||||
|
return api.post<ChangePasswordResponse>("/auth/change-password", {
|
||||||
|
current_password,
|
||||||
|
new_password,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { api } from "./client";
|
import { api } from "./client";
|
||||||
|
import type { BulkImportResult } from "./assets";
|
||||||
|
|
||||||
export interface CalibrationPlanItem {
|
export interface CalibrationPlanItem {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -142,4 +143,23 @@ export const calibrationApi = {
|
|||||||
completed_record: CalibrationRecordItem;
|
completed_record: CalibrationRecordItem;
|
||||||
next_record: CalibrationRecordItem;
|
next_record: CalibrationRecordItem;
|
||||||
}>(`/calibration/records/${id}/complete`, data),
|
}>(`/calibration/records/${id}/complete`, data),
|
||||||
|
downloadImportTemplate: async () => {
|
||||||
|
const { blob } = await api.downloadBlob("/calibration/import-template");
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = url;
|
||||||
|
a.download = "calibration_import_template.xlsx";
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
},
|
||||||
|
bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("file", file);
|
||||||
|
return api.upload<BulkImportResult>(
|
||||||
|
`/calibration/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||||
|
formData
|
||||||
|
);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ export interface ComplaintItem {
|
|||||||
received_at: string | null;
|
received_at: string | null;
|
||||||
assigned_to_id: number | null;
|
assigned_to_id: number | null;
|
||||||
assigned_to_name: string | null;
|
assigned_to_name: string | null;
|
||||||
|
assigned_team?: string | null;
|
||||||
assigned_at: string | null;
|
assigned_at: string | null;
|
||||||
attended_by_id: number | null;
|
attended_by_id: number | null;
|
||||||
attended_by_name: string | null;
|
attended_by_name: string | null;
|
||||||
@@ -77,6 +78,7 @@ export interface ComplaintEventItem {
|
|||||||
export interface ComplaintListParams {
|
export interface ComplaintListParams {
|
||||||
q?: string;
|
q?: string;
|
||||||
department_id?: number;
|
department_id?: number;
|
||||||
|
location_id?: number;
|
||||||
asset_id?: number;
|
asset_id?: number;
|
||||||
call_status?: CallStatus | "";
|
call_status?: CallStatus | "";
|
||||||
priority?: AssetCriticality | "";
|
priority?: AssetCriticality | "";
|
||||||
@@ -94,6 +96,7 @@ export interface ComplaintCreatePayload {
|
|||||||
breakdown_details?: string | null;
|
breakdown_details?: string | null;
|
||||||
priority: AssetCriticality;
|
priority: AssetCriticality;
|
||||||
notes?: string | null;
|
notes?: string | null;
|
||||||
|
assigned_team?: string | null;
|
||||||
received_by_id?: number | null;
|
received_by_id?: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,6 +105,7 @@ export interface ComplaintUpdatePayload {
|
|||||||
breakdown_details?: string | null;
|
breakdown_details?: string | null;
|
||||||
priority?: AssetCriticality;
|
priority?: AssetCriticality;
|
||||||
notes?: string | null;
|
notes?: string | null;
|
||||||
|
assigned_team?: string | null;
|
||||||
action_taken?: string | null;
|
action_taken?: string | null;
|
||||||
root_cause?: string | null;
|
root_cause?: string | null;
|
||||||
corrective_action?: string | null;
|
corrective_action?: string | null;
|
||||||
@@ -119,6 +123,7 @@ export const complaintsApi = {
|
|||||||
const qs = new URLSearchParams();
|
const qs = new URLSearchParams();
|
||||||
if (params.q) qs.set("q", params.q);
|
if (params.q) qs.set("q", params.q);
|
||||||
if (params.department_id) qs.set("department_id", String(params.department_id));
|
if (params.department_id) qs.set("department_id", String(params.department_id));
|
||||||
|
if (params.location_id) qs.set("location_id", String(params.location_id));
|
||||||
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
|
if (params.asset_id) qs.set("asset_id", String(params.asset_id));
|
||||||
if (params.call_status) qs.set("call_status", params.call_status);
|
if (params.call_status) qs.set("call_status", params.call_status);
|
||||||
if (params.priority) qs.set("priority", params.priority);
|
if (params.priority) qs.set("priority", params.priority);
|
||||||
@@ -136,7 +141,7 @@ export const complaintsApi = {
|
|||||||
api.get<{ items: ComplaintEventItem[]; total: number }>(`/complaints/${id}/events`),
|
api.get<{ items: ComplaintEventItem[]; total: number }>(`/complaints/${id}/events`),
|
||||||
update: (id: number, data: ComplaintUpdatePayload) =>
|
update: (id: number, data: ComplaintUpdatePayload) =>
|
||||||
api.patch<ComplaintItem>(`/complaints/${id}`, data),
|
api.patch<ComplaintItem>(`/complaints/${id}`, data),
|
||||||
assign: (id: number, data: { assigned_to_id: number; note?: string }) =>
|
assign: (id: number, data: { assigned_to_id?: number | null; assigned_team?: string | null; note?: string }) =>
|
||||||
api.post<ComplaintItem>(`/complaints/${id}/assign`, data),
|
api.post<ComplaintItem>(`/complaints/${id}/assign`, data),
|
||||||
attend: (id: number, data: { attended_by_id?: number; note?: string } = {}) =>
|
attend: (id: number, data: { attended_by_id?: number; note?: string } = {}) =>
|
||||||
api.post<ComplaintItem>(`/complaints/${id}/attend`, data),
|
api.post<ComplaintItem>(`/complaints/${id}/attend`, data),
|
||||||
|
|||||||
@@ -153,6 +153,8 @@ export const usersApi = {
|
|||||||
}>
|
}>
|
||||||
) => api.patch<MasterUser>(`/users/${id}`, data),
|
) => api.patch<MasterUser>(`/users/${id}`, data),
|
||||||
remove: (id: number) => api.delete<void>(`/users/${id}`),
|
remove: (id: number) => api.delete<void>(`/users/${id}`),
|
||||||
|
resetPassword: (id: number, new_password: string) =>
|
||||||
|
api.post<{ message: string }>(`/users/${id}/reset-password`, { new_password }),
|
||||||
};
|
};
|
||||||
|
|
||||||
export interface UserLookupItem {
|
export interface UserLookupItem {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { api } from "./client";
|
import { api } from "./client";
|
||||||
import type { AlertSeverity, CoverageStatus } from "./assets";
|
import type { AlertSeverity, BulkImportResult, CoverageStatus } from "./assets";
|
||||||
|
|
||||||
export type ContractStatus = CoverageStatus | "superseded";
|
export type ContractStatus = CoverageStatus | "superseded";
|
||||||
export type DemoStatus = "on_demo" | "overdue_return" | "returned";
|
export type DemoStatus = "on_demo" | "overdue_return" | "returned";
|
||||||
@@ -35,6 +35,8 @@ export interface ContractListParams {
|
|||||||
contract_type?: string;
|
contract_type?: string;
|
||||||
status?: string;
|
status?: string;
|
||||||
include_superseded?: boolean;
|
include_superseded?: boolean;
|
||||||
|
expiry_from?: string;
|
||||||
|
expiry_to?: string;
|
||||||
page?: number;
|
page?: number;
|
||||||
page_size?: number;
|
page_size?: number;
|
||||||
}
|
}
|
||||||
@@ -83,6 +85,8 @@ export interface WarrantyListParams {
|
|||||||
department_id?: number;
|
department_id?: number;
|
||||||
asset_id?: number;
|
asset_id?: number;
|
||||||
status?: string;
|
status?: string;
|
||||||
|
expiry_from?: string;
|
||||||
|
expiry_to?: string;
|
||||||
page?: number;
|
page?: number;
|
||||||
page_size?: number;
|
page_size?: number;
|
||||||
}
|
}
|
||||||
@@ -123,6 +127,8 @@ export interface InsuranceListParams {
|
|||||||
asset_id?: number;
|
asset_id?: number;
|
||||||
insurer_id?: number;
|
insurer_id?: number;
|
||||||
status?: string;
|
status?: string;
|
||||||
|
expiry_from?: string;
|
||||||
|
expiry_to?: string;
|
||||||
page?: number;
|
page?: number;
|
||||||
page_size?: number;
|
page_size?: number;
|
||||||
}
|
}
|
||||||
@@ -141,6 +147,7 @@ export interface DemoEquipmentItem {
|
|||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
equipment_type: string;
|
equipment_type: string;
|
||||||
|
serial_no?: string | null;
|
||||||
supplier_id: number;
|
supplier_id: number;
|
||||||
supplier_name: string | null;
|
supplier_name: string | null;
|
||||||
department_id: number;
|
department_id: number;
|
||||||
@@ -172,6 +179,7 @@ export interface DemoListParams {
|
|||||||
export interface DemoCreatePayload {
|
export interface DemoCreatePayload {
|
||||||
name: string;
|
name: string;
|
||||||
equipment_type: string;
|
equipment_type: string;
|
||||||
|
serial_no?: string | null;
|
||||||
supplier_id: number;
|
supplier_id: number;
|
||||||
department_id: number;
|
department_id: number;
|
||||||
location_id?: number | null;
|
location_id?: number | null;
|
||||||
@@ -202,6 +210,7 @@ export interface VisitItem {
|
|||||||
visited_by_name: string | null;
|
visited_by_name: string | null;
|
||||||
visit_date: string;
|
visit_date: string;
|
||||||
observations: string;
|
observations: string;
|
||||||
|
new_requirements?: string | null;
|
||||||
assets: VisitAssetBrief[];
|
assets: VisitAssetBrief[];
|
||||||
complaints: VisitComplaintBrief[];
|
complaints: VisitComplaintBrief[];
|
||||||
created_at: string;
|
created_at: string;
|
||||||
@@ -221,6 +230,7 @@ export interface VisitCreatePayload {
|
|||||||
department_id: number;
|
department_id: number;
|
||||||
visit_date: string;
|
visit_date: string;
|
||||||
observations: string;
|
observations: string;
|
||||||
|
new_requirements?: string | null;
|
||||||
asset_ids?: number[];
|
asset_ids?: number[];
|
||||||
complaint_ids?: number[];
|
complaint_ids?: number[];
|
||||||
}
|
}
|
||||||
@@ -251,6 +261,25 @@ export const contractsApi = {
|
|||||||
),
|
),
|
||||||
history: (assetId: number) =>
|
history: (assetId: number) =>
|
||||||
api.get<{ items: ContractItem[] }>(`/contracts/history/${assetId}`),
|
api.get<{ items: ContractItem[] }>(`/contracts/history/${assetId}`),
|
||||||
|
downloadImportTemplate: async () => {
|
||||||
|
const { blob } = await api.downloadBlob("/contracts/import-template");
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = url;
|
||||||
|
a.download = "contracts_import_template.xlsx";
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
},
|
||||||
|
bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("file", file);
|
||||||
|
return api.upload<BulkImportResult>(
|
||||||
|
`/contracts/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||||
|
formData
|
||||||
|
);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export const warrantiesApi = {
|
export const warrantiesApi = {
|
||||||
@@ -273,6 +302,25 @@ export const insuranceApi = {
|
|||||||
update: (id: number, data: Partial<InsuranceCreatePayload>) =>
|
update: (id: number, data: Partial<InsuranceCreatePayload>) =>
|
||||||
api.patch<InsuranceItem>(`/insurance/${id}`, data),
|
api.patch<InsuranceItem>(`/insurance/${id}`, data),
|
||||||
remove: (id: number) => api.delete<void>(`/insurance/${id}`),
|
remove: (id: number) => api.delete<void>(`/insurance/${id}`),
|
||||||
|
downloadImportTemplate: async () => {
|
||||||
|
const { blob } = await api.downloadBlob("/insurance/import-template");
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = url;
|
||||||
|
a.download = "insurance_import_template.xlsx";
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
},
|
||||||
|
bulkImport: (file: File, dryRun: boolean, skipInvalid: boolean) => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("file", file);
|
||||||
|
return api.upload<BulkImportResult>(
|
||||||
|
`/insurance/bulk-import?dry_run=${dryRun}&skip_invalid=${skipInvalid}`,
|
||||||
|
formData
|
||||||
|
);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export const demoEquipmentApi = {
|
export const demoEquipmentApi = {
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { api } from "./client";
|
||||||
|
import { usersApi } from "./masters";
|
||||||
|
|
||||||
|
export { usersApi };
|
||||||
|
|
||||||
|
export const resetPassword = (id: number, new_password: string) =>
|
||||||
|
api.post<{ message: string }>(`/users/${id}/reset-password`, { new_password });
|
||||||
@@ -0,0 +1,403 @@
|
|||||||
|
import { useRef, useState } from "react";
|
||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
Download,
|
||||||
|
FileSpreadsheet,
|
||||||
|
Upload,
|
||||||
|
CheckCircle2,
|
||||||
|
AlertCircle,
|
||||||
|
X,
|
||||||
|
} from "lucide-react";
|
||||||
|
import type { BulkImportResult } from "@/api/assets";
|
||||||
|
import { ApiError } from "@/api/client";
|
||||||
|
import { Modal } from "@/components/ui/dialog";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { toast } from "@/lib/toast";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
export interface PreviewColumn {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BulkGenericImportModalProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
entityName: string;
|
||||||
|
templateFilename: string;
|
||||||
|
onDownloadTemplate: () => Promise<void>;
|
||||||
|
onImport: (file: File, dryRun: boolean, skipInvalid: boolean) => Promise<BulkImportResult>;
|
||||||
|
queryKeysToInvalidate: string[][];
|
||||||
|
previewColumns: PreviewColumn[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const ACCEPTED_EXTS = [".xlsx", ".xls", ".csv"];
|
||||||
|
|
||||||
|
export function BulkGenericImportModal({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
entityName,
|
||||||
|
templateFilename,
|
||||||
|
onDownloadTemplate,
|
||||||
|
onImport,
|
||||||
|
queryKeysToInvalidate,
|
||||||
|
previewColumns,
|
||||||
|
}: BulkGenericImportModalProps) {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||||
|
const [dragActive, setDragActive] = useState(false);
|
||||||
|
const [downloadingTemplate, setDownloadingTemplate] = useState(false);
|
||||||
|
const [validating, setValidating] = useState(false);
|
||||||
|
const [importing, setImporting] = useState(false);
|
||||||
|
const [skipInvalid, setSkipInvalid] = useState(false);
|
||||||
|
const [preview, setPreview] = useState<BulkImportResult | null>(null);
|
||||||
|
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||||
|
|
||||||
|
function resetState() {
|
||||||
|
setSelectedFile(null);
|
||||||
|
setPreview(null);
|
||||||
|
setErrorMsg(null);
|
||||||
|
setSkipInvalid(false);
|
||||||
|
setValidating(false);
|
||||||
|
setImporting(false);
|
||||||
|
if (fileInputRef.current) fileInputRef.current.value = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClose() {
|
||||||
|
if (importing) return;
|
||||||
|
resetState();
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDownloadTemplate() {
|
||||||
|
setDownloadingTemplate(true);
|
||||||
|
setErrorMsg(null);
|
||||||
|
try {
|
||||||
|
await onDownloadTemplate();
|
||||||
|
toast.success(`Downloaded ${templateFilename}`);
|
||||||
|
} catch (err) {
|
||||||
|
const msg =
|
||||||
|
err instanceof ApiError
|
||||||
|
? err.detail
|
||||||
|
: "Failed to download import template.";
|
||||||
|
setErrorMsg(msg);
|
||||||
|
toast.error(msg);
|
||||||
|
} finally {
|
||||||
|
setDownloadingTemplate(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleFileSelect(files: FileList | null) {
|
||||||
|
if (!files || files.length === 0) return;
|
||||||
|
const file = files[0];
|
||||||
|
const lower = file.name.toLowerCase();
|
||||||
|
if (!ACCEPTED_EXTS.some((ext) => lower.endsWith(ext))) {
|
||||||
|
setErrorMsg("Unsupported file type. Please upload an .xlsx, .xls, or .csv file.");
|
||||||
|
setSelectedFile(null);
|
||||||
|
setPreview(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSelectedFile(file);
|
||||||
|
setErrorMsg(null);
|
||||||
|
setPreview(null);
|
||||||
|
setSkipInvalid(false);
|
||||||
|
setValidating(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await onImport(file, true, false);
|
||||||
|
setPreview(result);
|
||||||
|
} catch (err) {
|
||||||
|
const msg =
|
||||||
|
err instanceof ApiError
|
||||||
|
? err.detail
|
||||||
|
: "Failed to validate import file.";
|
||||||
|
setErrorMsg(msg);
|
||||||
|
} finally {
|
||||||
|
setValidating(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleConfirmImport() {
|
||||||
|
if (!selectedFile || !preview) return;
|
||||||
|
setImporting(true);
|
||||||
|
setErrorMsg(null);
|
||||||
|
try {
|
||||||
|
const result = await onImport(selectedFile, false, skipInvalid);
|
||||||
|
await Promise.all(
|
||||||
|
queryKeysToInvalidate.map((key) => qc.invalidateQueries({ queryKey: key }))
|
||||||
|
);
|
||||||
|
toast.success(
|
||||||
|
`Imported ${result.created_count} ${entityName.toLowerCase()}${
|
||||||
|
result.created_count === 1 ? "" : "s"
|
||||||
|
}`
|
||||||
|
);
|
||||||
|
resetState();
|
||||||
|
onClose();
|
||||||
|
} catch (err) {
|
||||||
|
const msg =
|
||||||
|
err instanceof ApiError ? err.detail : `Bulk ${entityName.toLowerCase()} import failed.`;
|
||||||
|
setErrorMsg(msg);
|
||||||
|
toast.error(msg);
|
||||||
|
} finally {
|
||||||
|
setImporting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const canImport =
|
||||||
|
Boolean(selectedFile && preview) &&
|
||||||
|
!validating &&
|
||||||
|
!importing &&
|
||||||
|
preview!.valid_count > 0 &&
|
||||||
|
(preview!.error_count === 0 || skipInvalid);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
if (!next) handleClose();
|
||||||
|
}}
|
||||||
|
title={title}
|
||||||
|
description={description}
|
||||||
|
className="max-w-4xl"
|
||||||
|
>
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Step 1: Template Download */}
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 rounded-lg border border-blue-200 bg-blue-50/70 p-3.5">
|
||||||
|
<div className="flex items-start gap-2.5 text-xs text-blue-950">
|
||||||
|
<FileSpreadsheet className="h-5 w-5 text-[#1e3a8a] shrink-0 mt-0.5" />
|
||||||
|
<div>
|
||||||
|
<div className="font-semibold text-sm text-[#1e3a8a]">
|
||||||
|
Step 1: Download the Excel Template
|
||||||
|
</div>
|
||||||
|
<p className="mt-0.5 text-blue-900/90">
|
||||||
|
Download the official pre-formatted template with lookup references before uploading.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
loading={downloadingTemplate}
|
||||||
|
onClick={handleDownloadTemplate}
|
||||||
|
className="shrink-0 bg-white"
|
||||||
|
>
|
||||||
|
<Download className="h-4 w-4 mr-1.5" />
|
||||||
|
Download Template (.xlsx)
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Step 2: File Picker / Dropzone */}
|
||||||
|
<div
|
||||||
|
onDragOver={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragActive(true);
|
||||||
|
}}
|
||||||
|
onDragLeave={() => setDragActive(false)}
|
||||||
|
onDrop={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragActive(false);
|
||||||
|
void handleFileSelect(e.dataTransfer.files);
|
||||||
|
}}
|
||||||
|
className={cn(
|
||||||
|
"border-2 border-dashed rounded-lg p-5 text-center transition-colors",
|
||||||
|
dragActive
|
||||||
|
? "border-[#1e3a8a] bg-blue-50"
|
||||||
|
: "border-gray-300 bg-gray-50/60 hover:bg-gray-50"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept=".xlsx,.xls,.csv"
|
||||||
|
aria-label={`Upload ${entityName.toLowerCase()} spreadsheet`}
|
||||||
|
onChange={(e) => void handleFileSelect(e.target.files)}
|
||||||
|
className="hidden"
|
||||||
|
/>
|
||||||
|
<Upload className="h-7 w-7 text-gray-400 mx-auto mb-2" />
|
||||||
|
<p className="text-sm font-medium text-gray-800">
|
||||||
|
{selectedFile ? selectedFile.name : "Drop your spreadsheet here, or browse"}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-gray-500 mt-1">
|
||||||
|
Accepts <code>.xlsx</code>, <code>.xls</code>, or <code>.csv</code> — automatically validates rows before importing.
|
||||||
|
</p>
|
||||||
|
<div className="mt-3 flex items-center justify-center gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={validating || importing}
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
>
|
||||||
|
{selectedFile ? "Choose Another File" : "Select Spreadsheet"}
|
||||||
|
</Button>
|
||||||
|
{selectedFile && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
disabled={validating || importing}
|
||||||
|
onClick={resetState}
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5 mr-1" />
|
||||||
|
Clear
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{validating && (
|
||||||
|
<div className="rounded-md border border-blue-200 bg-blue-50 px-3.5 py-2.5 text-xs text-blue-900">
|
||||||
|
Validating rows against hospital masters...
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{errorMsg && (
|
||||||
|
<div
|
||||||
|
role="alert"
|
||||||
|
className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800"
|
||||||
|
>
|
||||||
|
<AlertCircle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />
|
||||||
|
<span>{errorMsg}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Step 3: Dry-run Validation Preview */}
|
||||||
|
{preview && (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700 border border-gray-200">
|
||||||
|
Total Rows: {preview.total_rows}
|
||||||
|
</span>
|
||||||
|
<span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
|
||||||
|
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||||
|
Valid: {preview.valid_count}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium border",
|
||||||
|
preview.error_count > 0
|
||||||
|
? "bg-red-100 text-red-800 border-red-200"
|
||||||
|
: "bg-gray-100 text-gray-600 border-gray-200"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<AlertCircle className="h-3.5 w-3.5" />
|
||||||
|
Errors: {preview.error_count}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{preview.error_count > 0 && preview.valid_count > 0 && (
|
||||||
|
<label className="inline-flex items-center gap-2 text-xs font-medium text-gray-700 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={skipInvalid}
|
||||||
|
onChange={(e) => setSkipInvalid(e.target.checked)}
|
||||||
|
className="rounded border-gray-300 text-[#1e3a8a] focus:ring-blue-500"
|
||||||
|
/>
|
||||||
|
Skip invalid rows and import valid rows only
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border border-gray-200 rounded-lg overflow-hidden">
|
||||||
|
<div className="max-h-64 overflow-auto">
|
||||||
|
<table className="w-full text-xs">
|
||||||
|
<thead className="bg-gray-50 border-b border-gray-200 sticky top-0">
|
||||||
|
<tr>
|
||||||
|
<th className="px-3 py-2 text-left font-medium text-gray-600">Row</th>
|
||||||
|
{previewColumns.map((col) => (
|
||||||
|
<th key={col.key} className="px-3 py-2 text-left font-medium text-gray-600">
|
||||||
|
{col.label}
|
||||||
|
</th>
|
||||||
|
))}
|
||||||
|
<th className="px-3 py-2 text-left font-medium text-gray-600">Validation</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-100 bg-white">
|
||||||
|
{preview.preview_rows.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td
|
||||||
|
colSpan={previewColumns.length + 2}
|
||||||
|
className="px-3 py-6 text-center text-gray-400"
|
||||||
|
>
|
||||||
|
No data rows found in spreadsheet.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : (
|
||||||
|
preview.preview_rows.map((r) => {
|
||||||
|
const rowRecord = r as unknown as Record<string, unknown>;
|
||||||
|
const rowData = (rowRecord.data as Record<string, unknown> | undefined) || rowRecord;
|
||||||
|
return (
|
||||||
|
<tr
|
||||||
|
key={r.row}
|
||||||
|
className={r.valid ? "bg-white" : "bg-red-50/60"}
|
||||||
|
>
|
||||||
|
<td className="px-3 py-2 font-mono text-gray-500">{r.row}</td>
|
||||||
|
{previewColumns.map((col) => {
|
||||||
|
const val = rowRecord[col.key] ?? rowData[col.key];
|
||||||
|
return (
|
||||||
|
<td key={col.key} className="px-3 py-2 text-gray-800">
|
||||||
|
{val !== null && val !== undefined && val !== ""
|
||||||
|
? String(val)
|
||||||
|
: "—"}
|
||||||
|
</td>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
{r.valid ? (
|
||||||
|
<span className="inline-flex items-center gap-1 text-green-700 font-medium">
|
||||||
|
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||||
|
Ready
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="inline-flex items-start gap-1 text-red-700">
|
||||||
|
<AlertCircle className="h-3.5 w-3.5 shrink-0 mt-0.5" />
|
||||||
|
<span>{r.error || "Invalid row"}</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Footer */}
|
||||||
|
<div className="flex flex-col-reverse sm:flex-row sm:items-center justify-end gap-2 pt-2 border-t border-gray-100">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={importing}
|
||||||
|
onClick={handleClose}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
loading={importing}
|
||||||
|
disabled={!canImport}
|
||||||
|
onClick={handleConfirmImport}
|
||||||
|
>
|
||||||
|
<Upload className="h-4 w-4 mr-1.5" />
|
||||||
|
Import {preview?.valid_count ?? 0} {entityName}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { KeyRound, AlertCircle, Eye, EyeOff } from "lucide-react";
|
||||||
|
import { changePasswordApi } from "@/api/auth";
|
||||||
|
import { ApiError } from "@/api/client";
|
||||||
|
import { Modal } from "@/components/ui/dialog";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { toast } from "@/lib/toast";
|
||||||
|
import { useAuthStore } from "@/hooks/useAuth";
|
||||||
|
|
||||||
|
interface ChangePasswordModalProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps) {
|
||||||
|
const [currentPassword, setCurrentPassword] = useState("");
|
||||||
|
const [newPassword, setNewPassword] = useState("");
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState("");
|
||||||
|
const [showCurrent, setShowCurrent] = useState(false);
|
||||||
|
const [showNew, setShowNew] = useState(false);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||||
|
|
||||||
|
function resetState() {
|
||||||
|
setCurrentPassword("");
|
||||||
|
setNewPassword("");
|
||||||
|
setConfirmPassword("");
|
||||||
|
setShowCurrent(false);
|
||||||
|
setShowNew(false);
|
||||||
|
setErrorMsg(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleClose() {
|
||||||
|
if (loading) return;
|
||||||
|
resetState();
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setErrorMsg(null);
|
||||||
|
|
||||||
|
if (!currentPassword) {
|
||||||
|
setErrorMsg("Please enter your current password.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!newPassword || newPassword.length < 8) {
|
||||||
|
setErrorMsg("New password must be at least 8 characters.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (newPassword !== confirmPassword) {
|
||||||
|
setErrorMsg("New passwords do not match.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const res = await changePasswordApi(currentPassword, newPassword);
|
||||||
|
if (res.access_token) {
|
||||||
|
useAuthStore.getState().setToken(res.access_token);
|
||||||
|
}
|
||||||
|
toast.success(res.message || "Password changed successfully.");
|
||||||
|
handleClose();
|
||||||
|
} catch (err) {
|
||||||
|
const msg =
|
||||||
|
err instanceof ApiError ? err.detail : "Failed to change password.";
|
||||||
|
setErrorMsg(msg);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onOpenChange={(next) => {
|
||||||
|
if (!next) handleClose();
|
||||||
|
}}
|
||||||
|
title="Change Password"
|
||||||
|
description="Update your account login password."
|
||||||
|
className="max-w-md"
|
||||||
|
>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
{errorMsg && (
|
||||||
|
<div
|
||||||
|
role="alert"
|
||||||
|
className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3.5 py-2.5 text-xs text-red-800"
|
||||||
|
>
|
||||||
|
<AlertCircle className="h-4 w-4 text-red-600 shrink-0 mt-0.5" />
|
||||||
|
<span>{errorMsg}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="space-y-1">
|
||||||
|
<label className="text-xs font-medium text-gray-700">
|
||||||
|
Current Password <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<input
|
||||||
|
type={showCurrent ? "text" : "password"}
|
||||||
|
value={currentPassword}
|
||||||
|
onChange={(e) => setCurrentPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
autoComplete="current-password"
|
||||||
|
placeholder="Enter current password"
|
||||||
|
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md pr-10 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowCurrent((s) => !s)}
|
||||||
|
className="absolute right-2.5 top-2.5 text-gray-400 hover:text-gray-600"
|
||||||
|
aria-label={showCurrent ? "Hide current password" : "Show current password"}
|
||||||
|
>
|
||||||
|
{showCurrent ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1">
|
||||||
|
<label className="text-xs font-medium text-gray-700">
|
||||||
|
New Password <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<input
|
||||||
|
type={showNew ? "text" : "password"}
|
||||||
|
value={newPassword}
|
||||||
|
onChange={(e) => setNewPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
minLength={8}
|
||||||
|
autoComplete="new-password"
|
||||||
|
placeholder="At least 8 characters"
|
||||||
|
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md pr-10 focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowNew((s) => !s)}
|
||||||
|
className="absolute right-2.5 top-2.5 text-gray-400 hover:text-gray-600"
|
||||||
|
aria-label={showNew ? "Hide new password" : "Show new password"}
|
||||||
|
>
|
||||||
|
{showNew ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500 mt-1">At least 8 characters, with a letter and a number.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1">
|
||||||
|
<label className="text-xs font-medium text-gray-700">
|
||||||
|
Confirm New Password <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
autoComplete="new-password"
|
||||||
|
placeholder="Re-enter new password"
|
||||||
|
className="w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-end gap-2 pt-3 border-t border-gray-100">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={loading}
|
||||||
|
onClick={handleClose}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" size="sm" loading={loading}>
|
||||||
|
<KeyRound className="h-4 w-4 mr-1.5" />
|
||||||
|
Update Password
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,14 +1,20 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
import { render, screen, fireEvent } from "@testing-library/react";
|
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||||
import { ColumnDef } from "@tanstack/react-table";
|
import { ColumnDef } from "@tanstack/react-table";
|
||||||
import * as XLSX from "xlsx";
|
import XLSX from "xlsx-js-style";
|
||||||
import { DataTable } from "./DataTable";
|
import { DataTable } from "./DataTable";
|
||||||
|
|
||||||
vi.mock("xlsx", async () => {
|
vi.mock("xlsx-js-style", async (importOriginal) => {
|
||||||
const actual = await vi.importActual<typeof import("xlsx")>("xlsx");
|
const actual = await importOriginal<Record<string, unknown>>();
|
||||||
|
const base = ((actual as { default?: Record<string, unknown> }).default ?? actual) as Record<string, unknown>;
|
||||||
|
const writeFileMock = vi.fn();
|
||||||
return {
|
return {
|
||||||
...actual,
|
...base,
|
||||||
writeFile: vi.fn(),
|
writeFile: writeFileMock,
|
||||||
|
default: {
|
||||||
|
...base,
|
||||||
|
writeFile: writeFileMock,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -32,7 +38,7 @@ describe("DataTable", () => {
|
|||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("renders rows, filters globally, and exports visible rows to Excel (.xlsx)", () => {
|
it("renders rows, filters globally, and exports visible rows to Excel (.xlsx)", async () => {
|
||||||
render(
|
render(
|
||||||
<DataTable
|
<DataTable
|
||||||
data={data}
|
data={data}
|
||||||
@@ -56,10 +62,12 @@ describe("DataTable", () => {
|
|||||||
expect(exportBtn).toHaveTextContent("Export Excel (.xlsx)");
|
expect(exportBtn).toHaveTextContent("Export Excel (.xlsx)");
|
||||||
fireEvent.click(exportBtn);
|
fireEvent.click(exportBtn);
|
||||||
|
|
||||||
expect(XLSX.writeFile).toHaveBeenCalledTimes(1);
|
await waitFor(() => {
|
||||||
expect(XLSX.writeFile).toHaveBeenCalledWith(
|
expect(XLSX.writeFile).toHaveBeenCalledTimes(1);
|
||||||
expect.objectContaining({ SheetNames: ["Data"] }),
|
expect(XLSX.writeFile).toHaveBeenCalledWith(
|
||||||
"test-assets.xlsx"
|
expect.objectContaining({ SheetNames: ["Data"] }),
|
||||||
);
|
"test-assets.xlsx"
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import {
|
|||||||
type Table as TanStackTable,
|
type Table as TanStackTable,
|
||||||
} from "@tanstack/react-table";
|
} from "@tanstack/react-table";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import * as XLSX from "xlsx";
|
|
||||||
import {
|
import {
|
||||||
ChevronUp,
|
ChevronUp,
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
@@ -46,7 +45,7 @@ function formatExcelCell(val: unknown): string | number {
|
|||||||
return JSON.stringify(val);
|
return JSON.stringify(val);
|
||||||
}
|
}
|
||||||
|
|
||||||
function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
|
async function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
|
||||||
const rows = table.getPrePaginationRowModel().rows;
|
const rows = table.getPrePaginationRowModel().rows;
|
||||||
if (!rows.length) return;
|
if (!rows.length) return;
|
||||||
|
|
||||||
@@ -55,6 +54,9 @@ function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
|
|||||||
.filter((col) => col.id !== "actions");
|
.filter((col) => col.id !== "actions");
|
||||||
if (!visibleCols.length) return;
|
if (!visibleCols.length) return;
|
||||||
|
|
||||||
|
const XLSXModule = await import("xlsx-js-style");
|
||||||
|
const XLSX = XLSXModule.default ?? XLSXModule;
|
||||||
|
|
||||||
const exportRows = rows.map((row) => {
|
const exportRows = rows.map((row) => {
|
||||||
const record: Record<string, string | number> = {};
|
const record: Record<string, string | number> = {};
|
||||||
for (const col of visibleCols) {
|
for (const col of visibleCols) {
|
||||||
@@ -68,6 +70,105 @@ function exportToExcel<TData>(table: TanStackTable<TData>, filename: string) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const ws = XLSX.utils.json_to_sheet(exportRows);
|
const ws = XLSX.utils.json_to_sheet(exportRows);
|
||||||
|
|
||||||
|
// Apply rich executive styling to table header row (Navy fill, bold white font, borders)
|
||||||
|
for (let c = 0; c < visibleCols.length; c++) {
|
||||||
|
const headerAddr = XLSX.utils.encode_cell({ r: 0, c });
|
||||||
|
if (ws[headerAddr]) {
|
||||||
|
ws[headerAddr].s = {
|
||||||
|
fill: { fgColor: { rgb: "1E3A8A" } }, // Poona Hospital Deep Navy
|
||||||
|
font: { name: "Calibri", sz: 11, bold: true, color: { rgb: "FFFFFF" } },
|
||||||
|
alignment: { horizontal: "center", vertical: "center", wrapText: true },
|
||||||
|
border: {
|
||||||
|
top: { style: "thin", color: { rgb: "334155" } },
|
||||||
|
bottom: { style: "medium", color: { rgb: "0F172A" } },
|
||||||
|
left: { style: "thin", color: { rgb: "334155" } },
|
||||||
|
right: { style: "thin", color: { rgb: "334155" } },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply zebra striping, borders, and column-aware alignment to data rows
|
||||||
|
for (let r = 0; r < rows.length; r++) {
|
||||||
|
const isOdd = r % 2 === 1;
|
||||||
|
for (let c = 0; c < visibleCols.length; c++) {
|
||||||
|
const cellAddr = XLSX.utils.encode_cell({ r: r + 1, c });
|
||||||
|
if (!ws[cellAddr]) continue;
|
||||||
|
|
||||||
|
const col = visibleCols[c];
|
||||||
|
const headerLabel = (typeof col.columnDef.header === "string" ? col.columnDef.header : col.id).toLowerCase();
|
||||||
|
const val = rows[r].getValue(col.id);
|
||||||
|
|
||||||
|
let horizontalAlign: "left" | "center" | "right" = "left";
|
||||||
|
if (
|
||||||
|
typeof val === "number" ||
|
||||||
|
headerLabel.includes("cost") ||
|
||||||
|
headerLabel.includes("value") ||
|
||||||
|
headerLabel.includes("amount") ||
|
||||||
|
headerLabel.includes("price") ||
|
||||||
|
headerLabel.includes("minutes") ||
|
||||||
|
headerLabel.includes("downtime") ||
|
||||||
|
headerLabel.includes("total")
|
||||||
|
) {
|
||||||
|
horizontalAlign = "right";
|
||||||
|
} else if (
|
||||||
|
headerLabel.includes("code") ||
|
||||||
|
headerLabel.includes("date") ||
|
||||||
|
headerLabel.includes("status") ||
|
||||||
|
headerLabel.includes("priority") ||
|
||||||
|
headerLabel.includes("criticality") ||
|
||||||
|
headerLabel.includes("serial") ||
|
||||||
|
headerLabel.includes("mode") ||
|
||||||
|
headerLabel.includes("id") ||
|
||||||
|
typeof val === "boolean"
|
||||||
|
) {
|
||||||
|
horizontalAlign = "center";
|
||||||
|
}
|
||||||
|
|
||||||
|
ws[cellAddr].s = {
|
||||||
|
fill: { fgColor: { rgb: isOdd ? "F8FAFC" : "FFFFFF" } },
|
||||||
|
font: { name: "Calibri", sz: 10, color: { rgb: "0F172A" } },
|
||||||
|
alignment: { horizontal: horizontalAlign, vertical: "center" },
|
||||||
|
border: {
|
||||||
|
top: { style: "thin", color: { rgb: "E2E8F0" } },
|
||||||
|
bottom: { style: "thin", color: { rgb: "E2E8F0" } },
|
||||||
|
left: { style: "thin", color: { rgb: "E2E8F0" } },
|
||||||
|
right: { style: "thin", color: { rgb: "E2E8F0" } },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-fit column widths with generous padding so text/codes are never truncated
|
||||||
|
const colWidths = visibleCols.map((col) => {
|
||||||
|
const headerLabel =
|
||||||
|
typeof col.columnDef.header === "string" ? col.columnDef.header : col.id;
|
||||||
|
let maxLen = headerLabel.length;
|
||||||
|
for (const row of rows) {
|
||||||
|
const cellVal = formatExcelCell(row.getValue(col.id));
|
||||||
|
const strVal = String(cellVal ?? "");
|
||||||
|
if (strVal.length > maxLen) {
|
||||||
|
maxLen = strVal.length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { wch: Math.min(50, Math.max(14, maxLen + 3)) };
|
||||||
|
});
|
||||||
|
ws["!cols"] = colWidths;
|
||||||
|
|
||||||
|
// Add comfortable row heights: header row taller (28pt), data rows spacious (20pt)
|
||||||
|
ws["!rows"] = [
|
||||||
|
{ hpt: 28 },
|
||||||
|
...rows.map(() => ({ hpt: 20 })),
|
||||||
|
];
|
||||||
|
|
||||||
|
// Enable native Excel AutoFilter dropdowns on the header row
|
||||||
|
const lastColLetter = XLSX.utils.encode_col(visibleCols.length - 1);
|
||||||
|
ws["!autofilter"] = { ref: `A1:${lastColLetter}${rows.length + 1}` };
|
||||||
|
|
||||||
|
// Explicitly enable grid lines in Excel view
|
||||||
|
ws["!views"] = [{ showGridLines: true }];
|
||||||
|
|
||||||
const wb = XLSX.utils.book_new();
|
const wb = XLSX.utils.book_new();
|
||||||
XLSX.utils.book_append_sheet(wb, ws, "Data");
|
XLSX.utils.book_append_sheet(wb, ws, "Data");
|
||||||
XLSX.writeFile(wb, `${filename}.xlsx`);
|
XLSX.writeFile(wb, `${filename}.xlsx`);
|
||||||
@@ -120,7 +221,7 @@ export function DataTable<TData>({
|
|||||||
return (
|
return (
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{/* Toolbar */}
|
{/* Toolbar */}
|
||||||
<div className="flex flex-col sm:flex-row sm:items-center gap-2">
|
<div className="no-print flex flex-col sm:flex-row sm:items-center gap-2">
|
||||||
<div className="relative flex-1 min-w-0">
|
<div className="relative flex-1 min-w-0">
|
||||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||||
<input
|
<input
|
||||||
@@ -202,7 +303,7 @@ export function DataTable<TData>({
|
|||||||
value={(header.column.getFilterValue() as string) ?? ""}
|
value={(header.column.getFilterValue() as string) ?? ""}
|
||||||
onChange={(e) => header.column.setFilterValue(e.target.value)}
|
onChange={(e) => header.column.setFilterValue(e.target.value)}
|
||||||
placeholder="Filter..."
|
placeholder="Filter..."
|
||||||
className="w-full px-2 py-0.5 text-xs border border-gray-200 rounded focus:outline-none focus:ring-1 focus:ring-blue-400"
|
className="no-print w-full px-2 py-0.5 text-xs border border-gray-200 rounded focus:outline-none focus:ring-1 focus:ring-blue-400"
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -258,7 +359,7 @@ export function DataTable<TData>({
|
|||||||
|
|
||||||
{/* Pagination */}
|
{/* Pagination */}
|
||||||
{!loading && visibleRows.length > 0 && (
|
{!loading && visibleRows.length > 0 && (
|
||||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 px-3 sm:px-4 py-3 border-t border-gray-200 bg-gray-50 text-sm text-gray-600">
|
<div className="no-print flex flex-col sm:flex-row items-start sm:items-center justify-between gap-2 px-3 sm:px-4 py-3 border-t border-gray-200 bg-gray-50 text-sm text-gray-600">
|
||||||
<span>
|
<span>
|
||||||
{filteredRows.length} record{filteredRows.length !== 1 ? "s" : ""}
|
{filteredRows.length} record{filteredRows.length !== 1 ? "s" : ""}
|
||||||
{globalFilter || columnFilters.length ? " (filtered)" : ""}
|
{globalFilter || columnFilters.length ? " (filtered)" : ""}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { ApiError } from "@/api/client";
|
|||||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||||
import { vendorsApi } from "@/api/masters";
|
import { vendorsApi } from "@/api/masters";
|
||||||
import { pmApi, type ServiceMode } from "@/api/pm";
|
import { pmApi, type ServiceMode } from "@/api/pm";
|
||||||
|
import { attachmentsApi } from "@/api/attachments";
|
||||||
|
|
||||||
const inputCls =
|
const inputCls =
|
||||||
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500";
|
||||||
@@ -250,6 +251,7 @@ export function CompletePMModal({
|
|||||||
const [completedDate, setCompletedDate] = useState("");
|
const [completedDate, setCompletedDate] = useState("");
|
||||||
const [serviceDetails, setServiceDetails] = useState("");
|
const [serviceDetails, setServiceDetails] = useState("");
|
||||||
const [remarks, setRemarks] = useState("");
|
const [remarks, setRemarks] = useState("");
|
||||||
|
const [reportFile, setReportFile] = useState<File | null>(null);
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
@@ -258,6 +260,7 @@ export function CompletePMModal({
|
|||||||
setCompletedDate(new Date().toISOString().slice(0, 10));
|
setCompletedDate(new Date().toISOString().slice(0, 10));
|
||||||
setServiceDetails("");
|
setServiceDetails("");
|
||||||
setRemarks("");
|
setRemarks("");
|
||||||
|
setReportFile(null);
|
||||||
setError(null);
|
setError(null);
|
||||||
}, [open, recordId]);
|
}, [open, recordId]);
|
||||||
|
|
||||||
@@ -272,8 +275,12 @@ export function CompletePMModal({
|
|||||||
service_details: serviceDetails.trim(),
|
service_details: serviceDetails.trim(),
|
||||||
remarks: remarks.trim() || null,
|
remarks: remarks.trim() || null,
|
||||||
});
|
});
|
||||||
|
if (reportFile) {
|
||||||
|
await attachmentsApi.upload("pm_record", recordId, reportFile);
|
||||||
|
}
|
||||||
await qc.invalidateQueries({ queryKey: ["pm-records"] });
|
await qc.invalidateQueries({ queryKey: ["pm-records"] });
|
||||||
await qc.invalidateQueries({ queryKey: ["pm-schedules"] });
|
await qc.invalidateQueries({ queryKey: ["pm-schedules"] });
|
||||||
|
await qc.invalidateQueries({ queryKey: ["attachments", "pm_record", recordId] });
|
||||||
if (assetId) await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
|
if (assetId) await qc.invalidateQueries({ queryKey: ["asset-overview", assetId] });
|
||||||
onClose();
|
onClose();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -317,6 +324,15 @@ export function CompletePMModal({
|
|||||||
className={inputCls}
|
className={inputCls}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Service Report / Checklist (optional)</label>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
accept=".pdf,.png,.jpg,.jpeg,.doc,.docx"
|
||||||
|
onChange={(e) => setReportFile(e.target.files?.[0] ?? null)}
|
||||||
|
className="w-full text-xs text-gray-700 file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:text-xs file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 border border-gray-200 rounded-md p-1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<div className="flex justify-end gap-2 pt-2">
|
<div className="flex justify-end gap-2 pt-2">
|
||||||
<Button type="button" variant="outline" onClick={onClose}>
|
<Button type="button" variant="outline" onClick={onClose}>
|
||||||
Cancel
|
Cancel
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import {
|
|||||||
X,
|
X,
|
||||||
Package,
|
Package,
|
||||||
AlertCircle,
|
AlertCircle,
|
||||||
|
KeyRound,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { formatDate, formatRelative } from "@/lib/format";
|
import { formatDate, formatRelative } from "@/lib/format";
|
||||||
@@ -28,6 +29,7 @@ import { notificationsApi, type NotificationItem } from "@/api/notifications";
|
|||||||
import { searchApi } from "@/api/search";
|
import { searchApi } from "@/api/search";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { AssetStatusBadge, CallStatusBadge } from "@/components/StatusBadge";
|
import { AssetStatusBadge, CallStatusBadge } from "@/components/StatusBadge";
|
||||||
|
import { ChangePasswordModal } from "@/components/ChangePasswordModal";
|
||||||
import { toast } from "@/lib/toast";
|
import { toast } from "@/lib/toast";
|
||||||
|
|
||||||
interface TopBarProps {
|
interface TopBarProps {
|
||||||
@@ -41,6 +43,7 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
|||||||
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
|
const { user, demoAsOfDate, setDemoAsOfDate, logout } = useAuthStore();
|
||||||
|
|
||||||
const [menuOpen, setMenuOpen] = useState(false);
|
const [menuOpen, setMenuOpen] = useState(false);
|
||||||
|
const [changePasswordOpen, setChangePasswordOpen] = useState(false);
|
||||||
const [bellOpen, setBellOpen] = useState(false);
|
const [bellOpen, setBellOpen] = useState(false);
|
||||||
const [dateInput, setDateInput] = useState(demoAsOfDate ?? "");
|
const [dateInput, setDateInput] = useState(demoAsOfDate ?? "");
|
||||||
const [savingDate, setSavingDate] = useState(false);
|
const [savingDate, setSavingDate] = useState(false);
|
||||||
@@ -233,6 +236,7 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-3 sm:px-4 py-2 gap-2 sm:gap-3 sticky top-0 z-10">
|
<header className="min-h-14 bg-white border-b border-gray-200 flex items-center flex-wrap px-3 sm:px-4 py-2 gap-2 sm:gap-3 sticky top-0 z-10">
|
||||||
{/* Mobile/tablet nav toggle */}
|
{/* Mobile/tablet nav toggle */}
|
||||||
{onMenuClick && (
|
{onMenuClick && (
|
||||||
@@ -598,6 +602,17 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setMenuOpen(false);
|
||||||
|
setChangePasswordOpen(true);
|
||||||
|
}}
|
||||||
|
className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 text-left"
|
||||||
|
>
|
||||||
|
<KeyRound className="h-4 w-4 text-gray-500" />
|
||||||
|
Change Password
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={handleSignOut}
|
onClick={handleSignOut}
|
||||||
@@ -611,6 +626,11 @@ export function TopBar({ title, onMenuClick }: TopBarProps) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
<ChangePasswordModal
|
||||||
|
open={changePasswordOpen}
|
||||||
|
onClose={() => setChangePasswordOpen(false)}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ interface AuthState {
|
|||||||
demoAsOfDate: string | null;
|
demoAsOfDate: string | null;
|
||||||
hydrating: boolean;
|
hydrating: boolean;
|
||||||
setAuth: (user: UserOut, token: string) => void;
|
setAuth: (user: UserOut, token: string) => void;
|
||||||
|
setToken: (token: string) => void;
|
||||||
setDemoAsOfDate: (date: string | null) => void;
|
setDemoAsOfDate: (date: string | null) => void;
|
||||||
hydrate: () => Promise<void>;
|
hydrate: () => Promise<void>;
|
||||||
logout: () => void;
|
logout: () => void;
|
||||||
@@ -31,6 +32,11 @@ export const useAuthStore = create<AuthState>((set, get) => ({
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
setToken: (token) => {
|
||||||
|
sessionStorage.setItem("access_token", token);
|
||||||
|
set({ token });
|
||||||
|
},
|
||||||
|
|
||||||
setDemoAsOfDate: (date) => {
|
setDemoAsOfDate: (date) => {
|
||||||
set((state) => ({
|
set((state) => ({
|
||||||
demoAsOfDate: date || null,
|
demoAsOfDate: date || null,
|
||||||
|
|||||||
+73
-9
@@ -11,43 +11,107 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@media screen {
|
||||||
|
.print-only {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@media print {
|
@media print {
|
||||||
@page {
|
@page {
|
||||||
size: A4 landscape;
|
size: A4 landscape;
|
||||||
margin: 12mm;
|
margin: 8mm 10mm;
|
||||||
}
|
}
|
||||||
|
|
||||||
aside,
|
aside,
|
||||||
header,
|
header,
|
||||||
|
nav,
|
||||||
.no-print {
|
.no-print {
|
||||||
display: none !important;
|
display: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.print-only {
|
||||||
|
display: block !important;
|
||||||
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
background: #ffffff !important;
|
background: #ffffff !important;
|
||||||
color: #111827 !important;
|
color: #0f172a !important;
|
||||||
-webkit-print-color-adjust: exact;
|
-webkit-print-color-adjust: exact !important;
|
||||||
print-color-adjust: exact;
|
print-color-adjust: exact !important;
|
||||||
|
font-size: 10px !important;
|
||||||
|
line-height: 1.35 !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
main {
|
main {
|
||||||
padding: 0 !important;
|
padding: 0 !important;
|
||||||
|
margin: 0 !important;
|
||||||
overflow: visible !important;
|
overflow: visible !important;
|
||||||
|
max-width: 100% !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Prevent elements from breaking across PDF pages */
|
||||||
|
.print-break-inside-avoid {
|
||||||
|
break-inside: avoid !important;
|
||||||
|
page-break-inside: avoid !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.print-break-before {
|
||||||
|
break-before: page !important;
|
||||||
|
page-break-before: always !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Clean up card shadows and borders for crisp PDF generation */
|
||||||
|
.shadow-sm,
|
||||||
|
.shadow,
|
||||||
|
.shadow-md,
|
||||||
|
.shadow-lg {
|
||||||
|
box-shadow: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* High-fidelity PDF Table Styling */
|
||||||
table {
|
table {
|
||||||
border-collapse: collapse !important;
|
border-collapse: collapse !important;
|
||||||
width: 100% !important;
|
width: 100% !important;
|
||||||
|
page-break-inside: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
thead {
|
||||||
|
display: table-header-group !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
tfoot {
|
||||||
|
display: table-footer-group !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
tr {
|
||||||
|
page-break-inside: avoid !important;
|
||||||
|
break-inside: avoid !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
th {
|
||||||
|
background-color: #1e3a8a !important;
|
||||||
|
color: #ffffff !important;
|
||||||
|
font-weight: 600 !important;
|
||||||
|
font-size: 9.5px !important;
|
||||||
|
padding: 5px 6px !important;
|
||||||
|
border: 1px solid #1e293b !important;
|
||||||
|
text-align: center !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
th,
|
|
||||||
td {
|
td {
|
||||||
border: 1px solid #d1d5db !important;
|
border: 1px solid #cbd5e1 !important;
|
||||||
font-size: 10px !important;
|
font-size: 9px !important;
|
||||||
padding: 4px 6px !important;
|
padding: 4px 6px !important;
|
||||||
|
color: #0f172a !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.print-break-inside-avoid {
|
tbody tr:nth-child(even) td {
|
||||||
break-inside: avoid;
|
background-color: #f8fafc !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Force chart svg visibility */
|
||||||
|
.recharts-wrapper {
|
||||||
|
margin: 0 auto !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,8 @@ export function AssetsPage() {
|
|||||||
|
|
||||||
const [selectedDeptId, setSelectedDeptId] = useState<number | undefined>(undefined);
|
const [selectedDeptId, setSelectedDeptId] = useState<number | undefined>(undefined);
|
||||||
const [selectedStatus, setSelectedStatus] = useState<AssetStatus | "">("");
|
const [selectedStatus, setSelectedStatus] = useState<AssetStatus | "">("");
|
||||||
|
const [calibrationFilter, setCalibrationFilter] = useState<"all" | "required" | "not_required">("all");
|
||||||
|
const [insuranceFilter, setInsuranceFilter] = useState<"all" | "insured" | "uninsured">("all");
|
||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
const [bulkOpen, setBulkOpen] = useState(false);
|
const [bulkOpen, setBulkOpen] = useState(false);
|
||||||
|
|
||||||
@@ -44,11 +46,29 @@ export function AssetsPage() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const assetsQuery = useQuery({
|
const assetsQuery = useQuery({
|
||||||
queryKey: ["assets", selectedDeptId ?? "all", selectedStatus || "all"],
|
queryKey: [
|
||||||
|
"assets",
|
||||||
|
selectedDeptId ?? "all",
|
||||||
|
selectedStatus || "all",
|
||||||
|
calibrationFilter,
|
||||||
|
insuranceFilter,
|
||||||
|
],
|
||||||
queryFn: () =>
|
queryFn: () =>
|
||||||
assetsApi.list({
|
assetsApi.list({
|
||||||
department_id: isDeptUser ? undefined : selectedDeptId,
|
department_id: isDeptUser ? undefined : selectedDeptId,
|
||||||
status: selectedStatus || undefined,
|
status: selectedStatus || undefined,
|
||||||
|
requires_calibration:
|
||||||
|
calibrationFilter === "required"
|
||||||
|
? true
|
||||||
|
: calibrationFilter === "not_required"
|
||||||
|
? false
|
||||||
|
: undefined,
|
||||||
|
insurance_applicable:
|
||||||
|
insuranceFilter === "insured"
|
||||||
|
? true
|
||||||
|
: insuranceFilter === "uninsured"
|
||||||
|
? false
|
||||||
|
: undefined,
|
||||||
page_size: 200,
|
page_size: 200,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -208,6 +228,48 @@ export function AssetsPage() {
|
|||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1.5 flex-wrap">
|
||||||
|
<span className="text-xs font-medium text-gray-500 mr-1">Calibration:</span>
|
||||||
|
{[
|
||||||
|
{ value: "all", label: "All" },
|
||||||
|
{ value: "required", label: "Calibration Required" },
|
||||||
|
{ value: "not_required", label: "Not Required" },
|
||||||
|
].map((chip) => (
|
||||||
|
<button
|
||||||
|
key={chip.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setCalibrationFilter(chip.value as typeof calibrationFilter)}
|
||||||
|
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||||
|
calibrationFilter === chip.value
|
||||||
|
? "bg-emerald-700 text-white"
|
||||||
|
: "bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{chip.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<span className="text-xs font-medium text-gray-500 ml-3 mr-1">Insurance:</span>
|
||||||
|
{[
|
||||||
|
{ value: "all", label: "All" },
|
||||||
|
{ value: "insured", label: "Insurance Applicable" },
|
||||||
|
{ value: "uninsured", label: "Not Applicable" },
|
||||||
|
].map((chip) => (
|
||||||
|
<button
|
||||||
|
key={chip.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setInsuranceFilter(chip.value as typeof insuranceFilter)}
|
||||||
|
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||||
|
insuranceFilter === chip.value
|
||||||
|
? "bg-purple-700 text-white"
|
||||||
|
: "bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{chip.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<DataTable
|
<DataTable
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useState } from "react";
|
|||||||
import { Link } from "react-router-dom";
|
import { Link } from "react-router-dom";
|
||||||
import { useQuery } from "@tanstack/react-query";
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import type { ColumnDef } from "@tanstack/react-table";
|
import type { ColumnDef } from "@tanstack/react-table";
|
||||||
import { Plus, CheckCircle2, Paperclip, ShieldCheck, Search } from "lucide-react";
|
import { Plus, CheckCircle2, Paperclip, ShieldCheck, Search, Download, Upload } from "lucide-react";
|
||||||
import {
|
import {
|
||||||
calibrationApi,
|
calibrationApi,
|
||||||
type CalibrationRecordItem,
|
type CalibrationRecordItem,
|
||||||
@@ -22,6 +22,8 @@ import {
|
|||||||
ApproveCalibrationPlanModal,
|
ApproveCalibrationPlanModal,
|
||||||
CompleteCalibrationModal,
|
CompleteCalibrationModal,
|
||||||
} from "@/components/CalibrationModals";
|
} from "@/components/CalibrationModals";
|
||||||
|
import { BulkGenericImportModal } from "@/components/BulkGenericImportModal";
|
||||||
|
import { toast } from "@/lib/toast";
|
||||||
|
|
||||||
type CalTab = "records" | "plans";
|
type CalTab = "records" | "plans";
|
||||||
|
|
||||||
@@ -49,6 +51,7 @@ export function CalibrationPage() {
|
|||||||
const [dueTo, setDueTo] = useState("");
|
const [dueTo, setDueTo] = useState("");
|
||||||
|
|
||||||
const [bulkAddOpen, setBulkAddOpen] = useState(false);
|
const [bulkAddOpen, setBulkAddOpen] = useState(false);
|
||||||
|
const [importModalOpen, setImportModalOpen] = useState(false);
|
||||||
const [approvingPlan, setApprovingPlan] = useState<CalibrationPlanItem | null>(null);
|
const [approvingPlan, setApprovingPlan] = useState<CalibrationPlanItem | null>(null);
|
||||||
const [completingRec, setCompletingRec] = useState<CalibrationRecordItem | null>(null);
|
const [completingRec, setCompletingRec] = useState<CalibrationRecordItem | null>(null);
|
||||||
const [certModalRec, setCertModalRec] = useState<CalibrationRecordItem | null>(null);
|
const [certModalRec, setCertModalRec] = useState<CalibrationRecordItem | null>(null);
|
||||||
@@ -298,10 +301,33 @@ export function CalibrationPage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{canAddCalPlan && (
|
{canAddCalPlan && (
|
||||||
<Button onClick={() => setBulkAddOpen(true)}>
|
<div className="flex items-center gap-2">
|
||||||
<Plus className="h-4 w-4 mr-1.5" />
|
<Button
|
||||||
Add Equipment to Calibration
|
variant="outline"
|
||||||
</Button>
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
await calibrationApi.downloadImportTemplate();
|
||||||
|
toast.success("Downloaded Calibration import template (.xlsx)");
|
||||||
|
} catch {
|
||||||
|
toast.error("Failed to download template");
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Download className="h-4 w-4 mr-1.5" />
|
||||||
|
Template (.xlsx)
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setImportModalOpen(true)}
|
||||||
|
>
|
||||||
|
<Upload className="h-4 w-4 mr-1.5" />
|
||||||
|
Import (.xlsx)
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => setBulkAddOpen(true)}>
|
||||||
|
<Plus className="h-4 w-4 mr-1.5" />
|
||||||
|
Add Equipment to Calibration
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -481,6 +507,24 @@ export function CalibrationPage() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
|
<BulkGenericImportModal
|
||||||
|
open={importModalOpen}
|
||||||
|
onClose={() => setImportModalOpen(false)}
|
||||||
|
title="Bulk Import Calibration Plans"
|
||||||
|
description="Upload an Excel (.xlsx/.xls) or CSV spreadsheet to register multiple equipment calibration frequencies and agency assignments at once."
|
||||||
|
entityName="Calibration Plans"
|
||||||
|
templateFilename="calibration_import_template.xlsx"
|
||||||
|
onDownloadTemplate={() => calibrationApi.downloadImportTemplate()}
|
||||||
|
onImport={(file, dryRun, skipInvalid) => calibrationApi.bulkImport(file, dryRun, skipInvalid)}
|
||||||
|
queryKeysToInvalidate={[["calibration-plans"], ["calibration-records"], ["dashboard"]]}
|
||||||
|
previewColumns={[
|
||||||
|
{ key: "asset_code", label: "Asset Code" },
|
||||||
|
{ key: "frequency_months", label: "Frequency (Mo)" },
|
||||||
|
{ key: "agency_name", label: "Agency" },
|
||||||
|
{ key: "next_due_date", label: "Next Due Date" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ export function ComplaintDetailPage() {
|
|||||||
// Modals
|
// Modals
|
||||||
const [assignOpen, setAssignOpen] = useState(false);
|
const [assignOpen, setAssignOpen] = useState(false);
|
||||||
const [assignUserId, setAssignUserId] = useState<string>("");
|
const [assignUserId, setAssignUserId] = useState<string>("");
|
||||||
|
const [assignTeam, setAssignTeam] = useState<string>("");
|
||||||
const [assignNote, setAssignNote] = useState("");
|
const [assignNote, setAssignNote] = useState("");
|
||||||
|
|
||||||
const [closeOpen, setCloseOpen] = useState(false);
|
const [closeOpen, setCloseOpen] = useState(false);
|
||||||
@@ -173,12 +174,14 @@ export function ComplaintDetailPage() {
|
|||||||
const assignMutation = useMutation({
|
const assignMutation = useMutation({
|
||||||
mutationFn: () =>
|
mutationFn: () =>
|
||||||
complaintsApi.assign(complaintId, {
|
complaintsApi.assign(complaintId, {
|
||||||
assigned_to_id: Number(assignUserId),
|
assigned_to_id: assignUserId ? Number(assignUserId) : undefined,
|
||||||
|
assigned_team: assignTeam.trim() || undefined,
|
||||||
note: assignNote.trim() || undefined,
|
note: assignNote.trim() || undefined,
|
||||||
}),
|
}),
|
||||||
onSuccess: async () => {
|
onSuccess: async () => {
|
||||||
setActionError(null);
|
setActionError(null);
|
||||||
setAssignOpen(false);
|
setAssignOpen(false);
|
||||||
|
setAssignTeam("");
|
||||||
setAssignNote("");
|
setAssignNote("");
|
||||||
await refreshAll();
|
await refreshAll();
|
||||||
},
|
},
|
||||||
@@ -432,7 +435,9 @@ export function ComplaintDetailPage() {
|
|||||||
label="Assigned"
|
label="Assigned"
|
||||||
value={
|
value={
|
||||||
c.assigned_to_name
|
c.assigned_to_name
|
||||||
? `${c.assigned_to_name} (${formatDateTime(c.assigned_at)})`
|
? `${c.assigned_to_name}${c.assigned_team ? ` (${c.assigned_team})` : ""} (${formatDateTime(c.assigned_at)})`
|
||||||
|
: c.assigned_team
|
||||||
|
? `Team: ${c.assigned_team} (${formatDateTime(c.assigned_at)})`
|
||||||
: "Unassigned"
|
: "Unassigned"
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -523,6 +528,7 @@ export function ComplaintDetailPage() {
|
|||||||
? String(techUsers[0].id)
|
? String(techUsers[0].id)
|
||||||
: ""
|
: ""
|
||||||
);
|
);
|
||||||
|
setAssignTeam(c.assigned_team ?? "");
|
||||||
setAssignOpen(true);
|
setAssignOpen(true);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -878,6 +884,16 @@ export function ComplaintDetailPage() {
|
|||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Assigned Team (optional)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="e.g. Biomedical Bio-Eng Team A, Philips CE"
|
||||||
|
value={assignTeam}
|
||||||
|
onChange={(e) => setAssignTeam(e.target.value)}
|
||||||
|
className={inputCls}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className={labelCls}>Note (optional)</label>
|
<label className={labelCls}>Note (optional)</label>
|
||||||
<textarea
|
<textarea
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
type CallStatus,
|
type CallStatus,
|
||||||
} from "@/api/complaints";
|
} from "@/api/complaints";
|
||||||
import type { AssetCriticality } from "@/api/assets";
|
import type { AssetCriticality } from "@/api/assets";
|
||||||
import { departmentsApi, fetchUsersLookup } from "@/api/masters";
|
import { departmentsApi, locationsApi, fetchUsersLookup } from "@/api/masters";
|
||||||
import { useAuthStore } from "@/hooks/useAuth";
|
import { useAuthStore } from "@/hooks/useAuth";
|
||||||
import { can } from "@/lib/permissions";
|
import { can } from "@/lib/permissions";
|
||||||
import { formatDateTime, formatDuration } from "@/lib/format";
|
import { formatDateTime, formatDuration } from "@/lib/format";
|
||||||
@@ -35,6 +35,7 @@ export function ComplaintsPage() {
|
|||||||
|
|
||||||
const [q, setQ] = useState("");
|
const [q, setQ] = useState("");
|
||||||
const [departmentId, setDepartmentId] = useState<string>("");
|
const [departmentId, setDepartmentId] = useState<string>("");
|
||||||
|
const [locationId, setLocationId] = useState<string>("");
|
||||||
const [callStatus, setCallStatus] = useState<CallStatus | "">("");
|
const [callStatus, setCallStatus] = useState<CallStatus | "">("");
|
||||||
const [priority, setPriority] = useState<AssetCriticality | "">("");
|
const [priority, setPriority] = useState<AssetCriticality | "">("");
|
||||||
const [assignedToId, setAssignedToId] = useState<string>("");
|
const [assignedToId, setAssignedToId] = useState<string>("");
|
||||||
@@ -49,6 +50,11 @@ export function ComplaintsPage() {
|
|||||||
enabled: !isDeptUser,
|
enabled: !isDeptUser,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const locationsQuery = useQuery({
|
||||||
|
queryKey: ["locations", "active-only"],
|
||||||
|
queryFn: () => locationsApi.list(false),
|
||||||
|
});
|
||||||
|
|
||||||
const usersQuery = useQuery({
|
const usersQuery = useQuery({
|
||||||
queryKey: ["users-lookup"],
|
queryKey: ["users-lookup"],
|
||||||
queryFn: fetchUsersLookup,
|
queryFn: fetchUsersLookup,
|
||||||
@@ -59,6 +65,7 @@ export function ComplaintsPage() {
|
|||||||
"complaints",
|
"complaints",
|
||||||
q,
|
q,
|
||||||
departmentId,
|
departmentId,
|
||||||
|
locationId,
|
||||||
callStatus,
|
callStatus,
|
||||||
priority,
|
priority,
|
||||||
assignedToId,
|
assignedToId,
|
||||||
@@ -70,6 +77,7 @@ export function ComplaintsPage() {
|
|||||||
complaintsApi.list({
|
complaintsApi.list({
|
||||||
q: q.trim() || undefined,
|
q: q.trim() || undefined,
|
||||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||||
|
location_id: locationId ? Number(locationId) : undefined,
|
||||||
call_status: callStatus || undefined,
|
call_status: callStatus || undefined,
|
||||||
priority: priority || undefined,
|
priority: priority || undefined,
|
||||||
assigned_to_id: assignedToId ? Number(assignedToId) : undefined,
|
assigned_to_id: assignedToId ? Number(assignedToId) : undefined,
|
||||||
@@ -177,6 +185,10 @@ export function ComplaintsPage() {
|
|||||||
];
|
];
|
||||||
|
|
||||||
const departments = deptsQuery.data?.items ?? [];
|
const departments = deptsQuery.data?.items ?? [];
|
||||||
|
const allLocations = locationsQuery.data?.items ?? [];
|
||||||
|
const filteredLocations = departmentId
|
||||||
|
? allLocations.filter((l) => l.department_id === Number(departmentId))
|
||||||
|
: allLocations;
|
||||||
const techUsers = (usersQuery.data?.items ?? []).filter(
|
const techUsers = (usersQuery.data?.items ?? []).filter(
|
||||||
(u) => u.role === "biomedical" || u.role === "system_admin"
|
(u) => u.role === "biomedical" || u.role === "system_admin"
|
||||||
);
|
);
|
||||||
@@ -235,7 +247,10 @@ export function ComplaintsPage() {
|
|||||||
{!isDeptUser && (
|
{!isDeptUser && (
|
||||||
<select
|
<select
|
||||||
value={departmentId}
|
value={departmentId}
|
||||||
onChange={(e) => setDepartmentId(e.target.value)}
|
onChange={(e) => {
|
||||||
|
setDepartmentId(e.target.value);
|
||||||
|
setLocationId("");
|
||||||
|
}}
|
||||||
aria-label="Filter by Department"
|
aria-label="Filter by Department"
|
||||||
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||||
>
|
>
|
||||||
@@ -248,6 +263,20 @@ export function ComplaintsPage() {
|
|||||||
</select>
|
</select>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<select
|
||||||
|
value={locationId}
|
||||||
|
onChange={(e) => setLocationId(e.target.value)}
|
||||||
|
aria-label="Filter by Location"
|
||||||
|
className="px-2.5 py-1.5 text-xs border border-gray-200 rounded-md bg-white"
|
||||||
|
>
|
||||||
|
<option value="">All Locations</option>
|
||||||
|
{filteredLocations.map((loc) => (
|
||||||
|
<option key={loc.id} value={String(loc.id)}>
|
||||||
|
{loc.name} {loc.floor_wing ? `(${loc.floor_wing})` : ""}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
|
||||||
<select
|
<select
|
||||||
value={priority}
|
value={priority}
|
||||||
onChange={(e) => setPriority(e.target.value as AssetCriticality | "")}
|
onChange={(e) => setPriority(e.target.value as AssetCriticality | "")}
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import {
|
|||||||
Trash2,
|
Trash2,
|
||||||
Search,
|
Search,
|
||||||
AlertCircle,
|
AlertCircle,
|
||||||
|
Download,
|
||||||
|
Upload,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import {
|
import {
|
||||||
contractsApi,
|
contractsApi,
|
||||||
@@ -32,6 +34,7 @@ import { ExpiryChip } from "@/components/StatusBadge";
|
|||||||
import { AssetPicker } from "@/components/AssetPicker";
|
import { AssetPicker } from "@/components/AssetPicker";
|
||||||
import { Attachments } from "@/components/Attachments";
|
import { Attachments } from "@/components/Attachments";
|
||||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||||
|
import { BulkGenericImportModal } from "@/components/BulkGenericImportModal";
|
||||||
import { toast } from "@/lib/toast";
|
import { toast } from "@/lib/toast";
|
||||||
|
|
||||||
type TabKey = "contracts" | "warranties";
|
type TabKey = "contracts" | "warranties";
|
||||||
@@ -82,6 +85,9 @@ export function ContractsPage() {
|
|||||||
const [departmentId, setDepartmentId] = useState("");
|
const [departmentId, setDepartmentId] = useState("");
|
||||||
const [providerId, setProviderId] = useState("");
|
const [providerId, setProviderId] = useState("");
|
||||||
const [contractTypeFilter, setContractTypeFilter] = useState("");
|
const [contractTypeFilter, setContractTypeFilter] = useState("");
|
||||||
|
const [expiryFrom, setExpiryFrom] = useState("");
|
||||||
|
const [expiryTo, setExpiryTo] = useState("");
|
||||||
|
const [importModalOpen, setImportModalOpen] = useState(false);
|
||||||
|
|
||||||
// Contract modals
|
// Contract modals
|
||||||
const [contractFormOpen, setContractFormOpen] = useState(false);
|
const [contractFormOpen, setContractFormOpen] = useState(false);
|
||||||
@@ -130,6 +136,8 @@ export function ContractsPage() {
|
|||||||
contractTypeFilter,
|
contractTypeFilter,
|
||||||
statusFilter,
|
statusFilter,
|
||||||
includeSuperseded,
|
includeSuperseded,
|
||||||
|
expiryFrom,
|
||||||
|
expiryTo,
|
||||||
],
|
],
|
||||||
queryFn: () =>
|
queryFn: () =>
|
||||||
contractsApi.list({
|
contractsApi.list({
|
||||||
@@ -139,18 +147,22 @@ export function ContractsPage() {
|
|||||||
contract_type: contractTypeFilter || undefined,
|
contract_type: contractTypeFilter || undefined,
|
||||||
status: statusFilter || undefined,
|
status: statusFilter || undefined,
|
||||||
include_superseded: includeSuperseded,
|
include_superseded: includeSuperseded,
|
||||||
|
expiry_from: expiryFrom || undefined,
|
||||||
|
expiry_to: expiryTo || undefined,
|
||||||
page_size: 200,
|
page_size: 200,
|
||||||
}),
|
}),
|
||||||
enabled: tab === "contracts",
|
enabled: tab === "contracts",
|
||||||
});
|
});
|
||||||
|
|
||||||
const warrantiesQuery = useQuery({
|
const warrantiesQuery = useQuery({
|
||||||
queryKey: ["warranties", q, departmentId, statusFilter],
|
queryKey: ["warranties", q, departmentId, statusFilter, expiryFrom, expiryTo],
|
||||||
queryFn: () =>
|
queryFn: () =>
|
||||||
warrantiesApi.list({
|
warrantiesApi.list({
|
||||||
q: q.trim() || undefined,
|
q: q.trim() || undefined,
|
||||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||||
status: statusFilter || undefined,
|
status: statusFilter || undefined,
|
||||||
|
expiry_from: expiryFrom || undefined,
|
||||||
|
expiry_to: expiryTo || undefined,
|
||||||
page_size: 200,
|
page_size: 200,
|
||||||
}),
|
}),
|
||||||
enabled: tab === "warranties",
|
enabled: tab === "warranties",
|
||||||
@@ -469,20 +481,47 @@ export function ContractsPage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{canManage && (
|
{canManage && (
|
||||||
<Button
|
<div className="flex items-center gap-2">
|
||||||
onClick={() => {
|
{tab === "contracts" && (
|
||||||
if (tab === "contracts") {
|
<>
|
||||||
setEditingContract(null);
|
<Button
|
||||||
setContractFormOpen(true);
|
variant="outline"
|
||||||
} else {
|
onClick={async () => {
|
||||||
setEditingWarranty(null);
|
try {
|
||||||
setWarrantyFormOpen(true);
|
await contractsApi.downloadImportTemplate();
|
||||||
}
|
toast.success("Downloaded Contract import template (.xlsx)");
|
||||||
}}
|
} catch {
|
||||||
>
|
toast.error("Failed to download template");
|
||||||
<Plus className="h-4 w-4 mr-1.5" />
|
}
|
||||||
{tab === "contracts" ? "Add Contract" : "Add Warranty"}
|
}}
|
||||||
</Button>
|
>
|
||||||
|
<Download className="h-4 w-4 mr-1.5" />
|
||||||
|
Template (.xlsx)
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setImportModalOpen(true)}
|
||||||
|
>
|
||||||
|
<Upload className="h-4 w-4 mr-1.5" />
|
||||||
|
Import (.xlsx)
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
if (tab === "contracts") {
|
||||||
|
setEditingContract(null);
|
||||||
|
setContractFormOpen(true);
|
||||||
|
} else {
|
||||||
|
setEditingWarranty(null);
|
||||||
|
setWarrantyFormOpen(true);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4 mr-1.5" />
|
||||||
|
{tab === "contracts" ? "Add Contract" : "Add Warranty"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -606,6 +645,39 @@ export function ContractsPage() {
|
|||||||
</select>
|
</select>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<span className="text-[11px] text-gray-500 whitespace-nowrap">Expiry:</span>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={expiryFrom}
|
||||||
|
onChange={(e) => setExpiryFrom(e.target.value)}
|
||||||
|
title="Expiry From"
|
||||||
|
placeholder="From"
|
||||||
|
className="w-full px-2 py-1 text-xs border border-gray-200 rounded-md bg-white"
|
||||||
|
/>
|
||||||
|
<span className="text-[11px] text-gray-400">to</span>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={expiryTo}
|
||||||
|
onChange={(e) => setExpiryTo(e.target.value)}
|
||||||
|
title="Expiry To"
|
||||||
|
placeholder="To"
|
||||||
|
className="w-full px-2 py-1 text-xs border border-gray-200 rounded-md bg-white"
|
||||||
|
/>
|
||||||
|
{(expiryFrom || expiryTo) && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setExpiryFrom("");
|
||||||
|
setExpiryTo("");
|
||||||
|
}}
|
||||||
|
className="text-[11px] text-[#1e3a8a] hover:underline whitespace-nowrap"
|
||||||
|
>
|
||||||
|
Clear
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -699,6 +771,25 @@ export function ContractsPage() {
|
|||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<BulkGenericImportModal
|
||||||
|
open={importModalOpen}
|
||||||
|
onClose={() => setImportModalOpen(false)}
|
||||||
|
title="Bulk Import Contracts"
|
||||||
|
description="Upload an Excel (.xlsx/.xls) or CSV spreadsheet to register or update multiple AMC/CMC equipment contracts at once."
|
||||||
|
entityName="Contracts"
|
||||||
|
templateFilename="contracts_import_template.xlsx"
|
||||||
|
onDownloadTemplate={() => contractsApi.downloadImportTemplate()}
|
||||||
|
onImport={(file, dryRun, skipInvalid) => contractsApi.bulkImport(file, dryRun, skipInvalid)}
|
||||||
|
queryKeysToInvalidate={[["contracts"], ["dashboard"]]}
|
||||||
|
previewColumns={[
|
||||||
|
{ key: "asset_code", label: "Asset Code" },
|
||||||
|
{ key: "provider_name", label: "Provider" },
|
||||||
|
{ key: "contract_type", label: "Type" },
|
||||||
|
{ key: "start_date", label: "Start Date" },
|
||||||
|
{ key: "end_date", label: "End Date" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -119,14 +119,19 @@ export function DemoEquipmentPage() {
|
|||||||
const columns: ColumnDef<DemoEquipmentItem, unknown>[] = [
|
const columns: ColumnDef<DemoEquipmentItem, unknown>[] = [
|
||||||
{
|
{
|
||||||
id: "equipment",
|
id: "equipment",
|
||||||
accessorFn: (r) => `${r.name} ${r.equipment_type ?? ""}`,
|
accessorFn: (r) => `${r.name} ${r.equipment_type ?? ""} ${r.serial_no ?? ""}`,
|
||||||
header: "Equipment",
|
header: "Equipment",
|
||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
<div>
|
<div>
|
||||||
<div className="font-medium text-gray-900">{row.original.name}</div>
|
<div className="font-medium text-gray-900">{row.original.name}</div>
|
||||||
{row.original.equipment_type && (
|
<div className="text-xs text-gray-500">
|
||||||
<div className="text-xs text-gray-500">{row.original.equipment_type}</div>
|
{[
|
||||||
)}
|
row.original.equipment_type,
|
||||||
|
row.original.serial_no ? `SN: ${row.original.serial_no}` : null,
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" • ")}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -428,6 +433,7 @@ function DemoFormModal({
|
|||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [equipmentType, setEquipmentType] = useState("");
|
const [equipmentType, setEquipmentType] = useState("");
|
||||||
|
const [serialNo, setSerialNo] = useState("");
|
||||||
const [supplierId, setSupplierId] = useState("");
|
const [supplierId, setSupplierId] = useState("");
|
||||||
const [departmentId, setDepartmentId] = useState("");
|
const [departmentId, setDepartmentId] = useState("");
|
||||||
const [locationId, setLocationId] = useState("");
|
const [locationId, setLocationId] = useState("");
|
||||||
@@ -443,6 +449,7 @@ function DemoFormModal({
|
|||||||
if (editing) {
|
if (editing) {
|
||||||
setName(editing.name);
|
setName(editing.name);
|
||||||
setEquipmentType(editing.equipment_type ?? "");
|
setEquipmentType(editing.equipment_type ?? "");
|
||||||
|
setSerialNo(editing.serial_no ?? "");
|
||||||
setSupplierId(String(editing.supplier_id));
|
setSupplierId(String(editing.supplier_id));
|
||||||
setDepartmentId(String(editing.department_id));
|
setDepartmentId(String(editing.department_id));
|
||||||
setLocationId(editing.location_id ? String(editing.location_id) : "");
|
setLocationId(editing.location_id ? String(editing.location_id) : "");
|
||||||
@@ -455,6 +462,7 @@ function DemoFormModal({
|
|||||||
plus14.setDate(plus14.getDate() + 14);
|
plus14.setDate(plus14.getDate() + 14);
|
||||||
setName("");
|
setName("");
|
||||||
setEquipmentType("");
|
setEquipmentType("");
|
||||||
|
setSerialNo("");
|
||||||
setSupplierId("");
|
setSupplierId("");
|
||||||
setDepartmentId("");
|
setDepartmentId("");
|
||||||
setLocationId("");
|
setLocationId("");
|
||||||
@@ -476,6 +484,7 @@ function DemoFormModal({
|
|||||||
const payload = {
|
const payload = {
|
||||||
name: name.trim(),
|
name: name.trim(),
|
||||||
equipment_type: equipmentType.trim(),
|
equipment_type: equipmentType.trim(),
|
||||||
|
serial_no: serialNo.trim() || null,
|
||||||
supplier_id: Number(supplierId),
|
supplier_id: Number(supplierId),
|
||||||
department_id: Number(departmentId),
|
department_id: Number(departmentId),
|
||||||
location_id: locationId ? Number(locationId) : null,
|
location_id: locationId ? Number(locationId) : null,
|
||||||
@@ -537,6 +546,16 @@ function DemoFormModal({
|
|||||||
className={inputCls}
|
className={inputCls}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Serial Number</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={serialNo}
|
||||||
|
onChange={(e) => setSerialNo(e.target.value)}
|
||||||
|
placeholder="e.g. SN-DEMO-901"
|
||||||
|
className={inputCls}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<label className={labelCls}>Supplier *</label>
|
<label className={labelCls}>Supplier *</label>
|
||||||
<select
|
<select
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import {
|
|||||||
ShieldCheck,
|
ShieldCheck,
|
||||||
Search,
|
Search,
|
||||||
AlertCircle,
|
AlertCircle,
|
||||||
|
Download,
|
||||||
|
Upload,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import { insuranceApi, type InsuranceItem } from "@/api/phase5";
|
import { insuranceApi, type InsuranceItem } from "@/api/phase5";
|
||||||
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||||
@@ -26,6 +28,7 @@ import { AssetPicker } from "@/components/AssetPicker";
|
|||||||
import { Attachments } from "@/components/Attachments";
|
import { Attachments } from "@/components/Attachments";
|
||||||
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
import { InsuranceDrawer } from "@/components/InsuranceDrawer";
|
||||||
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
import { ConfirmDialog } from "@/components/ConfirmDialog";
|
||||||
|
import { BulkGenericImportModal } from "@/components/BulkGenericImportModal";
|
||||||
import { toast } from "@/lib/toast";
|
import { toast } from "@/lib/toast";
|
||||||
|
|
||||||
const inputCls =
|
const inputCls =
|
||||||
@@ -49,6 +52,9 @@ export function InsurancePage() {
|
|||||||
const [q, setQ] = useState("");
|
const [q, setQ] = useState("");
|
||||||
const [departmentId, setDepartmentId] = useState("");
|
const [departmentId, setDepartmentId] = useState("");
|
||||||
const [insurerId, setInsurerId] = useState("");
|
const [insurerId, setInsurerId] = useState("");
|
||||||
|
const [expiryFrom, setExpiryFrom] = useState("");
|
||||||
|
const [expiryTo, setExpiryTo] = useState("");
|
||||||
|
const [importModalOpen, setImportModalOpen] = useState(false);
|
||||||
|
|
||||||
const [formOpen, setFormOpen] = useState(false);
|
const [formOpen, setFormOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState<InsuranceItem | null>(null);
|
const [editing, setEditing] = useState<InsuranceItem | null>(null);
|
||||||
@@ -71,13 +77,23 @@ export function InsurancePage() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const policiesQuery = useQuery({
|
const policiesQuery = useQuery({
|
||||||
queryKey: ["insurance", q, departmentId, insurerId, statusFilter],
|
queryKey: [
|
||||||
|
"insurance",
|
||||||
|
q,
|
||||||
|
departmentId,
|
||||||
|
insurerId,
|
||||||
|
statusFilter,
|
||||||
|
expiryFrom,
|
||||||
|
expiryTo,
|
||||||
|
],
|
||||||
queryFn: () =>
|
queryFn: () =>
|
||||||
insuranceApi.list({
|
insuranceApi.list({
|
||||||
q: q.trim() || undefined,
|
q: q.trim() || undefined,
|
||||||
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
department_id: !isDeptUser && departmentId ? Number(departmentId) : undefined,
|
||||||
insurer_id: insurerId ? Number(insurerId) : undefined,
|
insurer_id: insurerId ? Number(insurerId) : undefined,
|
||||||
status: statusFilter || undefined,
|
status: statusFilter || undefined,
|
||||||
|
expiry_from: expiryFrom || undefined,
|
||||||
|
expiry_to: expiryTo || undefined,
|
||||||
page_size: 200,
|
page_size: 200,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -238,15 +254,38 @@ export function InsurancePage() {
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
{canManage && (
|
{canManage && (
|
||||||
<Button
|
<div className="flex items-center gap-2">
|
||||||
onClick={() => {
|
<Button
|
||||||
setEditing(null);
|
variant="outline"
|
||||||
setFormOpen(true);
|
onClick={async () => {
|
||||||
}}
|
try {
|
||||||
>
|
await insuranceApi.downloadImportTemplate();
|
||||||
<Plus className="h-4 w-4 mr-1.5" />
|
toast.success("Downloaded Insurance import template (.xlsx)");
|
||||||
Add Insurance Policy
|
} catch {
|
||||||
</Button>
|
toast.error("Failed to download template");
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Download className="h-4 w-4 mr-1.5" />
|
||||||
|
Template (.xlsx)
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setImportModalOpen(true)}
|
||||||
|
>
|
||||||
|
<Upload className="h-4 w-4 mr-1.5" />
|
||||||
|
Import (.xlsx)
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setEditing(null);
|
||||||
|
setFormOpen(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4 mr-1.5" />
|
||||||
|
Add Insurance Policy
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -310,6 +349,39 @@ export function InsurancePage() {
|
|||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1.5 sm:col-span-2 lg:col-span-3">
|
||||||
|
<span className="text-[11px] text-gray-500 whitespace-nowrap">Expiry:</span>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={expiryFrom}
|
||||||
|
onChange={(e) => setExpiryFrom(e.target.value)}
|
||||||
|
title="Expiry From"
|
||||||
|
placeholder="From"
|
||||||
|
className="px-2 py-1 text-xs border border-gray-200 rounded-md bg-white"
|
||||||
|
/>
|
||||||
|
<span className="text-[11px] text-gray-400">to</span>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={expiryTo}
|
||||||
|
onChange={(e) => setExpiryTo(e.target.value)}
|
||||||
|
title="Expiry To"
|
||||||
|
placeholder="To"
|
||||||
|
className="px-2 py-1 text-xs border border-gray-200 rounded-md bg-white"
|
||||||
|
/>
|
||||||
|
{(expiryFrom || expiryTo) && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setExpiryFrom("");
|
||||||
|
setExpiryTo("");
|
||||||
|
}}
|
||||||
|
className="text-[11px] text-[#1e3a8a] hover:underline whitespace-nowrap"
|
||||||
|
>
|
||||||
|
Clear
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -364,6 +436,25 @@ export function InsurancePage() {
|
|||||||
if (deleteTarget) deleteMutation.mutate(deleteTarget.id);
|
if (deleteTarget) deleteMutation.mutate(deleteTarget.id);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<BulkGenericImportModal
|
||||||
|
open={importModalOpen}
|
||||||
|
onClose={() => setImportModalOpen(false)}
|
||||||
|
title="Bulk Import Insurance Policies"
|
||||||
|
description="Upload an Excel (.xlsx/.xls) or CSV spreadsheet to register or update multiple equipment insurance policies at once."
|
||||||
|
entityName="Insurance Policies"
|
||||||
|
templateFilename="insurance_import_template.xlsx"
|
||||||
|
onDownloadTemplate={() => insuranceApi.downloadImportTemplate()}
|
||||||
|
onImport={(file, dryRun, skipInvalid) => insuranceApi.bulkImport(file, dryRun, skipInvalid)}
|
||||||
|
queryKeysToInvalidate={[["insurance"], ["dashboard"]]}
|
||||||
|
previewColumns={[
|
||||||
|
{ key: "asset_code", label: "Asset Code" },
|
||||||
|
{ key: "insurer_name", label: "Insurer" },
|
||||||
|
{ key: "policy_number", label: "Policy No" },
|
||||||
|
{ key: "start_date", label: "Start Date" },
|
||||||
|
{ key: "end_date", label: "End Date" },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,18 @@
|
|||||||
import { useState, useMemo } from "react";
|
import { useState, useMemo, useEffect } from "react";
|
||||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import type { ColumnDef } from "@tanstack/react-table";
|
import type { ColumnDef } from "@tanstack/react-table";
|
||||||
import { Plus, Pencil, Power, AlertCircle } from "lucide-react";
|
import { Plus, Pencil, Power, AlertCircle, KeyRound, Eye, EyeOff } from "lucide-react";
|
||||||
import { DataTable } from "@/components/DataTable";
|
import { DataTable } from "@/components/DataTable";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Modal } from "@/components/ui/dialog";
|
import { Modal } from "@/components/ui/dialog";
|
||||||
import { ApiError } from "@/api/client";
|
import { ApiError } from "@/api/client";
|
||||||
import { ROLE_LABELS, type Role } from "@/lib/permissions";
|
import { ROLE_LABELS, type Role } from "@/lib/permissions";
|
||||||
|
import { useAuthStore } from "@/hooks/useAuth";
|
||||||
|
import { toast } from "@/lib/toast";
|
||||||
import {
|
import {
|
||||||
departmentsApi,
|
departmentsApi,
|
||||||
locationsApi,
|
locationsApi,
|
||||||
@@ -425,8 +427,8 @@ function buildUserSchema(isEdit: boolean) {
|
|||||||
role: z.enum(["system_admin", "biomedical", "department_user", "management", "coordinator"]),
|
role: z.enum(["system_admin", "biomedical", "department_user", "management", "coordinator"]),
|
||||||
department_id: z.string().optional(),
|
department_id: z.string().optional(),
|
||||||
password: isEdit
|
password: isEdit
|
||||||
? z.string().refine((v) => v === "" || v.length >= 6, "Password must be at least 6 characters")
|
? z.string().refine((v) => v === "" || v.length >= 8, "Password must be at least 8 characters")
|
||||||
: z.string().min(6, "Password must be at least 6 characters"),
|
: z.string().min(8, "Password must be at least 8 characters"),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -530,6 +532,7 @@ function UserModal({
|
|||||||
{editing ? "New Password (leave blank to keep current)" : "Password *"}
|
{editing ? "New Password (leave blank to keep current)" : "Password *"}
|
||||||
</label>
|
</label>
|
||||||
<input {...register("password")} type="password" className={inputCls} />
|
<input {...register("password")} type="password" className={inputCls} />
|
||||||
|
<p className="text-xs text-gray-500 mt-1">At least 8 characters, with a letter and a number.</p>
|
||||||
{errors.password && <p className={errCls}>{errors.password.message}</p>}
|
{errors.password && <p className={errCls}>{errors.password.message}</p>}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-end gap-2 pt-2">
|
<div className="flex justify-end gap-2 pt-2">
|
||||||
@@ -541,6 +544,113 @@ function UserModal({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function ResetPasswordModal({
|
||||||
|
user,
|
||||||
|
onClose,
|
||||||
|
}: {
|
||||||
|
user: MasterUser | null;
|
||||||
|
onClose: () => void;
|
||||||
|
}) {
|
||||||
|
const [newPassword, setNewPassword] = useState("");
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState("");
|
||||||
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
|
const [clientError, setClientError] = useState<string | null>(null);
|
||||||
|
const [serverError, setServerError] = useState<string | null>(null);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setNewPassword("");
|
||||||
|
setConfirmPassword("");
|
||||||
|
setShowPassword(false);
|
||||||
|
setClientError(null);
|
||||||
|
setServerError(null);
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
if (!user) return null;
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!user) return;
|
||||||
|
setClientError(null);
|
||||||
|
setServerError(null);
|
||||||
|
|
||||||
|
if (newPassword !== confirmPassword) {
|
||||||
|
setClientError("Passwords do not match");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
await usersApi.resetPassword(user.id, newPassword);
|
||||||
|
toast.success(`Password for ${user.name} has been reset.`);
|
||||||
|
setNewPassword("");
|
||||||
|
setConfirmPassword("");
|
||||||
|
onClose();
|
||||||
|
} catch (err) {
|
||||||
|
setServerError(err instanceof ApiError ? err.detail : "Failed to reset password.");
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={Boolean(user)}
|
||||||
|
onOpenChange={(open) => !open && onClose()}
|
||||||
|
title={`Reset Password for ${user.name}`}
|
||||||
|
>
|
||||||
|
<FormErrorBanner message={clientError || serverError} />
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>New Password *</label>
|
||||||
|
<div className="relative">
|
||||||
|
<input
|
||||||
|
type={showPassword ? "text" : "password"}
|
||||||
|
value={newPassword}
|
||||||
|
onChange={(e) => setNewPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
className={inputCls}
|
||||||
|
placeholder="Enter new password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowPassword((s) => !s)}
|
||||||
|
className="absolute right-2.5 top-2.5 text-gray-400 hover:text-gray-600"
|
||||||
|
aria-label={showPassword ? "Hide password" : "Show password"}
|
||||||
|
>
|
||||||
|
{showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500 mt-1">At least 8 characters, with a letter and a number.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Confirm Password *</label>
|
||||||
|
<input
|
||||||
|
type={showPassword ? "text" : "password"}
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
className={inputCls}
|
||||||
|
placeholder="Re-enter new password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2 pt-2 border-t border-gray-100">
|
||||||
|
<Button type="button" variant="outline" onClick={onClose} disabled={submitting}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" loading={submitting}>
|
||||||
|
Reset Password
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// --- Main MastersPage ---
|
// --- Main MastersPage ---
|
||||||
export function MastersPage() {
|
export function MastersPage() {
|
||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
@@ -553,6 +663,8 @@ export function MastersPage() {
|
|||||||
const [editingCat, setEditingCat] = useState<Category | null>(null);
|
const [editingCat, setEditingCat] = useState<Category | null>(null);
|
||||||
const [editingVendor, setEditingVendor] = useState<Vendor | null>(null);
|
const [editingVendor, setEditingVendor] = useState<Vendor | null>(null);
|
||||||
const [editingUser, setEditingUser] = useState<MasterUser | null>(null);
|
const [editingUser, setEditingUser] = useState<MasterUser | null>(null);
|
||||||
|
const [resetPasswordUser, setResetPasswordUser] = useState<MasterUser | null>(null);
|
||||||
|
const { user: currentUser } = useAuthStore();
|
||||||
|
|
||||||
const deptsQuery = useQuery({
|
const deptsQuery = useQuery({
|
||||||
queryKey: ["departments", includeInactive],
|
queryKey: ["departments", includeInactive],
|
||||||
@@ -805,17 +917,30 @@ export function MastersPage() {
|
|||||||
enableSorting: false,
|
enableSorting: false,
|
||||||
enableColumnFilter: false,
|
enableColumnFilter: false,
|
||||||
cell: ({ row }) => (
|
cell: ({ row }) => (
|
||||||
<RowActions
|
<div className="flex items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
|
||||||
active={row.original.is_active}
|
<RowActions
|
||||||
busy={toggleMutation.isPending}
|
active={row.original.is_active}
|
||||||
onEdit={() => {
|
busy={toggleMutation.isPending}
|
||||||
setEditingUser(row.original);
|
onEdit={() => {
|
||||||
setModalOpen(true);
|
setEditingUser(row.original);
|
||||||
}}
|
setModalOpen(true);
|
||||||
onToggleActive={() =>
|
}}
|
||||||
toggleMutation.mutate({ tab: "users", id: row.original.id, currentlyActive: row.original.is_active })
|
onToggleActive={() =>
|
||||||
}
|
toggleMutation.mutate({ tab: "users", id: row.original.id, currentlyActive: row.original.is_active })
|
||||||
/>
|
}
|
||||||
|
/>
|
||||||
|
{currentUser?.role === "system_admin" && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setResetPasswordUser(row.original)}
|
||||||
|
className="text-blue-600 hover:text-blue-800"
|
||||||
|
>
|
||||||
|
<KeyRound className="h-3.5 w-3.5 mr-1" />
|
||||||
|
Reset password
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -946,6 +1071,12 @@ export function MastersPage() {
|
|||||||
departments={activeDepartments}
|
departments={activeDepartments}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
{resetPasswordUser && (
|
||||||
|
<ResetPasswordModal
|
||||||
|
user={resetPasswordUser}
|
||||||
|
onClose={() => setResetPasswordUser(null)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
ChevronLeft,
|
ChevronLeft,
|
||||||
ChevronRight,
|
ChevronRight,
|
||||||
Search,
|
Search,
|
||||||
|
Paperclip,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import {
|
import {
|
||||||
pmApi,
|
pmApi,
|
||||||
@@ -28,6 +29,7 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Modal } from "@/components/ui/dialog";
|
import { Modal } from "@/components/ui/dialog";
|
||||||
import { ScheduleStatusBadge } from "@/components/StatusBadge";
|
import { ScheduleStatusBadge } from "@/components/StatusBadge";
|
||||||
|
import { Attachments } from "@/components/Attachments";
|
||||||
import {
|
import {
|
||||||
NewPMScheduleModal,
|
NewPMScheduleModal,
|
||||||
CompletePMModal,
|
CompletePMModal,
|
||||||
@@ -96,6 +98,7 @@ export function PMPage() {
|
|||||||
const [completingRec, setCompletingRec] = useState<PMRecordItem | null>(null);
|
const [completingRec, setCompletingRec] = useState<PMRecordItem | null>(null);
|
||||||
const [reschedulingRec, setReschedulingRec] = useState<PMRecordItem | null>(null);
|
const [reschedulingRec, setReschedulingRec] = useState<PMRecordItem | null>(null);
|
||||||
const [calendarDetailRec, setCalendarDetailRec] = useState<PMRecordItem | null>(null);
|
const [calendarDetailRec, setCalendarDetailRec] = useState<PMRecordItem | null>(null);
|
||||||
|
const [attachRec, setAttachRec] = useState<PMRecordItem | null>(null);
|
||||||
|
|
||||||
const effectiveCalendarMonth = monthFilter || currentYearMonth();
|
const effectiveCalendarMonth = monthFilter || currentYearMonth();
|
||||||
|
|
||||||
@@ -236,6 +239,23 @@ export function PMPage() {
|
|||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "attachments",
|
||||||
|
header: "Reports",
|
||||||
|
enableSorting: false,
|
||||||
|
enableColumnFilter: false,
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() => setAttachRec(row.original)}
|
||||||
|
aria-label={`Attachments for PM ${row.original.id}`}
|
||||||
|
>
|
||||||
|
<Paperclip className="h-3.5 w-3.5 mr-1" />
|
||||||
|
Docs
|
||||||
|
</Button>
|
||||||
|
),
|
||||||
|
},
|
||||||
...(canManagePm
|
...(canManagePm
|
||||||
? [
|
? [
|
||||||
{
|
{
|
||||||
@@ -726,6 +746,21 @@ export function PMPage() {
|
|||||||
}
|
}
|
||||||
assetId={reschedulingRec?.asset_id}
|
assetId={reschedulingRec?.asset_id}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{attachRec && (
|
||||||
|
<Modal
|
||||||
|
open={Boolean(attachRec)}
|
||||||
|
onOpenChange={(o) => !o && setAttachRec(null)}
|
||||||
|
title={`PM Service Reports — ${attachRec.asset_code} (${attachRec.asset_name})`}
|
||||||
|
>
|
||||||
|
<Attachments
|
||||||
|
entityType="pm_record"
|
||||||
|
entityId={attachRec.id}
|
||||||
|
canUpload={canManagePm}
|
||||||
|
canDelete={canManagePm}
|
||||||
|
/>
|
||||||
|
</Modal>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ import {
|
|||||||
HelpCircle,
|
HelpCircle,
|
||||||
AlertCircle,
|
AlertCircle,
|
||||||
Lock,
|
Lock,
|
||||||
|
RotateCcw,
|
||||||
|
Filter,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import {
|
import {
|
||||||
REPORT_CATALOG,
|
REPORT_CATALOG,
|
||||||
@@ -36,6 +38,8 @@ import { useAuthStore } from "@/hooks/useAuth";
|
|||||||
import { formatDateTime } from "@/lib/format";
|
import { formatDateTime } from "@/lib/format";
|
||||||
import { DataTable } from "@/components/DataTable";
|
import { DataTable } from "@/components/DataTable";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
import { toast } from "@/lib/toast";
|
import { toast } from "@/lib/toast";
|
||||||
|
|
||||||
function currentMonthStr(): string {
|
function currentMonthStr(): string {
|
||||||
@@ -210,6 +214,55 @@ export function ReportDetailPage() {
|
|||||||
contractType,
|
contractType,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const activeFiltersCount = useMemo(() => {
|
||||||
|
let count = 0;
|
||||||
|
if (departmentId) count++;
|
||||||
|
if (month && month !== currentMonthStr()) count++;
|
||||||
|
if (dateFrom || dateTo) count++;
|
||||||
|
if (dueFrom || dueTo) count++;
|
||||||
|
if (priority) count++;
|
||||||
|
if (callStatus) count++;
|
||||||
|
if (serviceMode) count++;
|
||||||
|
if (agencyId) count++;
|
||||||
|
if (supplierId) count++;
|
||||||
|
if (statusFilter) count++;
|
||||||
|
if (recordKind && recordKind !== "all") count++;
|
||||||
|
if (contractType) count++;
|
||||||
|
return count;
|
||||||
|
}, [
|
||||||
|
departmentId,
|
||||||
|
month,
|
||||||
|
dateFrom,
|
||||||
|
dateTo,
|
||||||
|
dueFrom,
|
||||||
|
dueTo,
|
||||||
|
priority,
|
||||||
|
callStatus,
|
||||||
|
serviceMode,
|
||||||
|
agencyId,
|
||||||
|
supplierId,
|
||||||
|
statusFilter,
|
||||||
|
recordKind,
|
||||||
|
contractType,
|
||||||
|
]);
|
||||||
|
|
||||||
|
function handleResetFilters() {
|
||||||
|
setMonth(currentMonthStr());
|
||||||
|
setDateFrom("");
|
||||||
|
setDateTo("");
|
||||||
|
setDueFrom("");
|
||||||
|
setDueTo("");
|
||||||
|
setDepartmentId("");
|
||||||
|
setPriority("");
|
||||||
|
setCallStatus("");
|
||||||
|
setServiceMode("");
|
||||||
|
setAgencyId("");
|
||||||
|
setSupplierId("");
|
||||||
|
setStatusFilter("");
|
||||||
|
setRecordKind("all");
|
||||||
|
setContractType("");
|
||||||
|
}
|
||||||
|
|
||||||
const deptsQuery = useQuery({
|
const deptsQuery = useQuery({
|
||||||
queryKey: ["departments", "active-only"],
|
queryKey: ["departments", "active-only"],
|
||||||
queryFn: () => departmentsApi.list(false),
|
queryFn: () => departmentsApi.list(false),
|
||||||
@@ -344,52 +397,126 @@ export function ReportDetailPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-5">
|
<div className="space-y-5">
|
||||||
{/* Print-Only Letterhead */}
|
{/* Print-Only Official Hospital Letterhead & Scope */}
|
||||||
<div className="hidden print:flex items-center justify-between border-b-2 border-[#1e3a8a] pb-3 mb-4">
|
<div className="hidden print:block mb-4 border-b-2 border-[#1e3a8a] pb-3">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-start justify-between">
|
||||||
<img
|
<div className="flex items-center gap-3.5">
|
||||||
src="/logo.jpg"
|
<img
|
||||||
alt="Poona Hospital and Research Centre"
|
src="/logo.jpg"
|
||||||
className="h-12 w-12 object-contain"
|
alt="Poona Hospital and Research Centre"
|
||||||
/>
|
className="h-14 w-14 object-contain"
|
||||||
<div>
|
/>
|
||||||
<div className="text-base font-bold text-[#1e3a8a]">
|
<div>
|
||||||
Poona Hospital & Research Centre
|
<div className="text-base font-extrabold text-[#1e3a8a] tracking-tight">
|
||||||
</div>
|
POONA HOSPITAL & RESEARCH CENTRE
|
||||||
<div className="text-xs text-gray-600">
|
</div>
|
||||||
Asset Management & Maintenance — {report?.title ?? meta.title}
|
<div className="text-[11px] font-semibold text-gray-800">
|
||||||
|
NABH Accredited Tertiary Care Hospital • Department of Clinical Engineering
|
||||||
|
</div>
|
||||||
|
<div className="text-[10px] text-gray-500">
|
||||||
|
27, Sadashiv Peth, Pune, Maharashtra 411030 • Tel: +91 20 6609 6000
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="text-right text-[10px] text-gray-600 space-y-0.5 border-l border-gray-200 pl-3">
|
||||||
|
<div className="font-bold text-[#1e3a8a] uppercase tracking-wider">
|
||||||
|
Audit & Operational Record
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>Ref:</strong> PHRC-BME-{key?.toUpperCase() ?? "REP"}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<strong>Date:</strong> {formatDateTime(new Date().toISOString())} IST
|
||||||
|
</div>
|
||||||
|
{user?.name && (
|
||||||
|
<div>
|
||||||
|
<strong>Generated by:</strong> {user.name} ({user.role?.replace(/_/g, " ").toUpperCase()})
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-right text-[11px] text-gray-500">
|
|
||||||
<div>Printed: {formatDateTime(new Date().toISOString())} IST</div>
|
{/* Print Filter / Scope summary bar */}
|
||||||
{user?.name && <div>Generated by: {user.name}</div>}
|
<div className="mt-2.5 pt-2 border-t border-gray-200 flex flex-wrap items-center justify-between text-[10px] text-gray-700 bg-gray-50 px-3 py-1.5 rounded">
|
||||||
|
<div className="flex items-center gap-4 flex-wrap">
|
||||||
|
<div>
|
||||||
|
<span className="text-gray-500">Report:</span>{" "}
|
||||||
|
<strong>{report?.title ?? meta.title}</strong>
|
||||||
|
</div>
|
||||||
|
{month && (
|
||||||
|
<div>
|
||||||
|
<span className="text-gray-500">Period:</span> <strong>{month}</strong>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{dateFrom && (
|
||||||
|
<div>
|
||||||
|
<span className="text-gray-500">From:</span> <strong>{dateFrom}</strong>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{dateTo && (
|
||||||
|
<div>
|
||||||
|
<span className="text-gray-500">To:</span> <strong>{dateTo}</strong>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div>
|
||||||
|
<span className="text-gray-500">Department:</span>{" "}
|
||||||
|
<strong>
|
||||||
|
{departmentId
|
||||||
|
? departments.find((d) => String(d.id) === departmentId)?.name ?? departmentId
|
||||||
|
: isDeptUser && user?.department_name
|
||||||
|
? user.department_name
|
||||||
|
: "All Departments"}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
{priority && (
|
||||||
|
<div>
|
||||||
|
<span className="text-gray-500">Priority:</span>{" "}
|
||||||
|
<strong>{priority.toUpperCase()}</strong>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{callStatus && (
|
||||||
|
<div>
|
||||||
|
<span className="text-gray-500">Status:</span>{" "}
|
||||||
|
<strong>{callStatus.toUpperCase()}</strong>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="font-semibold text-gray-900">
|
||||||
|
Total Records: {report?.rows?.length ?? 0}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Screen Header */}
|
{/* Screen Header */}
|
||||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
<div className="no-print flex flex-wrap items-start justify-between gap-4 bg-white border border-gray-200 rounded-xl p-5 shadow-sm">
|
||||||
<div>
|
<div>
|
||||||
<Link
|
<div className="flex items-center gap-2 mb-2">
|
||||||
to="/reports"
|
<Link
|
||||||
className="no-print inline-flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-800 mb-1"
|
to="/reports"
|
||||||
>
|
className="inline-flex items-center gap-1.5 text-xs font-medium text-gray-500 hover:text-[#1e3a8a] transition-colors"
|
||||||
<ArrowLeft className="h-4 w-4" />
|
>
|
||||||
All Reports
|
<ArrowLeft className="h-3.5 w-3.5" />
|
||||||
</Link>
|
All Reports
|
||||||
<h1 className="text-2xl font-bold text-gray-900">
|
</Link>
|
||||||
|
<span className="text-gray-300">•</span>
|
||||||
|
<Badge variant="outline" className="text-[10px] bg-blue-50/60 text-[#1e3a8a] border-blue-200">
|
||||||
|
{meta.category}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900 tracking-tight">
|
||||||
{report?.title ?? meta.title}
|
{report?.title ?? meta.title}
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm text-gray-500 mt-0.5">{meta.description}</p>
|
<p className="text-sm text-gray-500 mt-1 max-w-2xl leading-relaxed">{meta.description}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="no-print flex flex-wrap items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2.5 pt-1">
|
||||||
{key === "monthly-maintenance" && report?.formula_info && (
|
{key === "monthly-maintenance" && report?.formula_info && (
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => setFormulaOpen((o) => !o)}
|
onClick={() => setFormulaOpen((o) => !o)}
|
||||||
|
className="border-blue-200 text-[#1e3a8a] hover:bg-blue-50 font-medium"
|
||||||
>
|
>
|
||||||
<HelpCircle className="h-4 w-4 mr-1.5 text-[#1e3a8a]" />
|
<HelpCircle className="h-4 w-4 mr-1.5 text-[#1e3a8a]" />
|
||||||
How this is calculated
|
How this is calculated
|
||||||
@@ -400,6 +527,7 @@ export function ReportDetailPage() {
|
|||||||
size="sm"
|
size="sm"
|
||||||
loading={exporting === "xlsx"}
|
loading={exporting === "xlsx"}
|
||||||
onClick={() => handleExport("xlsx")}
|
onClick={() => handleExport("xlsx")}
|
||||||
|
className="bg-emerald-700 hover:bg-emerald-800 text-white shadow-sm font-medium"
|
||||||
>
|
>
|
||||||
<FileSpreadsheet className="h-4 w-4 mr-1.5" />
|
<FileSpreadsheet className="h-4 w-4 mr-1.5" />
|
||||||
Export Excel (.xlsx)
|
Export Excel (.xlsx)
|
||||||
@@ -409,9 +537,11 @@ export function ReportDetailPage() {
|
|||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => window.print()}
|
onClick={() => window.print()}
|
||||||
|
className="border-gray-300 hover:bg-gray-50 text-gray-700 shadow-sm font-medium"
|
||||||
|
title="Generates an executive A4 landscape PDF report with official hospital sign-off"
|
||||||
>
|
>
|
||||||
<Printer className="h-4 w-4 mr-1.5" />
|
<Printer className="h-4 w-4 mr-1.5 text-[#1e3a8a]" />
|
||||||
Print A4
|
Print A4 / PDF
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -458,7 +588,32 @@ export function ReportDetailPage() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Tailored Filter Bar */}
|
{/* Tailored Filter Bar */}
|
||||||
<div className="no-print bg-white border border-gray-200 rounded-lg p-3.5 flex flex-wrap items-end gap-3">
|
<div className="no-print bg-white border border-gray-200 rounded-xl p-4 shadow-sm space-y-3">
|
||||||
|
<div className="flex items-center justify-between border-b border-gray-100 pb-2.5">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Filter className="h-4 w-4 text-[#1e3a8a]" />
|
||||||
|
<span className="text-xs font-semibold text-gray-800 uppercase tracking-wider">
|
||||||
|
Report Parameters & Scope
|
||||||
|
</span>
|
||||||
|
{activeFiltersCount > 0 && (
|
||||||
|
<Badge variant="info" className="text-[10px] px-2 py-0.5">
|
||||||
|
{activeFiltersCount} active filter{activeFiltersCount > 1 ? "s" : ""}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{activeFiltersCount > 0 && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleResetFilters}
|
||||||
|
className="text-xs text-gray-500 hover:text-red-600 flex items-center gap-1 transition-colors font-medium"
|
||||||
|
>
|
||||||
|
<RotateCcw className="h-3.5 w-3.5" />
|
||||||
|
Reset filters
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-end gap-3.5 pt-0.5">
|
||||||
{(key === "monthly-maintenance" ||
|
{(key === "monthly-maintenance" ||
|
||||||
key === "monthly-department" ||
|
key === "monthly-department" ||
|
||||||
key === "pm-compliance") && (
|
key === "pm-compliance") && (
|
||||||
@@ -742,34 +897,49 @@ export function ReportDetailPage() {
|
|||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Summary Strip */}
|
{/* Summary Strip */}
|
||||||
{report && (
|
{report && (
|
||||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2.5 print-break-inside-avoid">
|
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 print-break-inside-avoid">
|
||||||
{key === "monthly-maintenance" && (
|
{key === "monthly-maintenance" && (
|
||||||
<div className="bg-emerald-50 border border-emerald-300 rounded-lg p-3">
|
<div className="bg-white border border-emerald-300 border-t-4 border-t-emerald-600 rounded-xl p-3.5 shadow-sm">
|
||||||
<div className="text-[11px] font-semibold text-emerald-800">
|
<div className="text-[11px] font-semibold text-emerald-800 uppercase tracking-wider">
|
||||||
Uptime %
|
Uptime %
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xl font-bold text-emerald-900 mt-0.5 truncate">
|
<div className="text-2xl font-black text-emerald-900 mt-1 truncate">
|
||||||
{computeUptimePct(report.summary)}
|
{computeUptimePct(report.summary)}
|
||||||
</div>
|
</div>
|
||||||
|
<div className="text-[10px] text-emerald-700 mt-0.5">Hospital Availability</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{Object.entries(report.summary).map(([sKey, sVal]) => (
|
{Object.entries(report.summary).map(([sKey, sVal]) => {
|
||||||
<div
|
const isNegative = sKey.includes("downtime") || sKey.includes("overdue") || sKey.includes("under_repair");
|
||||||
key={sKey}
|
const isPositive = sKey.includes("uptime") || sKey.includes("compliance") || sKey.includes("completed");
|
||||||
className="bg-white border border-gray-200 rounded-lg p-3"
|
const borderTopColor = isNegative
|
||||||
>
|
? "border-t-rose-500"
|
||||||
<div className="text-[11px] font-medium text-gray-500">
|
: isPositive
|
||||||
{humanizeSummaryKey(sKey)}
|
? "border-t-emerald-500"
|
||||||
|
: "border-t-[#1e3a8a]";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={sKey}
|
||||||
|
className={cn(
|
||||||
|
"bg-white border border-gray-200 border-t-4 rounded-xl p-3.5 shadow-sm",
|
||||||
|
borderTopColor
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="text-[11px] font-medium text-gray-500 truncate">
|
||||||
|
{humanizeSummaryKey(sKey)}
|
||||||
|
</div>
|
||||||
|
<div className="text-xl font-bold text-gray-900 mt-1 truncate">
|
||||||
|
{String(sVal)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-lg font-bold text-gray-900 mt-0.5 truncate">
|
);
|
||||||
{String(sVal)}
|
})}
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -788,18 +958,26 @@ export function ReportDetailPage() {
|
|||||||
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
|
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
|
||||||
<XAxis dataKey="department" tick={{ fontSize: 11 }} />
|
<XAxis dataKey="department" tick={{ fontSize: 11 }} />
|
||||||
<YAxis tick={{ fontSize: 11 }} />
|
<YAxis tick={{ fontSize: 11 }} />
|
||||||
<Tooltip />
|
<Tooltip
|
||||||
<Legend />
|
contentStyle={{
|
||||||
|
backgroundColor: "#ffffff",
|
||||||
|
borderColor: "#cbd5e1",
|
||||||
|
borderRadius: "8px",
|
||||||
|
boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)",
|
||||||
|
fontSize: "12px",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Legend wrapperStyle={{ fontSize: "12px", paddingTop: "8px" }} />
|
||||||
<Bar
|
<Bar
|
||||||
dataKey="uptime_hours"
|
dataKey="uptime_hours"
|
||||||
name="Uptime (hrs)"
|
name="Uptime (hrs)"
|
||||||
fill="#22c55e"
|
fill="#10b981"
|
||||||
radius={[4, 4, 0, 0]}
|
radius={[4, 4, 0, 0]}
|
||||||
/>
|
/>
|
||||||
<Bar
|
<Bar
|
||||||
dataKey="downtime_hours"
|
dataKey="downtime_hours"
|
||||||
name="Downtime (hrs)"
|
name="Downtime (hrs)"
|
||||||
fill="#ef4444"
|
fill="#f43f5e"
|
||||||
radius={[4, 4, 0, 0]}
|
radius={[4, 4, 0, 0]}
|
||||||
/>
|
/>
|
||||||
</BarChart>
|
</BarChart>
|
||||||
@@ -827,8 +1005,16 @@ export function ReportDetailPage() {
|
|||||||
<Cell key={idx} fill={entry.color} />
|
<Cell key={idx} fill={entry.color} />
|
||||||
))}
|
))}
|
||||||
</Pie>
|
</Pie>
|
||||||
<Tooltip />
|
<Tooltip
|
||||||
<Legend />
|
contentStyle={{
|
||||||
|
backgroundColor: "#ffffff",
|
||||||
|
borderColor: "#cbd5e1",
|
||||||
|
borderRadius: "8px",
|
||||||
|
boxShadow: "0 4px 6px -1px rgb(0 0 0 / 0.1)",
|
||||||
|
fontSize: "12px",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Legend wrapperStyle={{ fontSize: "12px", paddingTop: "8px" }} />
|
||||||
</PieChart>
|
</PieChart>
|
||||||
</ResponsiveContainer>
|
</ResponsiveContainer>
|
||||||
</div>
|
</div>
|
||||||
@@ -844,6 +1030,47 @@ export function ReportDetailPage() {
|
|||||||
globalFilterPlaceholder="Quick filter report rows..."
|
globalFilterPlaceholder="Quick filter report rows..."
|
||||||
emptyMessage="No rows match the selected report filters."
|
emptyMessage="No rows match the selected report filters."
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Hospital Tripartite Sign-off Block (Print / PDF Only) */}
|
||||||
|
<div className="hidden print:block mt-8 pt-4 border-t-2 border-gray-300 print-break-inside-avoid">
|
||||||
|
<div className="flex items-center justify-between text-[10px] font-bold uppercase tracking-wider text-gray-700 mb-4">
|
||||||
|
<span>Hospital Engineering Audit & Verification Sign-off (NABH Chapter FMS)</span>
|
||||||
|
<span>Poona Hospital & Research Centre</span>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-3 gap-5 text-[10px]">
|
||||||
|
<div className="border border-gray-300 rounded p-3 space-y-4 bg-gray-50/50">
|
||||||
|
<div className="font-bold text-gray-800">1. PREPARED BY</div>
|
||||||
|
<div className="h-9 border-b border-dashed border-gray-400"></div>
|
||||||
|
<div className="space-y-0.5 text-gray-600">
|
||||||
|
<div>Name: {user?.name || "Biomedical Engineer"}</div>
|
||||||
|
<div>Role: {user?.role?.replace(/_/g, " ").toUpperCase() || "BIOMEDICAL"}</div>
|
||||||
|
<div>Date: {new Date().toLocaleDateString("en-IN")}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="border border-gray-300 rounded p-3 space-y-4 bg-gray-50/50">
|
||||||
|
<div className="font-bold text-gray-800">2. VERIFIED BY</div>
|
||||||
|
<div className="h-9 border-b border-dashed border-gray-400"></div>
|
||||||
|
<div className="space-y-0.5 text-gray-600">
|
||||||
|
<div>Name: __________________________</div>
|
||||||
|
<div>Role: HOD / Biomedical In-Charge</div>
|
||||||
|
<div>Date: ____ / ____ / ________</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="border border-gray-300 rounded p-3 space-y-4 bg-gray-50/50">
|
||||||
|
<div className="font-bold text-gray-800">3. APPROVED BY</div>
|
||||||
|
<div className="h-9 border-b border-dashed border-gray-400"></div>
|
||||||
|
<div className="space-y-0.5 text-gray-600">
|
||||||
|
<div>Name: __________________________</div>
|
||||||
|
<div>Role: Medical Superintendent / Director</div>
|
||||||
|
<div>Date: ____ / ____ / ________</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mt-4 pt-2 border-t border-gray-200 text-[9px] text-gray-500 flex items-center justify-between">
|
||||||
|
<span>Official Hospital Record • Poona Hospital & Research Centre • Confidential • Retain for 7 Years</span>
|
||||||
|
<span>AMS Portal Generated • NABH Compliant</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -74,6 +74,19 @@ export function ReportsPage() {
|
|||||||
<p className="text-xs text-gray-600 mt-1 leading-relaxed">
|
<p className="text-xs text-gray-600 mt-1 leading-relaxed">
|
||||||
{report.description}
|
{report.description}
|
||||||
</p>
|
</p>
|
||||||
|
<div className="flex items-center gap-1.5 flex-wrap pt-2.5">
|
||||||
|
<span className="inline-flex items-center text-[10px] text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded font-medium border border-emerald-100">
|
||||||
|
Excel (.xlsx)
|
||||||
|
</span>
|
||||||
|
<span className="inline-flex items-center text-[10px] text-blue-700 bg-blue-50 px-2 py-0.5 rounded font-medium border border-blue-100">
|
||||||
|
A4 / PDF Print
|
||||||
|
</span>
|
||||||
|
{report.key === "monthly-maintenance" && (
|
||||||
|
<span className="inline-flex items-center text-[10px] text-purple-700 bg-purple-50 px-2 py-0.5 rounded font-medium border border-purple-100">
|
||||||
|
Interactive Charts
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -106,11 +106,16 @@ export function VisitsPage() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
accessorKey: "observations",
|
accessorKey: "observations",
|
||||||
header: "Observations",
|
header: "Observations & Requirements",
|
||||||
cell: ({ getValue }) => (
|
cell: ({ row }) => (
|
||||||
<p className="text-xs text-gray-800 whitespace-pre-wrap max-w-sm">
|
<div className="space-y-1 max-w-sm">
|
||||||
{String(getValue())}
|
<p className="text-xs text-gray-800 whitespace-pre-wrap">{row.original.observations}</p>
|
||||||
</p>
|
{row.original.new_requirements && (
|
||||||
|
<p className="text-xs text-blue-700 bg-blue-50 border border-blue-100 rounded px-1.5 py-0.5">
|
||||||
|
<span className="font-semibold">Requirements:</span> {row.original.new_requirements}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -292,6 +297,7 @@ function VisitFormModal({
|
|||||||
const [departmentId, setDepartmentId] = useState("");
|
const [departmentId, setDepartmentId] = useState("");
|
||||||
const [visitDate, setVisitDate] = useState("");
|
const [visitDate, setVisitDate] = useState("");
|
||||||
const [observations, setObservations] = useState("");
|
const [observations, setObservations] = useState("");
|
||||||
|
const [newRequirements, setNewRequirements] = useState("");
|
||||||
const [selectedAssetIds, setSelectedAssetIds] = useState<number[]>([]);
|
const [selectedAssetIds, setSelectedAssetIds] = useState<number[]>([]);
|
||||||
const [assetSearch, setAssetSearch] = useState("");
|
const [assetSearch, setAssetSearch] = useState("");
|
||||||
const [raiseImmediately, setRaiseImmediately] = useState(false);
|
const [raiseImmediately, setRaiseImmediately] = useState(false);
|
||||||
@@ -307,11 +313,13 @@ function VisitFormModal({
|
|||||||
setDepartmentId(String(editing.department_id));
|
setDepartmentId(String(editing.department_id));
|
||||||
setVisitDate(editing.visit_date);
|
setVisitDate(editing.visit_date);
|
||||||
setObservations(editing.observations);
|
setObservations(editing.observations);
|
||||||
|
setNewRequirements(editing.new_requirements ?? "");
|
||||||
setSelectedAssetIds(editing.assets.map((a) => a.id));
|
setSelectedAssetIds(editing.assets.map((a) => a.id));
|
||||||
} else {
|
} else {
|
||||||
setDepartmentId("");
|
setDepartmentId("");
|
||||||
setVisitDate(new Date().toISOString().slice(0, 10));
|
setVisitDate(new Date().toISOString().slice(0, 10));
|
||||||
setObservations("");
|
setObservations("");
|
||||||
|
setNewRequirements("");
|
||||||
setSelectedAssetIds([]);
|
setSelectedAssetIds([]);
|
||||||
}
|
}
|
||||||
}, [open, editing]);
|
}, [open, editing]);
|
||||||
@@ -357,6 +365,7 @@ function VisitFormModal({
|
|||||||
department_id: Number(departmentId),
|
department_id: Number(departmentId),
|
||||||
visit_date: visitDate,
|
visit_date: visitDate,
|
||||||
observations: observations.trim(),
|
observations: observations.trim(),
|
||||||
|
new_requirements: newRequirements.trim() || null,
|
||||||
asset_ids: selectedAssetIds,
|
asset_ids: selectedAssetIds,
|
||||||
});
|
});
|
||||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||||
@@ -366,6 +375,7 @@ function VisitFormModal({
|
|||||||
department_id: Number(departmentId),
|
department_id: Number(departmentId),
|
||||||
visit_date: visitDate,
|
visit_date: visitDate,
|
||||||
observations: observations.trim(),
|
observations: observations.trim(),
|
||||||
|
new_requirements: newRequirements.trim() || null,
|
||||||
asset_ids: selectedAssetIds,
|
asset_ids: selectedAssetIds,
|
||||||
});
|
});
|
||||||
await qc.invalidateQueries({ queryKey: ["visits"] });
|
await qc.invalidateQueries({ queryKey: ["visits"] });
|
||||||
@@ -498,6 +508,17 @@ function VisitFormModal({
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>New Equipment / Maintenance Requirements</label>
|
||||||
|
<textarea
|
||||||
|
rows={2}
|
||||||
|
value={newRequirements}
|
||||||
|
onChange={(e) => setNewRequirements(e.target.value)}
|
||||||
|
placeholder="e.g. Additional infusion pumps requested, new mounting brackets needed..."
|
||||||
|
className={inputCls}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{!editing && (
|
{!editing && (
|
||||||
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||||
<input
|
<input
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||||
|
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||||
|
import { ResetPasswordModal } from "@/pages/MastersPage";
|
||||||
|
import { usersApi, type MasterUser } from "@/api/masters";
|
||||||
|
import { toast } from "@/lib/toast";
|
||||||
|
import { ApiError } from "@/api/client";
|
||||||
|
|
||||||
|
const mockUser: MasterUser = {
|
||||||
|
id: 42,
|
||||||
|
name: "Dr. Jane Doe",
|
||||||
|
email: "jane@poona.demo",
|
||||||
|
role: "department_user",
|
||||||
|
department_id: 2,
|
||||||
|
department_name: "Cardiology",
|
||||||
|
is_active: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("Admin ResetPasswordModal", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders the dialog with user details, helper text, and show/hide password toggle", () => {
|
||||||
|
render(<ResetPasswordModal user={mockUser} onClose={vi.fn()} />);
|
||||||
|
|
||||||
|
expect(screen.getByText("Reset Password for Dr. Jane Doe")).toBeInTheDocument();
|
||||||
|
expect(screen.getByPlaceholderText("Enter new password")).toBeInTheDocument();
|
||||||
|
expect(screen.getByPlaceholderText("Re-enter new password")).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.getByText("At least 8 characters, with a letter and a number.")
|
||||||
|
).toBeInTheDocument();
|
||||||
|
|
||||||
|
const input = screen.getByPlaceholderText("Enter new password");
|
||||||
|
expect(input).toHaveAttribute("type", "password");
|
||||||
|
|
||||||
|
const toggleBtn = screen.getByLabelText("Show password");
|
||||||
|
fireEvent.click(toggleBtn);
|
||||||
|
expect(input).toHaveAttribute("type", "text");
|
||||||
|
expect(screen.getByLabelText("Hide password")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("validates password mismatch before calling API", async () => {
|
||||||
|
const resetSpy = vi.spyOn(usersApi, "resetPassword").mockResolvedValue({ message: "OK" });
|
||||||
|
|
||||||
|
render(<ResetPasswordModal user={mockUser} onClose={vi.fn()} />);
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByPlaceholderText("Enter new password"), {
|
||||||
|
target: { value: "SecurePass1" },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByPlaceholderText("Re-enter new password"), {
|
||||||
|
target: { value: "DifferentPass2" },
|
||||||
|
});
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Reset Password" }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText(/passwords do not match/i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
expect(resetSpy).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("calls API on match, shows success toast, and closes dialog", async () => {
|
||||||
|
const onClose = vi.fn();
|
||||||
|
const resetSpy = vi
|
||||||
|
.spyOn(usersApi, "resetPassword")
|
||||||
|
.mockResolvedValue({ message: "Password reset successfully." });
|
||||||
|
const toastSpy = vi.spyOn(toast, "success");
|
||||||
|
|
||||||
|
render(<ResetPasswordModal user={mockUser} onClose={onClose} />);
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByPlaceholderText("Enter new password"), {
|
||||||
|
target: { value: "NewSecure99" },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByPlaceholderText("Re-enter new password"), {
|
||||||
|
target: { value: "NewSecure99" },
|
||||||
|
});
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Reset Password" }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(resetSpy).toHaveBeenCalledWith(42, "NewSecure99");
|
||||||
|
expect(toastSpy).toHaveBeenCalledWith("Password for Dr. Jane Doe has been reset.");
|
||||||
|
expect(onClose).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("displays server error message when API returns 422 error", async () => {
|
||||||
|
vi.spyOn(usersApi, "resetPassword").mockRejectedValue(
|
||||||
|
new ApiError(422, "Password must not start or end with a space.")
|
||||||
|
);
|
||||||
|
|
||||||
|
render(<ResetPasswordModal user={mockUser} onClose={vi.fn()} />);
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByPlaceholderText("Enter new password"), {
|
||||||
|
target: { value: " SpacePass1 " },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByPlaceholderText("Re-enter new password"), {
|
||||||
|
target: { value: " SpacePass1 " },
|
||||||
|
});
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Reset Password" }));
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(
|
||||||
|
screen.getByText("Password must not start or end with a space.")
|
||||||
|
).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1 +0,0 @@
|
|||||||
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/audit.ts","./src/api/auth.ts","./src/api/calibration.ts","./src/api/client.ts","./src/api/complaints.ts","./src/api/dashboard.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/notifications.ts","./src/api/phase5.ts","./src/api/pm.ts","./src/api/reports.ts","./src/api/search.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/bulkassetimportmodal.tsx","./src/components/calibrationmodals.tsx","./src/components/calibrationremindermodal.tsx","./src/components/confirmdialog.tsx","./src/components/insurancedrawer.tsx","./src/components/pmmodals.tsx","./src/components/raisecomplaintmodal.tsx","./src/components/statusbadge.tsx","./src/components/toastprovider.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/toast.ts","./src/lib/utils.ts","./src/lib/validation.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/auditlogspage.tsx","./src/pages/calibrationpage.tsx","./src/pages/complaintdetailpage.tsx","./src/pages/complaintspage.tsx","./src/pages/contractspage.tsx","./src/pages/dashboardpage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/demoequipmentpage.tsx","./src/pages/insurancepage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/notificationspage.tsx","./src/pages/pmpage.tsx","./src/pages/reportdetailpage.tsx","./src/pages/reportspage.tsx","./src/pages/settingspage.tsx","./src/pages/visitspage.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/bulk-import.test.tsx","./src/test/calibration-page.test.tsx","./src/test/complaint-detail.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/phase5-modules.test.tsx","./src/test/phase6-modules.test.tsx","./src/test/phase8-polish.test.tsx","./src/test/pm-page.test.tsx","./src/test/reports.test.tsx","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
|
|
||||||
@@ -11,7 +11,7 @@ export default defineConfig({
|
|||||||
server: {
|
server: {
|
||||||
port: 5173,
|
port: 5173,
|
||||||
proxy: {
|
proxy: {
|
||||||
"/api": { target: "http://localhost:8000", changeOrigin: true },
|
"/api": { target: "http://127.0.0.1:8000", changeOrigin: true },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
test: {
|
test: {
|
||||||
|
|||||||
Reference in New Issue
Block a user