Compare commits
9
Commits
b6465708f0
...
221cc8918f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
221cc8918f | ||
|
|
51e4b39c33 | ||
|
|
9276064d18 | ||
|
|
b8639bc52a | ||
|
|
cb47017eac | ||
|
|
5f649e3e4c | ||
|
|
c086833163 | ||
|
|
026da64e71 | ||
|
|
041a4075dd |
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
+21
-7
@@ -1,16 +1,19 @@
|
||||
backend/data/ams.db
|
||||
backend/data/test.db
|
||||
# SQLite databases
|
||||
backend/data/*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.db
|
||||
|
||||
# Data directories
|
||||
backend/data/backups/
|
||||
backend/data/uploads/*
|
||||
!backend/data/uploads/.gitkeep
|
||||
backend/data/backups/*
|
||||
!backend/data/backups/.gitkeep
|
||||
backend/data/*.db
|
||||
backend/data/*.zip
|
||||
backend/data/*.tar.gz
|
||||
backend/data/*
|
||||
!backend/data/.gitkeep
|
||||
!backend/data/uploads/
|
||||
!backend/data/backups/
|
||||
|
||||
# Python
|
||||
.venv/
|
||||
backend/.venv/
|
||||
.pytest_cache/
|
||||
@@ -19,10 +22,21 @@ __pycache__/
|
||||
**/__pycache__/
|
||||
**/*.pyc
|
||||
*.pyc
|
||||
|
||||
# Frontend
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
frontend/*.tsbuildinfo
|
||||
*.tsbuildinfo
|
||||
**/*.tsbuildinfo
|
||||
|
||||
# Archives
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
|
||||
# Environment & OS
|
||||
.env
|
||||
*.env.local
|
||||
.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)
|
||||
VENV_BIN := .venv/Scripts
|
||||
@@ -27,3 +27,6 @@ install:
|
||||
$(PYTHON_SYS) -m venv backend/.venv
|
||||
"backend/$(VENV_BIN)/pip" install -r backend/requirements.txt
|
||||
cd frontend && npm install
|
||||
|
||||
package:
|
||||
git archive --format=zip --output=../poona-ams-delivery.zip HEAD
|
||||
|
||||
@@ -31,6 +31,15 @@ def get_current_user(
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if user is None or not user.is_active:
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -38,7 +38,10 @@ def run_sqlite_migrations(engine: Engine) -> None:
|
||||
for col in table.columns:
|
||||
if col.name not in existing_cols:
|
||||
col_type = col.type.compile(engine.dialect)
|
||||
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} {col_type}"
|
||||
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:
|
||||
|
||||
@@ -1,9 +1,77 @@
|
||||
from datetime import timedelta
|
||||
import bcrypt
|
||||
from fastapi import HTTPException, status
|
||||
from jose import JWTError, jwt
|
||||
from .config import settings
|
||||
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:
|
||||
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:
|
||||
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)
|
||||
to_encode["exp"] = expire
|
||||
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
|
||||
@@ -67,6 +67,7 @@ class User(Base):
|
||||
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
role: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
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)
|
||||
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)
|
||||
|
||||
@@ -6,7 +6,7 @@ from sqlalchemy.orm import Session, joinedload
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.security import create_access_token, hash_password, verify_password
|
||||
from ..core.security import create_access_token, hash_password, validate_password, verify_password
|
||||
from ..models.masters import User
|
||||
from ..schemas.auth import LoginRequest, TokenResponse, UserOut
|
||||
from ..services.settings_service import get_demo_as_of_date
|
||||
@@ -17,7 +17,7 @@ router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
class ChangePasswordRequest(BaseModel):
|
||||
current_password: str
|
||||
new_password: str = Field(..., min_length=6)
|
||||
new_password: str = Field(..., max_length=128)
|
||||
|
||||
MAX_LOGIN_ATTEMPTS = 15
|
||||
LOGIN_WINDOW_SECONDS = 60.0
|
||||
@@ -83,7 +83,11 @@ def login(payload: LoginRequest, request: Request, db: Session = Depends(get_db)
|
||||
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(
|
||||
access_token=token,
|
||||
token_type="bearer",
|
||||
@@ -110,12 +114,24 @@ def change_password(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Current password is incorrect.",
|
||||
)
|
||||
new_pass = payload.new_password.strip()
|
||||
if len(new_pass) < 6:
|
||||
if payload.new_password == payload.current_password:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="New password must be at least 6 characters.",
|
||||
detail="New password must be different.",
|
||||
)
|
||||
current_user.password_hash = hash_password(new_pass)
|
||||
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()
|
||||
return {"message": "Password changed successfully."}
|
||||
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",
|
||||
}
|
||||
|
||||
@@ -243,6 +243,22 @@ def create_contract(
|
||||
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.")
|
||||
|
||||
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(
|
||||
asset_id=payload.asset_id,
|
||||
contract_type=payload.contract_type,
|
||||
|
||||
@@ -33,6 +33,7 @@ from ..services.calculations import (
|
||||
coverage_status,
|
||||
)
|
||||
from ..services.permissions import Role
|
||||
from ..services.scoping import resolve_department_scope
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/dashboard", tags=["dashboard"])
|
||||
@@ -46,17 +47,55 @@ def get_dashboard_summary(
|
||||
today = effective_today(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
|
||||
if current_user.role == Role.department_user.value:
|
||||
if current_user.department_id is not None:
|
||||
scoped_dept_id = current_user.department_id
|
||||
dept_obj = db.query(Department).filter(Department.id == scoped_dept_id).first()
|
||||
dept_scope_name = dept_obj.name if dept_obj else None
|
||||
else:
|
||||
# Department user with unassigned department must see zero scope, never hospital-wide
|
||||
scoped_dept_id = -1
|
||||
dept_scope_name = "Unassigned Department"
|
||||
if scoped_dept_id is not None:
|
||||
dept_obj = db.query(Department).filter(Department.id == scoped_dept_id).first()
|
||||
dept_scope_name = dept_obj.name if dept_obj else None
|
||||
|
||||
# Settings for dynamic calculations
|
||||
cal_lead = int(
|
||||
|
||||
@@ -2,7 +2,7 @@ from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
@@ -200,6 +200,17 @@ def create_insurance_policy(
|
||||
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
|
||||
pol = InsurancePolicy(
|
||||
asset_id=payload.asset_id,
|
||||
|
||||
@@ -6,6 +6,7 @@ from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..models import Asset, Complaint, User
|
||||
from ..services.permissions import Role
|
||||
from ..services.scoping import resolve_department_scope
|
||||
|
||||
router = APIRouter(prefix="/search", tags=["search"])
|
||||
|
||||
@@ -20,8 +21,11 @@ def global_search(
|
||||
if not term:
|
||||
return {"assets": [], "complaints": []}
|
||||
|
||||
scope = resolve_department_scope(current_user)
|
||||
if scope.is_empty:
|
||||
return {"assets": [], "complaints": []}
|
||||
|
||||
pattern = f"%{term}%"
|
||||
is_dept_scoped = current_user.role == Role.department_user.value
|
||||
|
||||
asset_q = db.query(Asset).options(joinedload(Asset.department)).filter(
|
||||
or_(
|
||||
@@ -30,8 +34,8 @@ def global_search(
|
||||
Asset.serial_no.ilike(pattern),
|
||||
)
|
||||
)
|
||||
if is_dept_scoped:
|
||||
asset_q = asset_q.filter(Asset.department_id == current_user.department_id)
|
||||
if scope.department_id is not None:
|
||||
asset_q = asset_q.filter(Asset.department_id == scope.department_id)
|
||||
assets = asset_q.order_by(Asset.asset_code.asc()).limit(8).all()
|
||||
|
||||
complaint_q = (
|
||||
@@ -47,8 +51,8 @@ def global_search(
|
||||
)
|
||||
)
|
||||
)
|
||||
if is_dept_scoped:
|
||||
complaint_q = complaint_q.filter(Asset.department_id == current_user.department_id)
|
||||
if scope.department_id is not None:
|
||||
complaint_q = complaint_q.filter(Asset.department_id == scope.department_id)
|
||||
complaints = (
|
||||
complaint_q.order_by(Complaint.registered_at.desc(), Complaint.id.desc())
|
||||
.limit(8)
|
||||
|
||||
@@ -6,7 +6,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
from ..core.db import get_db
|
||||
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 ..schemas.masters import (
|
||||
PaginatedOut,
|
||||
@@ -21,7 +21,7 @@ router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
class ResetPasswordRequest(BaseModel):
|
||||
new_password: str = Field(..., min_length=6)
|
||||
new_password: str = Field(..., max_length=128)
|
||||
|
||||
|
||||
def _user_list_out(user: User) -> UserListOut:
|
||||
@@ -93,6 +93,8 @@ def create_user(
|
||||
if dept is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
|
||||
validate_password(payload.password, email=payload.email)
|
||||
|
||||
user = User(
|
||||
name=payload.name.strip(),
|
||||
email=payload.email.strip().lower(),
|
||||
@@ -175,13 +177,10 @@ def update_user(
|
||||
data["email"] = data["email"].strip().lower()
|
||||
|
||||
password = data.pop("password", None)
|
||||
if password is not None and password.strip():
|
||||
if len(password) < 4:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must be at least 4 characters.",
|
||||
)
|
||||
if password is not None and password != "":
|
||||
validate_password(password, email=data.get("email", user.email))
|
||||
user.password_hash = hash_password(password)
|
||||
user.token_version = (user.token_version or 0) + 1
|
||||
|
||||
for k, v in data.items():
|
||||
setattr(user, k, v)
|
||||
@@ -243,12 +242,8 @@ def reset_user_password(
|
||||
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.")
|
||||
new_pass = payload.new_password.strip()
|
||||
if len(new_pass) < 6:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Password must be at least 6 characters.",
|
||||
)
|
||||
user.password_hash = hash_password(new_pass)
|
||||
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."}
|
||||
|
||||
@@ -123,7 +123,7 @@ class VendorOut(BaseModel):
|
||||
class UserCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=150)
|
||||
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
|
||||
department_id: Optional[int] = None
|
||||
is_active: bool = True
|
||||
|
||||
@@ -69,7 +69,7 @@ def build_import_template_xlsx(db: Session) -> BytesIO:
|
||||
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))}2"
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(IMPORT_COLUMNS))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
departments = (
|
||||
@@ -125,11 +125,17 @@ def build_import_template_xlsx(db: Session) -> BytesIO:
|
||||
"false",
|
||||
"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)
|
||||
|
||||
# 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.row_dimensions[1].height = 26
|
||||
ref.views.sheetView[0].showGridLines = True
|
||||
@@ -272,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.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
) 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)
|
||||
if not header_cells:
|
||||
return []
|
||||
|
||||
@@ -73,7 +73,7 @@ def build_contracts_template_xlsx(db: Session) -> BytesIO:
|
||||
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))}2"
|
||||
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()
|
||||
@@ -91,11 +91,17 @@ def build_contracts_template_xlsx(db: Session) -> BytesIO:
|
||||
"Comprehensive maintenance with all spare parts included",
|
||||
"Annual contract renewal",
|
||||
]
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Reference sheet
|
||||
# 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
|
||||
@@ -151,7 +157,7 @@ def build_calibration_template_xlsx(db: Session) -> BytesIO:
|
||||
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))}2"
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
assets = (
|
||||
@@ -176,11 +182,17 @@ def build_calibration_template_xlsx(db: Session) -> BytesIO:
|
||||
"ISO/IEC 17025 accredited",
|
||||
"Annual calibration plan",
|
||||
]
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Reference sheet
|
||||
# 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
|
||||
@@ -238,7 +250,7 @@ def build_insurance_template_xlsx(db: Session) -> BytesIO:
|
||||
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))}2"
|
||||
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()
|
||||
@@ -254,11 +266,17 @@ def build_insurance_template_xlsx(db: Session) -> BytesIO:
|
||||
18500,
|
||||
"Annual hospital equipment comprehensive policy",
|
||||
]
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Reference sheet
|
||||
# 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
|
||||
@@ -376,7 +394,7 @@ def _extract_rows(filename: str, content: bytes, sheet_name: str | None = None)
|
||||
code="INVALID_FILE_TYPE",
|
||||
) from exc
|
||||
|
||||
ws = wb[sheet_name] if sheet_name and sheet_name 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)
|
||||
if not header_cells:
|
||||
return []
|
||||
@@ -430,6 +448,12 @@ def process_contracts_import(
|
||||
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]] = []
|
||||
@@ -483,6 +507,16 @@ def process_contracts_import(
|
||||
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)
|
||||
@@ -592,7 +626,7 @@ def process_calibration_import(
|
||||
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: set[int] = set()
|
||||
seen_asset_ids: dict[int, int] = {}
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||
vendor_lookup: dict[str, Vendor] = {}
|
||||
@@ -627,12 +661,13 @@ def process_calibration_import(
|
||||
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 existing_plan_asset_ids:
|
||||
row_errors.append(f"Calibration plan already exists for asset '{asset_code}'")
|
||||
elif target_asset.id in seen_asset_ids:
|
||||
row_errors.append(f"Duplicate calibration plan for asset '{asset_code}' in upload file")
|
||||
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.add(target_asset.id)
|
||||
seen_asset_ids[target_asset.id] = row_idx
|
||||
|
||||
freq_months, f_err = _parse_positive_int(freq_val, "frequency_months")
|
||||
if f_err:
|
||||
@@ -777,6 +812,13 @@ def process_insurance_import(
|
||||
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]] = []
|
||||
@@ -820,6 +862,15 @@ def process_insurance_import(
|
||||
|
||||
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:
|
||||
|
||||
@@ -37,6 +37,7 @@ from .calculations import (
|
||||
coverage_status,
|
||||
)
|
||||
from .permissions import Role
|
||||
from .scoping import resolve_department_scope
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
_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]:
|
||||
if user.role == Role.department_user.value:
|
||||
return user.department_id
|
||||
return requested_dept_id
|
||||
scope = resolve_department_scope(user, requested_dept_id)
|
||||
return scope.department_id
|
||||
|
||||
|
||||
def _clean_filters(**kwargs: Any) -> dict[str, Any]:
|
||||
@@ -76,7 +76,8 @@ def _build_monthly_maintenance(
|
||||
today = effective_today(db)
|
||||
eff_now = effective_now_utc(db)
|
||||
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")
|
||||
|
||||
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"))
|
||||
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))
|
||||
if dept_id is not None:
|
||||
dept_q = dept_q.filter(Department.id == dept_id)
|
||||
@@ -230,7 +274,33 @@ def _build_monthly_department(
|
||||
) -> dict[str, Any]:
|
||||
today = effective_today(db)
|
||||
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)
|
||||
next_month_start = add_months(month_start, 1)
|
||||
@@ -326,7 +396,31 @@ def _build_daily_visit(
|
||||
|
||||
date_from = params.get("date_from")
|
||||
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(
|
||||
joinedload(DepartmentVisit.department),
|
||||
@@ -396,7 +490,8 @@ def _build_breakdown_complaints(
|
||||
user: User,
|
||||
params: 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_to = params.get("date_to")
|
||||
asset_id = params.get("asset_id")
|
||||
@@ -404,6 +499,46 @@ def _build_breakdown_complaints(
|
||||
call_status = params.get("call_status")
|
||||
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"))
|
||||
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
|
||||
eff_now = effective_now_utc(db)
|
||||
@@ -527,13 +662,54 @@ def _build_pm_compliance(
|
||||
params: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
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")
|
||||
date_from = params.get("date_from")
|
||||
date_to = params.get("date_to")
|
||||
asset_id = params.get("asset_id")
|
||||
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))
|
||||
outsourced_lead = int(get_setting_value(db, "pm_outsourced_lead_days", 15))
|
||||
red_days = int(get_setting_value(db, "red_threshold_days", 7))
|
||||
@@ -643,13 +819,48 @@ def _build_calibration_due(
|
||||
params: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
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_to = params.get("due_to")
|
||||
asset_id = params.get("asset_id")
|
||||
agency_id = params.get("agency_id")
|
||||
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(
|
||||
get_setting_value(
|
||||
db,
|
||||
@@ -747,12 +958,48 @@ def _build_contracts_warranty(
|
||||
params: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
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")
|
||||
record_kind = params.get("record_kind") or "all"
|
||||
status_filter = params.get("status")
|
||||
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(
|
||||
get_setting_value(
|
||||
db,
|
||||
@@ -889,12 +1136,46 @@ def _build_demo_equipment(
|
||||
params: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
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")
|
||||
status_filter = params.get("status")
|
||||
date_from = params.get("date_from")
|
||||
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(
|
||||
joinedload(DemoEquipment.supplier),
|
||||
joinedload(DemoEquipment.department),
|
||||
@@ -976,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]]] = {
|
||||
"monthly-maintenance": _build_monthly_maintenance,
|
||||
"monthly-department": _build_monthly_department,
|
||||
@@ -985,6 +1365,23 @@ REPORT_BUILDERS: dict[str, Callable[[Session, User, dict[str, Any]], dict[str, A
|
||||
"calibration-due": _build_calibration_due,
|
||||
"contracts-warranty": _build_contracts_warranty,
|
||||
"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,
|
||||
)
|
||||
+139
-61
@@ -5,7 +5,7 @@ Database & Attachments Backup and Disaster Recovery Utility.
|
||||
|
||||
Features:
|
||||
- Online SQLite backup via sqlite3.Connection.backup (transactionally consistent, no locks)
|
||||
- Bundles ams.db + uploads/ directory into a single timestamped ZIP archive
|
||||
- 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
|
||||
@@ -15,12 +15,13 @@ import argparse
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sqlite3
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -30,20 +31,45 @@ logging.basicConfig(
|
||||
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"
|
||||
|
||||
# Support DATABASE_URL environment variable if set (e.g. sqlite:///./data/ams.db or sqlite:///data/ams.db)
|
||||
db_url = os.environ.get("DATABASE_URL", "").strip()
|
||||
if db_url.startswith("sqlite:///"):
|
||||
sqlite_file = db_url.replace("sqlite:///", "").lstrip("./")
|
||||
db_path = Path(sqlite_file)
|
||||
if not db_path.is_absolute():
|
||||
db_path = backend_dir / sqlite_file
|
||||
else:
|
||||
db_path = data_dir / "ams.db"
|
||||
db_path = get_db_path(db_url, backend_dir)
|
||||
|
||||
upload_env = os.environ.get("UPLOAD_DIR", "").strip()
|
||||
if upload_env:
|
||||
@@ -78,20 +104,35 @@ def verify_sqlite_db(db_file: Path) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def run_backup(
|
||||
db_path: Path,
|
||||
uploads_dir: Path,
|
||||
backups_dir: Path,
|
||||
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 ZIP archive."""
|
||||
"""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
|
||||
|
||||
backups_dir.mkdir(parents=True, exist_ok=True)
|
||||
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")
|
||||
backup_zip_path = backups_dir / f"ams_backup_{timestamp}.zip"
|
||||
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"
|
||||
@@ -110,32 +151,47 @@ def run_backup(
|
||||
logger.error("Integrity check failed on temporary backup. Aborting.")
|
||||
return None
|
||||
|
||||
# 3. Create ZIP archive
|
||||
logger.info("Creating backup archive: %s", backup_zip_path)
|
||||
with zipfile.ZipFile(backup_zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||
# Add database file
|
||||
zf.write(temp_db_path, arcname="ams.db")
|
||||
# 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)
|
||||
|
||||
# Add uploads directory
|
||||
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_zip_path.stat().st_size / (1024 * 1024)
|
||||
logger.info("Backup successfully completed! File: %s (%.2f MB)", backup_zip_path, size_mb)
|
||||
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(
|
||||
backups_dir.glob("ams_backup_*.zip"),
|
||||
list(target_dir.glob("ams_backup_*.tar.gz")) + list(target_dir.glob("ams_backup_*.zip")),
|
||||
key=lambda p: p.stat().st_mtime,
|
||||
reverse=True,
|
||||
)
|
||||
@@ -147,36 +203,45 @@ def run_backup(
|
||||
except OSError as e:
|
||||
logger.warning("Failed to remove old backup %s: %s", old_backup, e)
|
||||
|
||||
return backup_zip_path
|
||||
return backup_file_path
|
||||
|
||||
|
||||
run_backup = create_backup
|
||||
|
||||
|
||||
def run_restore(
|
||||
backup_zip: Path,
|
||||
backup_archive: Path,
|
||||
db_path: Path,
|
||||
uploads_dir: Path,
|
||||
) -> bool:
|
||||
"""Restore database and uploads from a backup ZIP file with pre-restore safety copy."""
|
||||
if not backup_zip.exists():
|
||||
logger.error("Backup archive %s not found.", backup_zip)
|
||||
"""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_zip)
|
||||
logger.info("Restoring from archive: %s", backup_archive)
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Extract archive
|
||||
try:
|
||||
with zipfile.ZipFile(backup_zip, "r") as zf:
|
||||
zf.extractall(temp_dir)
|
||||
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 zip: %s", e)
|
||||
logger.error("Failed to read backup archive: %s", e)
|
||||
return False
|
||||
|
||||
extracted_db = Path(temp_dir) / "ams.db"
|
||||
if not extracted_db.exists():
|
||||
logger.error("Archive does not contain ams.db. Invalid backup.")
|
||||
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 ams.db failed integrity verification. Aborting restore.")
|
||||
logger.error("Restored database failed integrity verification. Aborting restore.")
|
||||
return False
|
||||
|
||||
# Safety backup of current db if exists
|
||||
@@ -221,26 +286,27 @@ def main() -> int:
|
||||
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 ZIP archive")
|
||||
restore_parser.add_argument("archive", type=Path, help="Path to backup zip archive")
|
||||
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 ZIP archive or .db file to verify")
|
||||
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 = run_backup(default_db, default_uploads, default_backups, keep_count=7)
|
||||
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 = run_backup(args.db, args.uploads, args.dest, keep_count=args.keep)
|
||||
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":
|
||||
@@ -249,19 +315,32 @@ def main() -> int:
|
||||
|
||||
if args.command == "verify":
|
||||
target = args.target
|
||||
if target.suffix == ".zip":
|
||||
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:
|
||||
if "ams.db" not in zf.namelist():
|
||||
logger.error("ZIP does not contain ams.db")
|
||||
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("ams.db", td)
|
||||
db_file = Path(td) / "ams.db"
|
||||
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 .zip archive or .db file")
|
||||
logger.error("Target must be a .tar.gz/.zip archive or .db file")
|
||||
return 1
|
||||
|
||||
return 0
|
||||
@@ -269,4 +348,3 @@ def main() -> int:
|
||||
|
||||
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"]
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(res.content))
|
||||
assert "Assets" in wb.sheetnames
|
||||
assert "Master Reference" in wb.sheetnames
|
||||
assert wb.sheetnames == ["Assets", "Example", "Master Reference"]
|
||||
assert wb["Example"].cell(row=1, column=1).value == "Example only - this sheet is ignored on import"
|
||||
ws = wb["Assets"]
|
||||
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"]
|
||||
@@ -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
|
||||
tmpl_res = client.get("/api/assets/import-template", headers=bio_headers)
|
||||
wb_tmpl = openpyxl.load_workbook(BytesIO(tmpl_res.content))
|
||||
ws_tmpl = wb_tmpl["Assets"]
|
||||
headers = [ws_tmpl.cell(row=1, column=i).value for i in range(1, 16)]
|
||||
ws_tmpl = wb_tmpl["Example"]
|
||||
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
|
||||
dept_code = ws_tmpl.cell(row=2, column=5).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,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
|
||||
@@ -16,6 +16,14 @@ This matrix maps the requirements defined in Section 10 ("Acceptance Criteria")
|
||||
| **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 |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -36,3 +36,20 @@ Items marked "to be confirmed" or left flexible in the proposal are recorded her
|
||||
- `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.
|
||||
|
||||
+7
-2
@@ -12,6 +12,8 @@ The System Administrator oversees system security, reference masters, user acces
|
||||
|
||||
### 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
|
||||
@@ -19,8 +21,10 @@ The System Administrator oversees system security, reference masters, user acces
|
||||
- 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 Asset Import**: Upload `.xlsx` or `.csv` files using the hospital standard template with pre-import validation preview.
|
||||
- **Database Backup & Recovery**: Execute `python scripts/backup.py backup` to create a safe online snapshot of the database and uploaded attachments.
|
||||
- **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.
|
||||
|
||||
---
|
||||
|
||||
@@ -51,6 +55,7 @@ Department Users (Nurses, In-charges, Technicians) raise and monitor breakdown c
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -26,8 +26,14 @@ export function fetchMeApi() {
|
||||
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<{ message: string }>("/auth/change-password", {
|
||||
return api.post<ChangePasswordResponse>("/auth/change-password", {
|
||||
current_password,
|
||||
new_password,
|
||||
});
|
||||
|
||||
@@ -153,6 +153,8 @@ export const usersApi = {
|
||||
}>
|
||||
) => api.patch<MasterUser>(`/users/${id}`, data),
|
||||
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 {
|
||||
|
||||
@@ -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 });
|
||||
@@ -5,6 +5,7 @@ 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;
|
||||
@@ -43,8 +44,8 @@ export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps)
|
||||
setErrorMsg("Please enter your current password.");
|
||||
return;
|
||||
}
|
||||
if (!newPassword || newPassword.length < 6) {
|
||||
setErrorMsg("New password must be at least 6 characters.");
|
||||
if (!newPassword || newPassword.length < 8) {
|
||||
setErrorMsg("New password must be at least 8 characters.");
|
||||
return;
|
||||
}
|
||||
if (newPassword !== confirmPassword) {
|
||||
@@ -55,6 +56,9 @@ export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps)
|
||||
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) {
|
||||
@@ -73,7 +77,7 @@ export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps)
|
||||
if (!next) handleClose();
|
||||
}}
|
||||
title="Change Password"
|
||||
description="Update your account login password. Password must be at least 6 characters long."
|
||||
description="Update your account login password."
|
||||
className="max-w-md"
|
||||
>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
@@ -122,9 +126,9 @@ export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps)
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
required
|
||||
minLength={6}
|
||||
minLength={8}
|
||||
autoComplete="new-password"
|
||||
placeholder="At least 6 characters"
|
||||
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
|
||||
@@ -136,6 +140,7 @@ export function ChangePasswordModal({ open, onClose }: ChangePasswordModalProps)
|
||||
{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">
|
||||
|
||||
@@ -8,6 +8,7 @@ interface AuthState {
|
||||
demoAsOfDate: string | null;
|
||||
hydrating: boolean;
|
||||
setAuth: (user: UserOut, token: string) => void;
|
||||
setToken: (token: string) => void;
|
||||
setDemoAsOfDate: (date: string | null) => void;
|
||||
hydrate: () => Promise<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) => {
|
||||
set((state) => ({
|
||||
demoAsOfDate: date || null,
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { useState, useMemo } from "react";
|
||||
import { useState, useMemo, useEffect } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
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 { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Modal } from "@/components/ui/dialog";
|
||||
import { ApiError } from "@/api/client";
|
||||
import { ROLE_LABELS, type Role } from "@/lib/permissions";
|
||||
import { useAuthStore } from "@/hooks/useAuth";
|
||||
import { toast } from "@/lib/toast";
|
||||
import {
|
||||
departmentsApi,
|
||||
locationsApi,
|
||||
@@ -425,8 +427,8 @@ function buildUserSchema(isEdit: boolean) {
|
||||
role: z.enum(["system_admin", "biomedical", "department_user", "management", "coordinator"]),
|
||||
department_id: z.string().optional(),
|
||||
password: isEdit
|
||||
? z.string().refine((v) => v === "" || v.length >= 6, "Password must be at least 6 characters")
|
||||
: z.string().min(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(8, "Password must be at least 8 characters"),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -530,6 +532,7 @@ function UserModal({
|
||||
{editing ? "New Password (leave blank to keep current)" : "Password *"}
|
||||
</label>
|
||||
<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>}
|
||||
</div>
|
||||
<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 ---
|
||||
export function MastersPage() {
|
||||
const qc = useQueryClient();
|
||||
@@ -553,6 +663,8 @@ export function MastersPage() {
|
||||
const [editingCat, setEditingCat] = useState<Category | null>(null);
|
||||
const [editingVendor, setEditingVendor] = useState<Vendor | null>(null);
|
||||
const [editingUser, setEditingUser] = useState<MasterUser | null>(null);
|
||||
const [resetPasswordUser, setResetPasswordUser] = useState<MasterUser | null>(null);
|
||||
const { user: currentUser } = useAuthStore();
|
||||
|
||||
const deptsQuery = useQuery({
|
||||
queryKey: ["departments", includeInactive],
|
||||
@@ -805,17 +917,30 @@ export function MastersPage() {
|
||||
enableSorting: false,
|
||||
enableColumnFilter: false,
|
||||
cell: ({ row }) => (
|
||||
<RowActions
|
||||
active={row.original.is_active}
|
||||
busy={toggleMutation.isPending}
|
||||
onEdit={() => {
|
||||
setEditingUser(row.original);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
onToggleActive={() =>
|
||||
toggleMutation.mutate({ tab: "users", id: row.original.id, currentlyActive: row.original.is_active })
|
||||
}
|
||||
/>
|
||||
<div className="flex items-center gap-1.5" onClick={(e) => e.stopPropagation()}>
|
||||
<RowActions
|
||||
active={row.original.is_active}
|
||||
busy={toggleMutation.isPending}
|
||||
onEdit={() => {
|
||||
setEditingUser(row.original);
|
||||
setModalOpen(true);
|
||||
}}
|
||||
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}
|
||||
/>
|
||||
)}
|
||||
{resetPasswordUser && (
|
||||
<ResetPasswordModal
|
||||
user={resetPasswordUser}
|
||||
onClose={() => setResetPasswordUser(null)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user